test.cc 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144
  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. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // Failures of the services that the *_Online tests reach, unrelated to the
  145. // client under test: httpbingo.org intermittently answers with gateway errors,
  146. // and badssl.com drops connections from CI runners before it sends its
  147. // certificate. A handshake that fails before any verdict on the certificate is
  148. // left to the tests against local servers.
  149. static bool is_service_failure(const Result &res) {
  150. if (res) {
  151. return res->status == StatusCode::BadGateway_502 ||
  152. res->status == StatusCode::ServiceUnavailable_503 ||
  153. res->status == StatusCode::GatewayTimeout_504;
  154. }
  155. return res.error() == Error::SSLConnection;
  156. }
  157. template <typename F> static Result retry_service_failures(F &&send) {
  158. auto res = send();
  159. for (auto wait : {1, 2}) {
  160. if (!is_service_failure(res)) { break; }
  161. std::this_thread::sleep_for(std::chrono::seconds(wait));
  162. res = send();
  163. }
  164. return res;
  165. }
  166. #define SKIP_ON_SERVICE_FAILURE(res) \
  167. do { \
  168. if (is_service_failure(res)) { \
  169. if (res) { \
  170. GTEST_SKIP() << "service failure: status " << (res)->status; \
  171. } else { \
  172. GTEST_SKIP() << "service failure: " << to_string((res).error()); \
  173. } \
  174. } \
  175. } while (0)
  176. class UnixSocketTest : public ::testing::Test {
  177. protected:
  178. void TearDown() override { std::remove(pathname_.c_str()); }
  179. void client_GET(const std::string &addr) {
  180. httplib::Client cli{addr};
  181. cli.set_address_family(AF_UNIX);
  182. ASSERT_TRUE(cli.is_valid());
  183. const auto &result = cli.Get(pattern_);
  184. ASSERT_TRUE(result) << "error: " << result.error();
  185. const auto &resp = result.value();
  186. EXPECT_EQ(resp.status, StatusCode::OK_200);
  187. EXPECT_EQ(resp.body, content_);
  188. }
  189. static std::string make_sock_path() {
  190. const char *shard = getenv("GTEST_SHARD_INDEX");
  191. return shard ? std::string("./httplib-server-") + shard + ".sock"
  192. : "./httplib-server.sock";
  193. }
  194. const std::string pathname_{make_sock_path()};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. // ".//x.sock", which is not taken for a URL
  215. client_GET("./" + pathname_.substr(1));
  216. }
  217. #if defined(__linux__) || \
  218. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  219. TEST_F(UnixSocketTest, PeerPid) {
  220. httplib::Server svr;
  221. std::string remote_port_val;
  222. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  223. res.set_content(content_, "text/plain");
  224. remote_port_val = std::to_string(req.remote_port);
  225. });
  226. std::thread t{[&] {
  227. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  228. }};
  229. auto se = detail::scope_exit([&] {
  230. svr.stop();
  231. t.join();
  232. ASSERT_FALSE(svr.is_running());
  233. });
  234. svr.wait_until_ready();
  235. ASSERT_TRUE(svr.is_running());
  236. client_GET(pathname_);
  237. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  238. }
  239. #endif
  240. #ifdef __linux__
  241. TEST_F(UnixSocketTest, abstract) {
  242. constexpr char svr_path[]{"\x00httplib-server.sock"};
  243. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  244. httplib::Server svr;
  245. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  246. res.set_content(content_, "text/plain");
  247. });
  248. std::thread t{[&] {
  249. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  250. }};
  251. auto se = detail::scope_exit([&] {
  252. svr.stop();
  253. t.join();
  254. ASSERT_FALSE(svr.is_running());
  255. });
  256. svr.wait_until_ready();
  257. ASSERT_TRUE(svr.is_running());
  258. client_GET(abstract_addr);
  259. }
  260. #endif
  261. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  262. httplib::Server svr;
  263. std::string received_host_header;
  264. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  265. // Capture the Host header sent by the client
  266. auto host_iter = req.headers.find("Host");
  267. if (host_iter != req.headers.end()) {
  268. received_host_header = host_iter->second;
  269. }
  270. res.set_content(content_, "text/plain");
  271. });
  272. std::thread t{[&] {
  273. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  274. }};
  275. auto se = detail::scope_exit([&] {
  276. svr.stop();
  277. t.join();
  278. ASSERT_FALSE(svr.is_running());
  279. });
  280. svr.wait_until_ready();
  281. ASSERT_TRUE(svr.is_running());
  282. // Test that Host header is automatically set to "localhost" for Unix socket
  283. // connections
  284. httplib::Client cli{pathname_};
  285. cli.set_address_family(AF_UNIX);
  286. ASSERT_TRUE(cli.is_valid());
  287. const auto &result = cli.Get(pattern_);
  288. ASSERT_TRUE(result) << "error: " << result.error();
  289. const auto &resp = result.value();
  290. EXPECT_EQ(resp.status, StatusCode::OK_200);
  291. EXPECT_EQ(resp.body, content_);
  292. // Verify that Host header was automatically set to "localhost"
  293. EXPECT_EQ(received_host_header, "localhost");
  294. }
  295. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  296. // Another socket in the working directory, which a Location can name as
  297. // its host
  298. const auto other_path = "other-" + pathname_.substr(2);
  299. httplib::Server svr;
  300. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  301. // An absolute Location naming the Host this client sends
  302. res.set_redirect("http://localhost" + pattern_);
  303. });
  304. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_redirect("http://" + other_path + pattern_);
  306. });
  307. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  308. res.set_redirect("http://mapped.test" + pattern_);
  309. });
  310. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  311. res.set_header("X-Auth", req.get_header_value("Authorization"));
  312. res.set_content(content_, "text/plain");
  313. });
  314. httplib::Server other;
  315. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  316. res.set_content("other", "text/plain");
  317. });
  318. std::thread t{[&] {
  319. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  320. }};
  321. std::thread t2{[&] {
  322. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  323. }};
  324. auto se = detail::scope_exit([&] {
  325. svr.stop();
  326. other.stop();
  327. t.join();
  328. t2.join();
  329. std::remove(other_path.c_str());
  330. });
  331. svr.wait_until_ready();
  332. other.wait_until_ready();
  333. httplib::Client cli{pathname_};
  334. cli.set_address_family(AF_UNIX);
  335. cli.set_follow_location(true);
  336. cli.set_bearer_token_auth("token");
  337. // Another host: the same socket, without the credentials
  338. auto res = cli.Get("/cross");
  339. ASSERT_TRUE(res) << "error: " << res.error();
  340. EXPECT_EQ(StatusCode::OK_200, res->status);
  341. EXPECT_EQ(content_, res->body);
  342. EXPECT_EQ("", res->get_header_value("X-Auth"));
  343. // localhost is this client's own host
  344. res = cli.Get("/redirect");
  345. ASSERT_TRUE(res) << "error: " << res.error();
  346. EXPECT_EQ(StatusCode::OK_200, res->status);
  347. EXPECT_EQ(content_, res->body);
  348. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  349. // A host the caller mapped to a socket goes there
  350. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  351. res = cli.Get("/mapped");
  352. ASSERT_TRUE(res) << "error: " << res.error();
  353. EXPECT_EQ(StatusCode::OK_200, res->status);
  354. EXPECT_EQ("other", res->body);
  355. }
  356. #ifndef _WIN32
  357. TEST(SocketStream, wait_writable_UNIX) {
  358. int fds[2];
  359. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  360. const auto asSocketStream = [&](socket_t fd,
  361. std::function<bool(Stream &)> func) {
  362. return detail::process_client_socket(
  363. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  364. };
  365. asSocketStream(fds[0], [&](Stream &s0) {
  366. EXPECT_EQ(s0.socket(), fds[0]);
  367. EXPECT_TRUE(s0.wait_writable());
  368. EXPECT_TRUE(s0.is_peer_alive());
  369. EXPECT_EQ(0, close(fds[1]));
  370. EXPECT_FALSE(s0.is_peer_alive());
  371. return true;
  372. });
  373. EXPECT_EQ(0, close(fds[0]));
  374. }
  375. TEST(SocketStream, wait_writable_INET) {
  376. sockaddr_in addr;
  377. memset(&addr, 0, sizeof(addr));
  378. addr.sin_family = AF_INET;
  379. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  380. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  381. int disconnected_svr_sock = -1;
  382. std::thread svr{[&] {
  383. const int s = socket(AF_INET, SOCK_STREAM, 0);
  384. ASSERT_LE(0, s);
  385. // PORT + 1 is shared with the SSL redirect tests and with
  386. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  387. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  388. // because that happens on a worker thread the ASSERT does not stop the
  389. // test: it runs on and fails at the disconnected_svr_sock check instead.
  390. default_socket_options(s);
  391. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  392. ASSERT_EQ(0, listen(s, 1));
  393. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  394. ASSERT_EQ(0, close(s));
  395. }};
  396. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  397. std::thread cli{[&] {
  398. const int s = socket(AF_INET, SOCK_STREAM, 0);
  399. ASSERT_LE(0, s);
  400. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  401. ASSERT_EQ(0, close(s));
  402. }};
  403. cli.join();
  404. svr.join();
  405. ASSERT_NE(disconnected_svr_sock, -1);
  406. const auto asSocketStream = [&](socket_t fd,
  407. std::function<bool(Stream &)> func) {
  408. return detail::process_client_socket(
  409. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  410. };
  411. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  412. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  413. // wait_writable() returns true because select_write() only checks if the
  414. // send buffer has space. Peer disconnection is detected later by send().
  415. EXPECT_TRUE(ss.wait_writable());
  416. return true;
  417. });
  418. ASSERT_EQ(0, close(disconnected_svr_sock));
  419. }
  420. #endif // #ifndef _WIN32
  421. TEST(SetSocketOptTest, TcpNoDelay) {
  422. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  423. ASSERT_NE(sock, INVALID_SOCKET);
  424. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  425. int val = 0;
  426. socklen_t len = sizeof(val);
  427. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  428. reinterpret_cast<char *>(&val), &len));
  429. EXPECT_NE(val, 0);
  430. detail::close_socket(sock);
  431. }
  432. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  433. // accept() reports failures through WSAGetLastError() on Windows and through
  434. // errno everywhere else. Asking the wrong one is what made the accept loop
  435. // treat every recoverable failure as fatal on Windows.
  436. struct Classification {
  437. bool resource;
  438. bool transient;
  439. };
  440. auto classify = [](int err) {
  441. #ifdef _WIN32
  442. WSASetLastError(err);
  443. #else
  444. errno = err;
  445. #endif
  446. // Read both before asserting: an assertion may clobber the error slot.
  447. Classification c;
  448. c.resource = detail::is_accept_resource_error();
  449. c.transient = detail::is_accept_transient_error();
  450. return c;
  451. };
  452. #ifdef _WIN32
  453. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  454. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  455. WSAECONNRESET, WSAECONNABORTED};
  456. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  457. #else
  458. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  459. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  460. ECONNABORTED};
  461. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  462. #endif
  463. for (auto err : resource_errors) {
  464. const auto c = classify(err);
  465. EXPECT_TRUE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. for (auto err : transient_errors) {
  469. const auto c = classify(err);
  470. EXPECT_TRUE(c.transient) << "error " << err;
  471. EXPECT_FALSE(c.resource) << "error " << err;
  472. }
  473. for (auto err : fatal_errors) {
  474. const auto c = classify(err);
  475. EXPECT_FALSE(c.resource) << "error " << err;
  476. EXPECT_FALSE(c.transient) << "error " << err;
  477. }
  478. #ifdef _WIN32
  479. WSASetLastError(0);
  480. #else
  481. errno = 0;
  482. #endif
  483. }
  484. TEST(ClientTest, MoveConstructible) {
  485. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  486. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  487. }
  488. TEST(ClientTest, MoveAssignable) {
  489. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  490. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  491. }
  492. #ifdef _WIN32
  493. TEST(StartupTest, WSAStartup) {
  494. WSADATA wsaData;
  495. int ret = WSAStartup(0x0002, &wsaData);
  496. ASSERT_EQ(0, ret);
  497. }
  498. #endif
  499. TEST(DecodePathTest, PercentCharacter) {
  500. EXPECT_EQ(
  501. decode_path_component(
  502. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  503. U8("descrip=Gastos áéíóúñÑ 6"));
  504. }
  505. TEST(DecodePathTest, PercentCharacterNUL) {
  506. string expected;
  507. expected.push_back('x');
  508. expected.push_back('\0');
  509. expected.push_back('x');
  510. EXPECT_EQ(decode_path_component("x%00x"), expected);
  511. }
  512. TEST(DecodePathTest, UnicodeEncoding) {
  513. // %u0041 = 'A' (1-byte UTF-8)
  514. EXPECT_EQ("A", decode_path_component("%u0041"));
  515. // %u00E9 = 'é' (2-byte UTF-8)
  516. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  517. // %u3042 = 'あ' (3-byte UTF-8)
  518. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  519. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  520. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  521. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  522. // neighbours)
  523. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  524. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  525. }
  526. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  527. // A sign or whitespace inside the two-character escape window must not be
  528. // accepted as a valid percent-encoding; the sequence is passed through
  529. // literally, matching decode_uri_component / decode_path_component.
  530. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  531. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  532. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  533. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  534. // Well-formed escapes still decode.
  535. EXPECT_EQ("-", decode_query_component("%2D", false));
  536. EXPECT_EQ("A", decode_query_component("%41", false));
  537. }
  538. TEST(SanitizeFilenameTest, VariousPatterns) {
  539. // Path traversal
  540. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  541. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  542. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  543. // Normal and edge cases
  544. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  545. EXPECT_EQ("filename.txt",
  546. httplib::sanitize_filename("/path/to/filename.txt"));
  547. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  548. EXPECT_EQ("", httplib::sanitize_filename(".."));
  549. EXPECT_EQ("", httplib::sanitize_filename(""));
  550. // Null bytes stripped
  551. EXPECT_EQ("safe.txt",
  552. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  553. // Whitespace-only rejected
  554. EXPECT_EQ("", httplib::sanitize_filename(" "));
  555. }
  556. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  557. // before it is dropped; anywhere else it is an ordinary file name character.
  558. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  559. #ifdef _WIN32
  560. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  561. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  562. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  563. #else
  564. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  565. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  566. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  567. #endif
  568. }
  569. // Forward declaration (see the base64_encode note below): split builds move the
  570. // definition into httplib.cc, so re-declaring it here lets the test link.
  571. namespace httplib {
  572. namespace detail {
  573. bool is_chunked_transfer_encoding(const Headers &headers);
  574. } // namespace detail
  575. } // namespace httplib
  576. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  577. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  578. auto make = [](std::initializer_list<const char *> lines) {
  579. Headers h;
  580. for (auto te : lines) {
  581. if (te) { h.emplace("Transfer-Encoding", te); }
  582. }
  583. return h;
  584. };
  585. // Sole coding, matched case-insensitively.
  586. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  587. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  588. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  589. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  590. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  593. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  595. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  596. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  597. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  598. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  599. // were received, into one list. Headers preserves that order, so the answer
  600. // is decided by the last coding of the last line and the order the lines
  601. // arrived in is significant.
  602. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  603. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  604. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  605. // The split can fall anywhere in the list.
  606. EXPECT_TRUE(
  607. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  608. EXPECT_FALSE(
  609. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  610. // A trailing line naming no coding leaves the list ending in nothing, so it
  611. // must not inherit the chunked from the line before it.
  612. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  613. }
  614. // Forward declarations (see the base64_encode note below).
  615. namespace httplib {
  616. namespace detail {
  617. bool parse_status_line(const char *line, std::string &version, int &status,
  618. std::string &reason);
  619. std::string file_extension(const std::string &path);
  620. std::string
  621. find_content_type(const std::string &path,
  622. const std::map<std::string, std::string> &user_data,
  623. const std::string &default_content_type);
  624. bool can_compress_content_type(const std::string &content_type);
  625. bool is_prohibited_header_name(const std::string &name);
  626. bool is_valid_path(const std::string &path);
  627. #ifdef CPPHTTPLIB_SSL_ENABLED
  628. bool match_hostname(const std::string &pattern, const std::string &hostname);
  629. #endif
  630. } // namespace detail
  631. } // namespace httplib
  632. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  633. struct {
  634. const char *line;
  635. const char *version;
  636. int status;
  637. const char *reason;
  638. } cases[] = {
  639. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  640. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  641. // The reason phrase may be empty, or left out along with its space.
  642. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  643. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  644. };
  645. for (const auto &c : cases) {
  646. std::string version;
  647. int status = 0;
  648. std::string reason = "unset";
  649. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  650. << c.line;
  651. EXPECT_EQ(c.version, version);
  652. EXPECT_EQ(c.status, status);
  653. EXPECT_EQ(c.reason, reason);
  654. }
  655. }
  656. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  657. const char *lines[] = {
  658. "HTTP/2 200 OK\r\n",
  659. "HTTP/1.2 200 OK\r\n",
  660. "HTTP/1.1 20 OK\r\n",
  661. "HTTP/1.1 2000 OK\r\n",
  662. "HTTP/1.1 2x0 OK\r\n",
  663. "HTTP/1.1 200 OK\r\n",
  664. "HTTP/1.1 200OK\r\n",
  665. "HTTP/1.1 200 O\rK\r\n",
  666. "HTTP/1.1 200 OK",
  667. "HTTP/1.1 200 OK\r\nX",
  668. "",
  669. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  670. "HTTP/1.1 200 OK\n",
  671. #endif
  672. };
  673. for (auto line : lines) {
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  678. << line;
  679. }
  680. }
  681. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  682. // Long enough to overflow the stack when matched with std::regex.
  683. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  684. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  685. std::string version;
  686. int status = 0;
  687. std::string reason;
  688. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  689. EXPECT_EQ(200, status);
  690. EXPECT_EQ(long_reason, reason);
  691. }
  692. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  693. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  694. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  695. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  696. EXPECT_EQ("", detail::file_extension("noext"));
  697. EXPECT_EQ("", detail::file_extension("a."));
  698. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  699. EXPECT_EQ("", detail::file_extension("a.b-c"));
  700. // Long enough to overflow the stack when matched with std::regex.
  701. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  702. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  703. }
  704. #ifdef CPPHTTPLIB_SSL_ENABLED
  705. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  706. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  707. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  708. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  709. // A wildcard needs two labels after it, in the leftmost label only
  710. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  711. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  712. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  713. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  714. EXPECT_FALSE(
  715. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  716. // No name may have an empty label
  717. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  718. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  719. }
  720. #endif
  721. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  722. detail::case_ignore::hash hash;
  723. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  724. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  725. // Long enough to overflow the stack if hashed one call per character.
  726. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  727. }
  728. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  729. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  730. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  731. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  732. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  733. // Same 26-bit hash as html, svg and js.
  734. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  735. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  736. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  737. }
  738. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  739. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  740. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  741. }
  742. }
  743. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  744. // name anywhere else.
  745. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  746. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  747. #ifdef _WIN32
  748. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  749. #else
  750. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  751. #endif
  752. }
  753. }
  754. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  755. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  756. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  757. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  758. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  759. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  760. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  761. // Same 26-bit hash as application/json.
  762. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  763. }
  764. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  765. Request req;
  766. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  767. EXPECT_TRUE(req.is_multipart_form_data());
  768. std::string boundary;
  769. EXPECT_TRUE(detail::parse_multipart_boundary(
  770. req.get_header_value("Content-Type"), boundary));
  771. EXPECT_EQ("x", boundary);
  772. }
  773. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  774. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  775. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  776. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  777. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  778. // Same 26-bit hash as REMOTE_ADDR.
  779. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  780. }
  781. // Forward declaration: in split builds split.py strips `inline` and moves the
  782. // definition into httplib.cc, so detail::base64_encode is not visible from the
  783. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  784. // in both header-only and split builds.
  785. namespace httplib {
  786. namespace detail {
  787. std::string base64_encode(const std::string &in);
  788. } // namespace detail
  789. } // namespace httplib
  790. TEST(Base64EncodeTest, KnownAnswers) {
  791. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  792. // where the accumulator's top bit is already set before the next shift.
  793. EXPECT_EQ("", detail::base64_encode(""));
  794. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  795. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  796. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  797. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  798. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  799. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  800. // High bytes keep the top bit set across several rounds.
  801. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  802. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  803. }
  804. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  805. string unescapedCharacters = "-_.!~*'()";
  806. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  807. }
  808. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  809. string reservedCharacters = ";,/?:@&=+$";
  810. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  811. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  812. }
  813. TEST(ClientQueryOrder, PreserveOrder) {
  814. // This test reproduces Issue #2259: client may reorder query parameters
  815. // when sending a GET request. The expected behavior is that the client
  816. // preserves the original query string order when the caller supplied it
  817. // as part of the path.
  818. Server svr;
  819. svr.Get("/", [&](const Request &req, Response &res) {
  820. // Echo back the raw target so the test can assert ordering
  821. res.set_content(req.target, "text/plain");
  822. });
  823. std::thread t{[&] { svr.listen(HOST, PORT); }};
  824. auto se = detail::scope_exit([&] {
  825. svr.stop();
  826. t.join();
  827. ASSERT_FALSE(svr.is_running());
  828. });
  829. svr.wait_until_ready();
  830. Client cli(HOST, PORT);
  831. ASSERT_TRUE(cli.is_valid());
  832. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  833. auto res = cli.Get(original);
  834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  835. // Expect the echoed target to exactly match the original path (order
  836. // preserved)
  837. EXPECT_EQ(res->body, original);
  838. }
  839. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  846. "%D0%B4%D0%BE%D0%BC");
  847. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  848. }
  849. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  850. string unescapedCharacters = "-_.!~*'()";
  851. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  852. }
  853. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  854. string reservedCharacters = ";,/?:@&=+$";
  855. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  856. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  857. }
  858. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  859. string chineseCharacters = U8("中国語");
  860. string russianCharacters = U8("дом");
  861. string brazilianCharacters = U8("óculos");
  862. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  863. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  864. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  865. "%D0%B4%D0%BE%D0%BC");
  866. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  867. }
  868. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  869. // Issue #2082 use case: encoding path component with ampersand
  870. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  871. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  872. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  873. }
  874. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  875. string unescapedCharacters = "-_.!~*'()";
  876. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  877. }
  878. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  879. string reservedCharacters = ";,/?:@&=+$#";
  880. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  881. }
  882. TEST(EncodeUriTest, TestUTF8Characters) {
  883. string chineseCharacters = U8("中国語");
  884. string russianCharacters = U8("дом");
  885. string brazilianCharacters = U8("óculos");
  886. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  887. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  888. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  889. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  890. }
  891. TEST(EncodeUriTest, TestCompleteUri) {
  892. string uri =
  893. "https://example.com/path/to/resource?query=value&param=test#fragment";
  894. EXPECT_EQ(
  895. httplib::encode_uri(uri),
  896. "https://example.com/path/to/resource?query=value&param=test#fragment");
  897. }
  898. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  899. string uri =
  900. "https://example.com/path with spaces/file name.html?q=hello world";
  901. EXPECT_EQ(httplib::encode_uri(uri),
  902. "https://example.com/path%20with%20spaces/"
  903. "file%20name.html?q=hello%20world");
  904. }
  905. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  906. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  908. }
  909. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  910. string unescapedCharacters = "-_.!~*'()";
  911. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  912. }
  913. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  914. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  915. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  916. string encodedBrazilian = "%C3%B3culos";
  917. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  918. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  919. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  920. }
  921. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  922. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  923. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  924. "Piri Tommy Villiers - on & on");
  925. }
  926. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  927. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  928. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  929. }
  930. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  931. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  932. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  933. }
  934. TEST(DecodeUriTest, TestUTF8Characters) {
  935. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  936. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  937. string encodedBrazilian = "%C3%B3culos";
  938. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  939. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  940. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  941. }
  942. TEST(DecodeUriTest, TestCompleteUri) {
  943. string encodedUri = "https://example.com/path%20with%20spaces/"
  944. "file%20name.html?q=hello%20world";
  945. EXPECT_EQ(
  946. httplib::decode_uri(encodedUri),
  947. "https://example.com/path with spaces/file name.html?q=hello world");
  948. }
  949. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  950. string original =
  951. "https://example.com/path with spaces/file name.html?q=hello world";
  952. string encoded = httplib::encode_uri(original);
  953. string decoded = httplib::decode_uri(encoded);
  954. EXPECT_EQ(decoded, original);
  955. }
  956. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  957. // decode_uri is the inverse of encode_uri: an escaped reserved character
  958. // stays encoded so it is not promoted into a real delimiter, while
  959. // non-reserved escapes still decode (like JS decodeURI).
  960. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  961. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  962. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  963. "%3F%3A%40%26%3D%2B%24%2C%3B");
  964. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  965. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  966. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  967. "http://example.com/a%2Fb");
  968. // decode_uri_component still decodes the reserved character.
  969. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  970. }
  971. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  972. string original = "Piri Tommy Villiers - on & on";
  973. string encoded = httplib::encode_uri_component(original);
  974. string decoded = httplib::decode_uri_component(encoded);
  975. EXPECT_EQ(decoded, original);
  976. }
  977. TEST(TrimTests, TrimStringTests) {
  978. EXPECT_EQ("abc", detail::trim_copy("abc"));
  979. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  980. EXPECT_TRUE(detail::trim_copy("").empty());
  981. }
  982. TEST(AsciiTest, LocaleIndependentClassification) {
  983. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  984. // which consult the global C locale: std::isalnum(0xC5) can return true
  985. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  986. // helpers must classify every byte by the ASCII grammar alone.
  987. for (int i = 0; i < 256; i++) {
  988. auto c = static_cast<char>(i);
  989. auto is_digit = i >= '0' && i <= '9';
  990. auto is_upper = i >= 'A' && i <= 'Z';
  991. auto is_lower = i >= 'a' && i <= 'z';
  992. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  993. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  994. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  995. << "byte " << i;
  996. }
  997. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  998. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  999. // Non-ASCII bytes must be percent-encoded, never passed through as
  1000. // alphanumeric.
  1001. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  1002. }
  1003. TEST(FromCharsTest, Double) {
  1004. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  1005. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  1006. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  1007. auto parse = [](const std::string &s, double &v) {
  1008. return detail::from_chars(s.data(), s.data() + s.size(), v);
  1009. };
  1010. double v = -1.0;
  1011. // Representative quality values.
  1012. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.0);
  1014. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 1.0);
  1016. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1017. EXPECT_DOUBLE_EQ(v, 0.8);
  1018. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 0.001);
  1020. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1021. EXPECT_DOUBLE_EQ(v, 1.0);
  1022. // A missing integer or fractional part is tolerated.
  1023. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.5);
  1025. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1026. EXPECT_DOUBLE_EQ(v, 5.0);
  1027. // Values outside [0, 1] still parse; the caller range-checks them.
  1028. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1029. EXPECT_DOUBLE_EQ(v, 123.456);
  1030. // Stops at the first byte that is not part of the number and reports where.
  1031. std::string trailing = "0.9, text/html";
  1032. auto r = parse(trailing, v);
  1033. EXPECT_EQ(r.ec, std::errc{});
  1034. EXPECT_DOUBLE_EQ(v, 0.9);
  1035. EXPECT_EQ(*r.ptr, ',');
  1036. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1037. // outright, and an 'e'/'E' simply ends the number.
  1038. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1040. std::string exp_input = "1.5e3";
  1041. r = parse(exp_input, v);
  1042. EXPECT_EQ(r.ec, std::errc{});
  1043. EXPECT_DOUBLE_EQ(v, 1.5);
  1044. EXPECT_EQ(*r.ptr, 'e');
  1045. // Invalid inputs.
  1046. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1047. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1048. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1049. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1050. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1051. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1052. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1053. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1054. std::errc{});
  1055. EXPECT_DOUBLE_EQ(v, 0.0);
  1056. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1057. std::errc{});
  1058. EXPECT_GE(v, 0.0);
  1059. EXPECT_LE(v, 1.0);
  1060. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1061. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1062. }
  1063. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1064. // Simple case without quality values
  1065. std::vector<std::string> result1;
  1066. EXPECT_TRUE(detail::parse_accept_header(
  1067. "text/html,application/json,text/plain", result1));
  1068. EXPECT_EQ(result1.size(), 3U);
  1069. EXPECT_EQ(result1[0], "text/html");
  1070. EXPECT_EQ(result1[1], "application/json");
  1071. EXPECT_EQ(result1[2], "text/plain");
  1072. // With quality values
  1073. std::vector<std::string> result2;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1076. EXPECT_EQ(result2.size(), 3U);
  1077. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1078. EXPECT_EQ(result2[1], "text/html");
  1079. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1080. }
  1081. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1082. // Mixed with and without quality values
  1083. std::vector<std::string> result;
  1084. EXPECT_TRUE(detail::parse_accept_header(
  1085. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1086. EXPECT_EQ(result.size(), 3U);
  1087. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1088. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1089. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1090. }
  1091. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1092. // Empty header
  1093. std::vector<std::string> empty_result;
  1094. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1095. EXPECT_TRUE(empty_result.empty());
  1096. // Single type
  1097. std::vector<std::string> single_result;
  1098. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1099. EXPECT_EQ(single_result.size(), 1U);
  1100. EXPECT_EQ(single_result[0], "application/json");
  1101. // Wildcard types
  1102. std::vector<std::string> wildcard_result;
  1103. EXPECT_TRUE(detail::parse_accept_header(
  1104. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1105. EXPECT_EQ(wildcard_result.size(), 3U);
  1106. EXPECT_EQ(wildcard_result[0], "application/json");
  1107. EXPECT_EQ(wildcard_result[1], "text/*");
  1108. EXPECT_EQ(wildcard_result[2], "*/*");
  1109. }
  1110. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1111. // Common browser Accept header
  1112. std::vector<std::string> browser_result;
  1113. EXPECT_TRUE(
  1114. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1115. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1116. browser_result));
  1117. EXPECT_EQ(browser_result.size(), 6U);
  1118. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1119. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1120. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1121. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1122. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1123. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1124. // API client header
  1125. std::vector<std::string> api_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1128. api_result));
  1129. EXPECT_EQ(api_result.size(), 3U);
  1130. EXPECT_EQ(api_result[0], "application/json");
  1131. EXPECT_EQ(api_result[1], "application/xml");
  1132. EXPECT_EQ(api_result[2], "text/plain");
  1133. }
  1134. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1135. // Quality value with 3 decimal places
  1136. std::vector<std::string> decimal_result;
  1137. EXPECT_TRUE(detail::parse_accept_header(
  1138. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1139. EXPECT_EQ(decimal_result.size(), 2U);
  1140. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1141. EXPECT_EQ(decimal_result[1], "text/html");
  1142. // Zero quality (should still be included but with lowest priority)
  1143. std::vector<std::string> zero_q_result;
  1144. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1145. zero_q_result));
  1146. EXPECT_EQ(zero_q_result.size(), 2U);
  1147. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1148. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1149. // No spaces around commas
  1150. std::vector<std::string> no_space_result;
  1151. EXPECT_TRUE(detail::parse_accept_header(
  1152. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1153. no_space_result));
  1154. EXPECT_EQ(no_space_result.size(), 3U);
  1155. EXPECT_EQ(no_space_result[0], "text/html");
  1156. EXPECT_EQ(no_space_result[1], "application/json");
  1157. EXPECT_EQ(no_space_result[2], "text/plain");
  1158. }
  1159. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1160. // Quality values always use '.' as the decimal separator, so parsing must
  1161. // not depend on the process locale. An embedding application may have
  1162. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1163. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1164. std::string saved = cur ? cur : "C";
  1165. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1166. "fr_FR.UTF-8"};
  1167. bool switched = false;
  1168. for (const auto loc : comma_locales) {
  1169. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1170. std::localeconv()->decimal_point[0] == ',') {
  1171. switched = true;
  1172. break;
  1173. }
  1174. }
  1175. if (!switched) {
  1176. std::setlocale(LC_NUMERIC, saved.c_str());
  1177. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1178. }
  1179. // The higher-weighted type appears later in the list, so a correct parse
  1180. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1181. // sensitive parse reads both weights as 0 and leaves the original order.
  1182. std::vector<std::string> result;
  1183. EXPECT_TRUE(detail::parse_accept_header(
  1184. "application/json;q=0.1,text/html;q=0.9", result));
  1185. ASSERT_EQ(result.size(), 2U);
  1186. EXPECT_EQ(result[0], "text/html");
  1187. EXPECT_EQ(result[1], "application/json");
  1188. std::setlocale(LC_NUMERIC, saved.c_str());
  1189. }
  1190. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1191. std::vector<std::string> result;
  1192. // Invalid quality value (> 1.0)
  1193. EXPECT_FALSE(
  1194. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1195. // Invalid quality value (< 0.0)
  1196. EXPECT_FALSE(
  1197. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1198. // Invalid quality value (not a number)
  1199. EXPECT_FALSE(detail::parse_accept_header(
  1200. "text/html;q=invalid,application/json", result));
  1201. // A valid numeric prefix does not make the entire quality value valid.
  1202. EXPECT_FALSE(detail::parse_accept_header(
  1203. "text/html;q=0.5junk,application/json", result));
  1204. // Empty quality value
  1205. EXPECT_FALSE(
  1206. detail::parse_accept_header("text/html;q=,application/json", result));
  1207. // Invalid media type format (no slash and not wildcard)
  1208. EXPECT_FALSE(
  1209. detail::parse_accept_header("invalidtype,application/json", result));
  1210. // Valid cases should still work
  1211. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1212. EXPECT_EQ(result.size(), 1U);
  1213. EXPECT_EQ(result[0], "*/*");
  1214. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1215. EXPECT_EQ(result.size(), 1U);
  1216. EXPECT_EQ(result[0], "*");
  1217. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1218. EXPECT_EQ(result.size(), 1U);
  1219. EXPECT_EQ(result[0], "text/*");
  1220. }
  1221. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1222. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1223. // and must not be answered with 400 Bad Request.
  1224. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1225. struct {
  1226. const char *value;
  1227. std::vector<std::string> expected;
  1228. } cases[] = {
  1229. {",application/json", {"application/json"}},
  1230. {"text/html,", {"text/html"}},
  1231. {"text/html,,*/*", {"text/html", "*/*"}},
  1232. // An empty element may be spelled with whitespace in it
  1233. {"text/html, , application/json", {"text/html", "application/json"}},
  1234. // Nothing but empty elements is an empty list, which means the same
  1235. // thing as no Accept header at all
  1236. {",,,", {}},
  1237. // Quality values still apply across ignored empty elements
  1238. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1239. };
  1240. for (const auto &c : cases) {
  1241. std::vector<std::string> result;
  1242. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1243. << "value: " << c.value;
  1244. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1245. }
  1246. // An invalid entry is still rejected when empty elements surround it
  1247. std::vector<std::string> result;
  1248. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1249. }
  1250. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1251. // or ';' inside one does not end the list element or the parameter. Section
  1252. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1253. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1254. struct {
  1255. const char *value;
  1256. std::vector<std::string> expected;
  1257. } cases[] = {
  1258. {"text/html;profile=\"a,b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // A "q=" inside a quoted value is not the weight
  1261. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1262. {"text/html", "application/json"}},
  1263. // The weight after a quoted value still applies
  1264. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1265. {"application/json", "text/html"}},
  1266. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1267. {"application/json", "text/html"}},
  1268. {"text/html;profile=\"a\\\"b\",application/json",
  1269. {"text/html", "application/json"}},
  1270. // An escaped backslash does not escape the '"' after it
  1271. {"text/html;profile=\"a\\\\\",application/json",
  1272. {"text/html", "application/json"}},
  1273. };
  1274. for (const auto &c : cases) {
  1275. std::vector<std::string> result;
  1276. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1277. << "value: " << c.value;
  1278. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1279. }
  1280. }
  1281. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1282. Server svr;
  1283. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1284. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1285. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1286. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1287. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1291. EXPECT_TRUE(false);
  1292. res.set_content("bad request", "text/plain");
  1293. });
  1294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. listen_thread.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. Client cli("localhost", PORT);
  1302. {
  1303. auto res = cli.Get(
  1304. "/accept_ok",
  1305. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1307. EXPECT_EQ(StatusCode::OK_200, res->status);
  1308. }
  1309. {
  1310. auto res = cli.Get("/accept_bad_request",
  1311. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1313. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1314. }
  1315. }
  1316. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1317. Server svr;
  1318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1319. res.set_content("ok", "text/plain");
  1320. });
  1321. std::atomic<int> start_count{0};
  1322. std::atomic<bool> running_when_called{false};
  1323. svr.set_start_handler([&]() {
  1324. running_when_called = svr.is_running();
  1325. start_count++;
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. std::thread t([&]() { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. // A successful request proves the accept loop is running, which the start
  1336. // handler precedes; so by now the handler must have run exactly once.
  1337. Client cli(HOST, port);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res = cli.Get("/");
  1340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(1, start_count.load());
  1343. EXPECT_TRUE(running_when_called.load());
  1344. }
  1345. TEST(DivideTest, DivideStringTests) {
  1346. auto divide = [](const std::string &str, char d) {
  1347. std::string lhs;
  1348. std::string rhs;
  1349. detail::divide(str, d,
  1350. [&](const char *lhs_data, std::size_t lhs_size,
  1351. const char *rhs_data, std::size_t rhs_size) {
  1352. lhs.assign(lhs_data, lhs_size);
  1353. rhs.assign(rhs_data, rhs_size);
  1354. });
  1355. return std::make_pair(std::move(lhs), std::move(rhs));
  1356. };
  1357. {
  1358. const auto res = divide("", '=');
  1359. EXPECT_EQ(res.first, "");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("=", '=');
  1364. EXPECT_EQ(res.first, "");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide(" ", '=');
  1369. EXPECT_EQ(res.first, " ");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("a", '=');
  1374. EXPECT_EQ(res.first, "a");
  1375. EXPECT_EQ(res.second, "");
  1376. }
  1377. {
  1378. const auto res = divide("a=", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "");
  1381. }
  1382. {
  1383. const auto res = divide("=b", '=');
  1384. EXPECT_EQ(res.first, "");
  1385. EXPECT_EQ(res.second, "b");
  1386. }
  1387. {
  1388. const auto res = divide("a=b", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b");
  1391. }
  1392. {
  1393. const auto res = divide("a=b=", '=');
  1394. EXPECT_EQ(res.first, "a");
  1395. EXPECT_EQ(res.second, "b=");
  1396. }
  1397. {
  1398. const auto res = divide("a=b=c", '=');
  1399. EXPECT_EQ(res.first, "a");
  1400. EXPECT_EQ(res.second, "b=c");
  1401. }
  1402. }
  1403. TEST(SplitTest, ParseQueryString) {
  1404. string s = "key1=val1&key2=val2&key3=val3";
  1405. Params dic;
  1406. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1407. [&](const char *b, const char *e) {
  1408. string key, val;
  1409. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1410. if (key.empty()) {
  1411. key.assign(b2, e2);
  1412. } else {
  1413. val.assign(b2, e2);
  1414. }
  1415. });
  1416. dic.emplace(key, val);
  1417. });
  1418. EXPECT_EQ("val1", dic.find("key1")->second);
  1419. EXPECT_EQ("val2", dic.find("key2")->second);
  1420. EXPECT_EQ("val3", dic.find("key3")->second);
  1421. }
  1422. TEST(SplitTest, ParseInvalidQueryTests) {
  1423. {
  1424. string s = " ";
  1425. Params dict;
  1426. detail::parse_query_text(s, dict);
  1427. EXPECT_TRUE(dict.empty());
  1428. }
  1429. {
  1430. string s = " = =";
  1431. Params dict;
  1432. detail::parse_query_text(s, dict);
  1433. EXPECT_TRUE(dict.empty());
  1434. }
  1435. }
  1436. TEST(ParseQueryTest, ParseQueryString) {
  1437. {
  1438. std::string s = "key1=val1&key2=val2&key3=val3";
  1439. Params dic;
  1440. detail::parse_query_text(s, dic);
  1441. EXPECT_EQ("val1", dic.find("key1")->second);
  1442. EXPECT_EQ("val2", dic.find("key2")->second);
  1443. EXPECT_EQ("val3", dic.find("key3")->second);
  1444. }
  1445. {
  1446. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1447. Params dic;
  1448. detail::parse_query_text(s, dic);
  1449. EXPECT_EQ("", dic.find("key1")->second);
  1450. EXPECT_EQ("val1", dic.find("key2")->second);
  1451. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1452. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1453. }
  1454. }
  1455. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1456. Params dic;
  1457. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1458. dic.emplace("key1", "val1");
  1459. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1460. dic.emplace("key2", "val2");
  1461. dic.emplace("key3", "val3");
  1462. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1463. }
  1464. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1465. Params params;
  1466. params.emplace("a", "1");
  1467. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1468. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1469. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1470. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1471. // Long enough to overflow the stack when matched with std::regex.
  1472. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1473. EXPECT_EQ("/p?" + long_query + "&a=1",
  1474. append_query_params("/p?" + long_query, params));
  1475. }
  1476. // Joins every entry of a Headers or Params into "key=value " so a whole
  1477. // traversal can be compared in one assertion. Both are instantiations of the
  1478. // same insertion-ordered container, so one helper serves both.
  1479. template <typename Map> static std::string entries_to_string(const Map &m) {
  1480. std::string s;
  1481. for (const auto &entry : m) {
  1482. s += entry.first + "=" + entry.second + " ";
  1483. }
  1484. return s;
  1485. }
  1486. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1487. // Params used to be a std::multimap, which sorted by name and handed the
  1488. // caller's query back alphabetised. A client signing its query string could
  1489. // not reproduce the order it asked for.
  1490. Params dic;
  1491. dic.emplace("zulu", "1");
  1492. dic.emplace("alpha", "2");
  1493. dic.emplace("mike", "3");
  1494. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1495. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1496. }
  1497. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1498. Params dic;
  1499. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1500. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1501. }
  1502. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1503. Request req;
  1504. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1505. req.params);
  1506. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1507. EXPECT_EQ("first", req.get_param_value("tag"));
  1508. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1509. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1510. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1511. EXPECT_EQ("", req.get_param_value("tag", 3));
  1512. }
  1513. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1514. // Params shares its container with Headers, which matches field names
  1515. // case-insensitively. Parameter names must not pick that up.
  1516. Params dic;
  1517. dic.emplace("Key", "upper");
  1518. dic.emplace("key", "lower");
  1519. EXPECT_EQ(2U, dic.size());
  1520. EXPECT_EQ(1U, dic.count("Key"));
  1521. EXPECT_EQ(1U, dic.count("key"));
  1522. EXPECT_EQ("upper", dic.find("Key")->second);
  1523. EXPECT_EQ("lower", dic.find("key")->second);
  1524. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1525. }
  1526. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1527. Server svr;
  1528. std::string order;
  1529. svr.Get("/order", [&](const Request &req, Response &res) {
  1530. order = entries_to_string(req.params);
  1531. res.set_content("ok", "text/plain");
  1532. });
  1533. auto port = svr.bind_to_any_port(HOST);
  1534. thread t = thread([&] { svr.listen_after_bind(); });
  1535. auto se = detail::scope_exit([&] {
  1536. svr.stop();
  1537. t.join();
  1538. ASSERT_FALSE(svr.is_running());
  1539. });
  1540. svr.wait_until_ready();
  1541. Client cli(HOST, port);
  1542. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1543. ASSERT_TRUE(res);
  1544. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1545. }
  1546. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1547. Server svr;
  1548. std::string field_order, file_order;
  1549. svr.Post("/order", [&](const Request &req, Response &res) {
  1550. for (const auto &field : req.form.fields) {
  1551. field_order += field.first + "=" + field.second.content + " ";
  1552. }
  1553. for (const auto &file : req.form.files) {
  1554. file_order += file.first + "=" + file.second.filename + " ";
  1555. }
  1556. res.set_content("ok", "text/plain");
  1557. });
  1558. auto port = svr.bind_to_any_port(HOST);
  1559. thread t = thread([&] { svr.listen_after_bind(); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. t.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. UploadFormDataItems items = {
  1567. {"zulu", "1", "", ""},
  1568. {"alpha", "2", "", ""},
  1569. {"mike", "3", "", ""},
  1570. {"zebra", "z", "z.txt", "text/plain"},
  1571. {"apple", "a", "a.txt", "text/plain"},
  1572. };
  1573. Client cli(HOST, port);
  1574. auto res = cli.Post("/order", items);
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1577. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1578. }
  1579. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1580. Server svr;
  1581. std::vector<std::string> values;
  1582. std::string first, second, out_of_range, order;
  1583. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1584. values = req.form.get_fields("tag");
  1585. first = req.form.get_field("tag", 0);
  1586. second = req.form.get_field("tag", 1);
  1587. out_of_range = req.form.get_field("tag", 2);
  1588. for (const auto &field : req.form.fields) {
  1589. order += field.first + "=" + field.second.content + " ";
  1590. }
  1591. res.set_content("ok", "text/plain");
  1592. });
  1593. auto port = svr.bind_to_any_port(HOST);
  1594. thread t = thread([&] { svr.listen_after_bind(); });
  1595. auto se = detail::scope_exit([&] {
  1596. svr.stop();
  1597. t.join();
  1598. ASSERT_FALSE(svr.is_running());
  1599. });
  1600. svr.wait_until_ready();
  1601. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1602. // not adjacent in the container.
  1603. UploadFormDataItems items = {
  1604. {"tag", "first", "", ""},
  1605. {"other", "x", "", ""},
  1606. {"tag", "second", "", ""},
  1607. };
  1608. Client cli(HOST, port);
  1609. auto res = cli.Post("/repeated", items);
  1610. ASSERT_TRUE(res);
  1611. ASSERT_EQ(2U, values.size());
  1612. EXPECT_EQ("first", values[0]);
  1613. EXPECT_EQ("second", values[1]);
  1614. EXPECT_EQ("first", first);
  1615. EXPECT_EQ("second", second);
  1616. // std::multimap already kept entries sharing a name in insertion order, so
  1617. // everything above passes without this change too. The whole traversal is
  1618. // what tells the two apart: sorting by name would hoist "other" to the front
  1619. // and the two "tag" parts would end up adjacent.
  1620. EXPECT_EQ("tag=first other=x tag=second ", order);
  1621. // Advancing past the last entry of a name used to run off the container;
  1622. // the container's saturating increment makes it return the default instead.
  1623. EXPECT_EQ("", out_of_range);
  1624. }
  1625. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1626. Server svr;
  1627. std::string file_names;
  1628. svr.Post("/upload", [&](const Request &req, Response &res) {
  1629. for (const auto &file : req.form.files) {
  1630. file_names += file.first + "|" + file.second.filename + " ";
  1631. }
  1632. res.set_content("ok", "text/plain");
  1633. });
  1634. auto port = svr.bind_to_any_port(HOST);
  1635. thread t = thread([&] { svr.listen_after_bind(); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. t.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. // A trailing backslash would otherwise escape the closing quote.
  1643. UploadFormDataItems items = {
  1644. {"dir\\", "x", "a.txt", "text/plain"},
  1645. {"b", "y", "a\\\\b.txt", "text/plain"},
  1646. };
  1647. Client cli(HOST, port);
  1648. auto res = cli.Post("/upload", items);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1651. }
  1652. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1653. // Server::read_content() keeps a FormFields::iterator alive across the
  1654. // content callbacks that fill the part it points at. The container is
  1655. // vector-backed, so a later emplace can reallocate and invalidate an older
  1656. // iterator; 64 parts grow the vector through seven reallocations, which
  1657. // checks that every part's content still lands in its own entry.
  1658. const size_t part_count = 64;
  1659. // One formula for both the parts sent and the values expected back, so the
  1660. // two cannot drift apart.
  1661. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1662. auto content_of = [](size_t i) {
  1663. return std::string(64, static_cast<char>('a' + (i % 26)));
  1664. };
  1665. Server svr;
  1666. std::vector<std::pair<std::string, std::string>> received;
  1667. svr.Post("/many", [&](const Request &req, Response &res) {
  1668. for (const auto &field : req.form.fields) {
  1669. received.emplace_back(field.first, field.second.content);
  1670. }
  1671. res.set_content("ok", "text/plain");
  1672. });
  1673. auto port = svr.bind_to_any_port(HOST);
  1674. thread t = thread([&] { svr.listen_after_bind(); });
  1675. auto se = detail::scope_exit([&] {
  1676. svr.stop();
  1677. t.join();
  1678. ASSERT_FALSE(svr.is_running());
  1679. });
  1680. svr.wait_until_ready();
  1681. UploadFormDataItems items;
  1682. for (size_t i = 0; i < part_count; i++) {
  1683. items.push_back({name_of(i), content_of(i), "", ""});
  1684. }
  1685. Client cli(HOST, port);
  1686. auto res = cli.Post("/many", items);
  1687. ASSERT_TRUE(res);
  1688. ASSERT_EQ(part_count, received.size());
  1689. for (size_t i = 0; i < part_count; i++) {
  1690. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1691. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1692. }
  1693. }
  1694. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1695. string content_type = "multipart/form-data; boundary=something";
  1696. string boundary;
  1697. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1698. EXPECT_TRUE(ret);
  1699. EXPECT_EQ(boundary, "something");
  1700. }
  1701. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1702. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1703. string boundary;
  1704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1705. EXPECT_TRUE(ret);
  1706. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1709. string content_type =
  1710. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1711. string boundary;
  1712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1713. EXPECT_TRUE(ret);
  1714. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1715. }
  1716. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1717. string content_type =
  1718. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1719. string boundary;
  1720. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1723. }
  1724. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1725. const string boundary(70, 'a');
  1726. string content_type = "multipart/form-data; boundary=" + boundary;
  1727. string parsed;
  1728. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1729. EXPECT_TRUE(ret);
  1730. EXPECT_EQ(parsed, boundary);
  1731. }
  1732. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1733. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1734. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1735. string parsed;
  1736. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1737. EXPECT_FALSE(ret);
  1738. }
  1739. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1740. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1741. // is 72 characters on the wire and still valid.
  1742. const string boundary(70, 'a');
  1743. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1744. string parsed;
  1745. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1746. EXPECT_EQ(parsed, boundary);
  1747. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1748. parsed.clear();
  1749. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1752. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1753. // The parameter parser must not treat that '=' as the key/value separator.
  1754. string content_type =
  1755. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1756. "charset=UTF-8";
  1757. string parsed;
  1758. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1759. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1760. }
  1761. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1762. // A ';' inside the quoted-string is part of the value, not a parameter
  1763. // separator, so it must not truncate the boundary.
  1764. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1765. string parsed;
  1766. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1767. EXPECT_EQ(parsed, "a;b");
  1768. }
  1769. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1770. string parsed;
  1771. EXPECT_TRUE(detail::parse_multipart_boundary(
  1772. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1773. EXPECT_EQ("a\\b", parsed);
  1774. EXPECT_TRUE(detail::parse_multipart_boundary(
  1775. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1776. EXPECT_EQ("a\"b", parsed);
  1777. }
  1778. TEST(ParseDispositionParamsTest, QuotedValues) {
  1779. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1780. // ';' and '=' are ordinary characters inside one.
  1781. struct {
  1782. const char *value;
  1783. std::vector<std::pair<const char *, const char *>> expected;
  1784. } cases[] = {
  1785. {"name=\"file1\"; filename=\"a.txt\"",
  1786. {{"name", "file1"}, {"filename", "a.txt"}}},
  1787. // MIME parameter names are case-insensitive, but their values are not.
  1788. {"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
  1789. {{"name", "Upload"}, {"filename", "Report.TXT"}}},
  1790. // Whitespace around '=' and ';' is still trimmed
  1791. {"name=\"file2\" ;filename = \"a.html\"",
  1792. {{"name", "file2"}, {"filename", "a.html"}}},
  1793. // '=' inside the value used to leave only the text after the last one
  1794. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1795. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1796. {"name=\"x=y\"", {{"name", "x=y"}}},
  1797. // ';' inside the value used to truncate the pair and leave a bogus one
  1798. {"name=\"file3\"; filename=\"a;b.txt\"",
  1799. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1800. // An unquoted value keeps working, and so does filename*
  1801. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1802. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1803. // A parameter with no key is dropped rather than turned into one whose
  1804. // key is the value
  1805. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1806. // An escaped quote does not end the value
  1807. {"name=\"a\\\"; filename=evil.php\"",
  1808. {{"name", "a\"; filename=evil.php"}}},
  1809. // Other backslashes, as in a Windows path, are kept
  1810. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1811. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1812. };
  1813. for (const auto &c : cases) {
  1814. Params params;
  1815. detail::parse_disposition_params(c.value, params);
  1816. for (const auto &kv : c.expected) {
  1817. auto it = params.find(kv.first);
  1818. ASSERT_NE(it, params.end())
  1819. << "value: " << c.value << ", key: " << kv.first;
  1820. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1821. }
  1822. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1823. }
  1824. }
  1825. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1826. Server svr;
  1827. std::string filename;
  1828. std::string content;
  1829. svr.Post("/upload", [&](const Request &req, Response &) {
  1830. const auto &file = req.form.get_file("file");
  1831. filename = file.filename;
  1832. content = file.content;
  1833. });
  1834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1835. auto se = detail::scope_exit([&] {
  1836. svr.stop();
  1837. thread.join();
  1838. ASSERT_FALSE(svr.is_running());
  1839. });
  1840. svr.wait_until_ready();
  1841. std::string body = "--B\r\n"
  1842. "Content-Disposition: form-data; name=\"file\"; "
  1843. "filename=\"a.txt\"\r\n"
  1844. "Content-Type: text/plain\r\n"
  1845. "\r\n"
  1846. "hello\r\n"
  1847. "--B--\r\n";
  1848. Client cli(HOST, PORT);
  1849. auto res = cli.Post(
  1850. "/upload",
  1851. [&](size_t offset, DataSink &sink) {
  1852. if (offset < body.size()) {
  1853. sink.write(&body[offset], 1);
  1854. } else {
  1855. sink.done();
  1856. }
  1857. return true;
  1858. },
  1859. "multipart/form-data; boundary=B");
  1860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1861. EXPECT_EQ(StatusCode::OK_200, res->status);
  1862. EXPECT_EQ("a.txt", filename);
  1863. EXPECT_EQ("hello", content);
  1864. }
  1865. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1866. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1867. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1868. Server svr;
  1869. std::string field_value, file_name, file_filename;
  1870. bool has_field = false, has_file = false;
  1871. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1872. has_field = req.form.has_field("x=y");
  1873. field_value = req.form.get_field("x=y");
  1874. has_file = req.form.has_file("file1");
  1875. const auto &file = req.form.get_file("file1");
  1876. file_name = file.name;
  1877. file_filename = file.filename;
  1878. res.set_content("ok", "text/plain");
  1879. });
  1880. auto port = svr.bind_to_any_port(HOST);
  1881. thread t = thread([&] { svr.listen_after_bind(); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. t.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. UploadFormDataItems items = {
  1889. {"x=y", "field-value", "", ""},
  1890. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1891. };
  1892. Client cli(HOST, port);
  1893. auto res = cli.Post("/quoted", items);
  1894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1895. ASSERT_EQ(StatusCode::OK_200, res->status);
  1896. EXPECT_TRUE(has_field);
  1897. EXPECT_EQ("field-value", field_value);
  1898. EXPECT_TRUE(has_file);
  1899. EXPECT_EQ("file1", file_name);
  1900. EXPECT_EQ("a;b=report.pdf", file_filename);
  1901. }
  1902. TEST(GetHeaderValueTest, DefaultValue) {
  1903. Headers headers = {{"Dummy", "Dummy"}};
  1904. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1905. EXPECT_STREQ("text/plain", val);
  1906. }
  1907. TEST(GetHeaderValueTest, DefaultValueInt) {
  1908. Headers headers = {{"Dummy", "Dummy"}};
  1909. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1910. EXPECT_EQ(100ull, val);
  1911. }
  1912. TEST(GetHeaderValueTest, RegularValue) {
  1913. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1914. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1915. EXPECT_STREQ("text/html", val);
  1916. }
  1917. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1918. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1919. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1920. EXPECT_STREQ("text/html", val);
  1921. }
  1922. TEST(GetHeaderValueTest, SetContent) {
  1923. Response res;
  1924. res.set_content("html", "text/html");
  1925. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1926. res.set_content("text", "text/plain");
  1927. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1928. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1929. }
  1930. TEST(GetHeaderValueTest, RegularValueInt) {
  1931. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1932. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1933. EXPECT_EQ(100ull, val);
  1934. }
  1935. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1936. Headers headers = {{"Content-Length", "x"}};
  1937. auto is_invalid_value = false;
  1938. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1939. is_invalid_value);
  1940. EXPECT_EQ(0ull, val);
  1941. EXPECT_TRUE(is_invalid_value);
  1942. }
  1943. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1944. // An all-digit value that overflows size_t must be reported as invalid, not
  1945. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1946. // a large length to a small one on 32-bit builds, leaving the framing length
  1947. // wrong while is_invalid_value stayed false.
  1948. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1949. auto is_invalid_value = false;
  1950. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1951. is_invalid_value);
  1952. EXPECT_TRUE(is_invalid_value);
  1953. // A well-formed length is unaffected.
  1954. Headers ok = {{"Content-Length", "1234"}};
  1955. is_invalid_value = false;
  1956. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1957. is_invalid_value);
  1958. EXPECT_EQ(1234ull, val);
  1959. EXPECT_FALSE(is_invalid_value);
  1960. }
  1961. TEST(GetHeaderValueTest, Range) {
  1962. {
  1963. Headers headers = {make_range_header({{1, -1}})};
  1964. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1965. EXPECT_STREQ("bytes=1-", val);
  1966. }
  1967. {
  1968. Headers headers = {make_range_header({{-1, 1}})};
  1969. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1970. EXPECT_STREQ("bytes=-1", val);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, 10}})};
  1974. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1975. EXPECT_STREQ("bytes=1-10", val);
  1976. }
  1977. {
  1978. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1979. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1980. EXPECT_STREQ("bytes=1-10, 100-", val);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1984. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1985. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1986. }
  1987. {
  1988. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1989. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1990. EXPECT_STREQ("bytes=0-0, -1", val);
  1991. }
  1992. }
  1993. TEST(BearerTokenAuthTest, SchemeValidation) {
  1994. // A value shorter than "Bearer " must not throw from the fixed-length
  1995. // substr, and a non-Bearer scheme must not be reported as a token.
  1996. struct {
  1997. const char *value;
  1998. const char *expected;
  1999. } cases[] = {
  2000. {"x", ""},
  2001. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  2002. {"Bearer abc123", "abc123"},
  2003. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  2004. };
  2005. for (const auto &c : cases) {
  2006. Request req;
  2007. req.set_header("Authorization", c.value);
  2008. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  2009. }
  2010. }
  2011. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  2012. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2013. // to depend on the standard library (libstdc++ handed back duplicates in
  2014. // reverse insertion order, libc++ in insertion order).
  2015. Request req;
  2016. req.set_header("Accept-Encoding", "gzip");
  2017. req.set_header("Accept-Encoding", "deflate");
  2018. req.set_header("Accept-Encoding", "br");
  2019. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2020. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2021. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2022. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2023. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2024. }
  2025. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2026. Request req;
  2027. req.set_header("X-Test", "only");
  2028. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2029. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2030. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2031. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2032. }
  2033. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2034. Request req;
  2035. req.set_header("X-First", "1");
  2036. req.set_header("X-Test", "2");
  2037. req.params.emplace("first", "1");
  2038. req.params.emplace("test", "2");
  2039. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2040. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2041. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2042. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2043. // The second one is negative when read as a signed value
  2044. const auto max_id = (std::numeric_limits<size_t>::max)();
  2045. for (auto id : {max_id / 2, max_id}) {
  2046. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2047. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2048. EXPECT_EQ("", req.get_param_value("test", id));
  2049. EXPECT_EQ("", req.form.get_field("test", id));
  2050. EXPECT_EQ("", req.form.get_file("test", id).content);
  2051. }
  2052. }
  2053. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2054. Headers headers;
  2055. headers.emplace("Host", "example.com");
  2056. headers.emplace("Accept-Encoding", "gzip");
  2057. headers.emplace("User-Agent", "test");
  2058. headers.emplace("Accept-Encoding", "deflate");
  2059. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2060. "Accept-Encoding=deflate ",
  2061. entries_to_string(headers));
  2062. }
  2063. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2064. Headers headers = {{"Content-Type", "text/html"},
  2065. {"CONTENT-TYPE", "text/xml"}};
  2066. EXPECT_EQ(2U, headers.count("content-type"));
  2067. auto it = headers.find("content-type");
  2068. ASSERT_TRUE(it != headers.end());
  2069. EXPECT_EQ("text/html", it->second);
  2070. }
  2071. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2072. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2073. // drop only those fields and leave everything positioned between them.
  2074. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2075. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2076. auto rng = headers.equal_range("a");
  2077. headers.erase(rng.first, rng.second);
  2078. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2079. }
  2080. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2081. Headers headers = {
  2082. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2083. EXPECT_EQ(3U, headers.erase("A"));
  2084. EXPECT_EQ(0U, headers.count("A"));
  2085. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2086. }
  2087. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2088. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2089. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2090. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2091. }
  2092. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2093. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2094. headers.emplace_front("Host", "example.com");
  2095. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2096. entries_to_string(headers));
  2097. }
  2098. TEST(ParseHeaderValueTest, Range) {
  2099. {
  2100. Ranges ranges;
  2101. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2102. EXPECT_TRUE(ret);
  2103. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2104. }
  2105. {
  2106. Ranges ranges;
  2107. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2108. EXPECT_TRUE(ret);
  2109. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2110. }
  2111. {
  2112. Ranges ranges;
  2113. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2114. EXPECT_TRUE(ret);
  2115. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2116. }
  2117. {
  2118. Ranges ranges;
  2119. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2120. EXPECT_FALSE(ret);
  2121. }
  2122. {
  2123. Ranges ranges;
  2124. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2125. EXPECT_TRUE(ret);
  2126. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2127. }
  2128. {
  2129. Ranges ranges;
  2130. auto ret =
  2131. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2132. EXPECT_TRUE(ret);
  2133. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2134. }
  2135. {
  2136. Ranges ranges;
  2137. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2138. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2139. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2140. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2141. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2142. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2143. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2144. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2145. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2146. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2147. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2148. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2149. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2150. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2151. EXPECT_FALSE(
  2152. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2153. EXPECT_TRUE(ranges.empty());
  2154. }
  2155. {
  2156. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2157. // remainder of the representation, so it stays accepted.
  2158. Ranges ranges;
  2159. auto ret =
  2160. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2161. EXPECT_TRUE(ret);
  2162. ASSERT_EQ(1u, ranges.size());
  2163. EXPECT_EQ(0, ranges[0].first);
  2164. EXPECT_EQ(-1, ranges[0].second);
  2165. }
  2166. // RFC 9110 14.1: range unit names are case-insensitive.
  2167. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2168. Ranges ranges;
  2169. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2170. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2171. }
  2172. }
  2173. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2174. Request req;
  2175. req.set_header("Accept-Encoding", "gzip");
  2176. Response res;
  2177. res.set_header("Content-Type", "text/plain");
  2178. auto ret = detail::encoding_type(req, res);
  2179. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2180. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2181. #else
  2182. EXPECT_TRUE(ret == detail::EncodingType::None);
  2183. #endif
  2184. }
  2185. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2186. Request req;
  2187. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2188. Response res;
  2189. res.set_header("Content-Type", "text/plain");
  2190. auto ret = detail::encoding_type(req, res);
  2191. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2192. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2193. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2194. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2195. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2196. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2197. #else
  2198. EXPECT_TRUE(ret == detail::EncodingType::None);
  2199. #endif
  2200. }
  2201. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2202. Request req;
  2203. req.set_header("Accept-Encoding",
  2204. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2205. Response res;
  2206. res.set_header("Content-Type", "text/plain");
  2207. auto ret = detail::encoding_type(req, res);
  2208. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2209. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2210. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2211. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2212. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2213. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2214. #else
  2215. EXPECT_TRUE(ret == detail::EncodingType::None);
  2216. #endif
  2217. }
  2218. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2219. // All supported encodings rejected with q=0 should return None
  2220. Request req;
  2221. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2222. Response res;
  2223. res.set_header("Content-Type", "text/plain");
  2224. auto ret = detail::encoding_type(req, res);
  2225. EXPECT_TRUE(ret == detail::EncodingType::None);
  2226. }
  2227. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2228. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2229. Request req;
  2230. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2231. Response res;
  2232. res.set_header("Content-Type", "text/plain");
  2233. auto ret = detail::encoding_type(req, res);
  2234. EXPECT_TRUE(ret == detail::EncodingType::None);
  2235. }
  2236. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2237. Request req;
  2238. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2239. Response res;
  2240. res.set_header("Content-Type", "text/plain");
  2241. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2242. }
  2243. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2244. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2245. Request req;
  2246. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2247. Response res;
  2248. res.set_header("Content-Type", "text/plain");
  2249. auto ret = detail::encoding_type(req, res);
  2250. EXPECT_TRUE(ret == detail::EncodingType::None);
  2251. }
  2252. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2253. // RFC 7231: Accept-Encoding values are case-insensitive
  2254. Request req;
  2255. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2256. Response res;
  2257. res.set_header("Content-Type", "text/plain");
  2258. auto ret = detail::encoding_type(req, res);
  2259. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2260. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2261. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2262. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2263. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2264. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2265. #else
  2266. EXPECT_TRUE(ret == detail::EncodingType::None);
  2267. #endif
  2268. }
  2269. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2270. // q value should determine priority, not hardcoded order
  2271. Request req;
  2272. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2273. Response res;
  2274. res.set_header("Content-Type", "text/plain");
  2275. auto ret = detail::encoding_type(req, res);
  2276. // gzip has highest q=1.0, so it should be selected even though
  2277. // br and zstd are also supported
  2278. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2279. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2280. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2281. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2282. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2283. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2284. #else
  2285. EXPECT_TRUE(ret == detail::EncodingType::None);
  2286. #endif
  2287. }
  2288. TEST(BufferStreamTest, read) {
  2289. detail::BufferStream strm1;
  2290. Stream &strm = strm1;
  2291. EXPECT_EQ(5, strm.write("hello"));
  2292. char buf[512];
  2293. EXPECT_EQ(2, strm.read(buf, 2));
  2294. EXPECT_EQ('h', buf[0]);
  2295. EXPECT_EQ('e', buf[1]);
  2296. EXPECT_EQ(2, strm.read(buf, 2));
  2297. EXPECT_EQ('l', buf[0]);
  2298. EXPECT_EQ('l', buf[1]);
  2299. EXPECT_EQ(1, strm.read(buf, 1));
  2300. EXPECT_EQ('o', buf[0]);
  2301. EXPECT_EQ(0, strm.read(buf, 1));
  2302. }
  2303. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2304. auto host = "www.httpwatch.com";
  2305. auto ip = hosted_at(host);
  2306. EXPECT_EQ("23.96.13.243", ip);
  2307. std::vector<std::string> addrs;
  2308. hosted_at(host, addrs);
  2309. EXPECT_EQ(1u, addrs.size());
  2310. }
  2311. #if 0 // It depends on each test environment...
  2312. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2313. auto host = "www.youtube.com";
  2314. std::vector<std::string> addrs;
  2315. hosted_at(host, addrs);
  2316. EXPECT_EQ(20u, addrs.size());
  2317. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2318. EXPECT_TRUE(it != addrs.end());
  2319. }
  2320. #endif
  2321. class ChunkedEncodingTest : public ::testing::Test {
  2322. protected:
  2323. ChunkedEncodingTest()
  2324. : cli_(HOST, PORT)
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. ,
  2327. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2328. #endif
  2329. {
  2330. cli_.set_connection_timeout(2);
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. cli_.enable_server_certificate_verification(false);
  2333. #endif
  2334. }
  2335. virtual void SetUp() {
  2336. read_file("./image.jpg", image_data_);
  2337. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2338. res.set_content("Hello World!", "text/plain");
  2339. });
  2340. svr_.Get(
  2341. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2342. res.set_chunked_content_provider(
  2343. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2344. size_t remaining = image_data_.size() - offset;
  2345. if (remaining == 0) {
  2346. sink.done();
  2347. } else {
  2348. constexpr size_t CHUNK_SIZE = 1024;
  2349. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2350. sink.write(&image_data_[offset], send_size);
  2351. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2352. }
  2353. return true;
  2354. });
  2355. });
  2356. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2357. svr_.wait_until_ready();
  2358. }
  2359. virtual void TearDown() {
  2360. svr_.stop();
  2361. if (!request_threads_.empty()) {
  2362. std::this_thread::sleep_for(std::chrono::seconds(1));
  2363. for (auto &t : request_threads_) {
  2364. t.join();
  2365. }
  2366. }
  2367. t_.join();
  2368. }
  2369. #ifdef CPPHTTPLIB_SSL_ENABLED
  2370. SSLClient cli_;
  2371. SSLServer svr_;
  2372. #else
  2373. Client cli_;
  2374. Server svr_;
  2375. #endif
  2376. thread t_;
  2377. std::vector<thread> request_threads_;
  2378. std::string image_data_;
  2379. };
  2380. TEST_F(ChunkedEncodingTest, NormalGet) {
  2381. auto res = cli_.Get("/chunked");
  2382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2383. std::string out;
  2384. read_file("./image.jpg", out);
  2385. EXPECT_EQ(StatusCode::OK_200, res->status);
  2386. EXPECT_EQ(out, res->body);
  2387. }
  2388. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2389. std::string body;
  2390. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2391. body.append(data, data_length);
  2392. return true;
  2393. });
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. std::string out;
  2396. read_file("./image.jpg", out);
  2397. EXPECT_EQ(StatusCode::OK_200, res->status);
  2398. EXPECT_EQ(out, body);
  2399. }
  2400. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2401. std::string body;
  2402. auto res = cli_.Get(
  2403. "/chunked",
  2404. [&](const Response &response) {
  2405. EXPECT_EQ(StatusCode::OK_200, response.status);
  2406. return true;
  2407. },
  2408. [&](const char *data, size_t data_length) {
  2409. body.append(data, data_length);
  2410. return true;
  2411. });
  2412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2413. std::string out;
  2414. read_file("./image.jpg", out);
  2415. EXPECT_EQ(StatusCode::OK_200, res->status);
  2416. EXPECT_EQ(out, body);
  2417. }
  2418. TEST(RangeTest, FromHTTPBin_Online) {
  2419. auto host = "httpbingo.org";
  2420. auto path = std::string{"/range/32"};
  2421. #ifdef CPPHTTPLIB_SSL_ENABLED
  2422. auto port = 443;
  2423. SSLClient cli(host, port);
  2424. #else
  2425. auto port = 80;
  2426. Client cli(host, port);
  2427. #endif
  2428. cli.set_connection_timeout(5);
  2429. {
  2430. auto res = retry_service_failures([&] { return cli.Get(path); });
  2431. SKIP_ON_SERVICE_FAILURE(res);
  2432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2433. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2434. EXPECT_EQ(StatusCode::OK_200, res->status);
  2435. }
  2436. {
  2437. Headers headers = {make_range_header({{1, -1}})};
  2438. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2439. SKIP_ON_SERVICE_FAILURE(res);
  2440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2441. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2443. }
  2444. {
  2445. Headers headers = {make_range_header({{1, 10}})};
  2446. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2447. SKIP_ON_SERVICE_FAILURE(res);
  2448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2449. EXPECT_EQ("bcdefghijk", res->body);
  2450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2451. }
  2452. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2453. // entire resource, while the original httpbin returned 200. Both are
  2454. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2455. {
  2456. Headers headers = {make_range_header({{0, 31}})};
  2457. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2458. SKIP_ON_SERVICE_FAILURE(res);
  2459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2460. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2461. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2462. res->status == StatusCode::PartialContent_206);
  2463. }
  2464. {
  2465. Headers headers = {make_range_header({{0, -1}})};
  2466. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2467. SKIP_ON_SERVICE_FAILURE(res);
  2468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2469. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2470. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2471. res->status == StatusCode::PartialContent_206);
  2472. }
  2473. // go-httpbin returns 206 with clamped range for over-range requests,
  2474. // while the original httpbin returned 416. Both behaviors are observed
  2475. // in real servers, so we only verify the request succeeds.
  2476. {
  2477. Headers headers = {make_range_header({{0, 32}})};
  2478. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2479. SKIP_ON_SERVICE_FAILURE(res);
  2480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2481. }
  2482. }
  2483. TEST(RangeTest, IgnoredForPost) {
  2484. Server svr;
  2485. svr.Post("/", [](const Request &, Response &res) {
  2486. res.set_content("abcdefg", "text/plain");
  2487. });
  2488. auto port = svr.bind_to_any_port(HOST);
  2489. ASSERT_GT(port, 0);
  2490. thread t = thread([&] { svr.listen_after_bind(); });
  2491. auto se = detail::scope_exit([&] {
  2492. svr.stop();
  2493. t.join();
  2494. ASSERT_FALSE(svr.is_running());
  2495. });
  2496. svr.wait_until_ready();
  2497. Client cli(HOST, port);
  2498. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2499. auto res = cli.Post("/", Headers{{"Range", range}});
  2500. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2501. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2502. EXPECT_EQ("abcdefg", res->body) << range;
  2503. }
  2504. }
  2505. TEST(RangeTest, IgnoredForUnknownUnit) {
  2506. Server svr;
  2507. svr.Get("/", [](const Request &, Response &res) {
  2508. res.set_content("abcdefg", "text/plain");
  2509. });
  2510. auto port = svr.bind_to_any_port(HOST);
  2511. ASSERT_GT(port, 0);
  2512. thread t = thread([&] { svr.listen_after_bind(); });
  2513. auto se = detail::scope_exit([&] {
  2514. svr.stop();
  2515. t.join();
  2516. ASSERT_FALSE(svr.is_running());
  2517. });
  2518. svr.wait_until_ready();
  2519. Client cli(HOST, port);
  2520. for (auto range : {"items=1-2", "none=x"}) {
  2521. auto res = cli.Get("/", Headers{{"Range", range}});
  2522. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2523. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2524. EXPECT_EQ("abcdefg", res->body) << range;
  2525. }
  2526. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2527. ASSERT_TRUE(res) << to_string(res.error());
  2528. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2529. }
  2530. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2531. auto host = "unresolvableaddress.local";
  2532. auto path = std::string{"/"};
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. auto port = 443;
  2535. SSLClient cli(host, port);
  2536. #else
  2537. auto port = 80;
  2538. Client cli(host, port);
  2539. #endif
  2540. cli.set_connection_timeout(1);
  2541. {
  2542. auto res = cli.Get(path);
  2543. ASSERT_FALSE(res);
  2544. }
  2545. std::this_thread::sleep_for(std::chrono::seconds(8));
  2546. }
  2547. #if defined(__linux__) && defined(__GLIBC__) && \
  2548. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2549. // Forward declaration: in split builds split.py strips `inline` and moves the
  2550. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2551. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2552. // against the symbol in both header-only and split builds.
  2553. namespace httplib {
  2554. namespace detail {
  2555. int getaddrinfo_with_timeout(const char *node, const char *service,
  2556. const struct addrinfo *hints,
  2557. struct addrinfo **res, time_t timeout_sec);
  2558. } // namespace detail
  2559. } // namespace httplib
  2560. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2561. //
  2562. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2563. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2564. // gai_suspend() call hits the connection timeout the function calls
  2565. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2566. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2567. // still alive and still references the now-destroyed stack frame.
  2568. //
  2569. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2570. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2571. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2572. // and runs them in a container.
  2573. namespace {
  2574. bool should_run_issue_2431_tests() {
  2575. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2576. return v && *v && std::string(v) != "0";
  2577. }
  2578. std::string unique_unresolvable_host(int n) {
  2579. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2580. // glibc still asks the configured nameserver — which is exactly the path
  2581. // we want to exercise. A unique label per call avoids the resolver cache.
  2582. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2583. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2584. std::to_string(n) + ".invalid";
  2585. }
  2586. } // namespace
  2587. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2588. if (!should_run_issue_2431_tests()) {
  2589. GTEST_SKIP()
  2590. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2591. }
  2592. for (int i = 0; i < 8; ++i) {
  2593. struct addrinfo hints;
  2594. memset(&hints, 0, sizeof(hints));
  2595. hints.ai_family = AF_UNSPEC;
  2596. hints.ai_socktype = SOCK_STREAM;
  2597. auto host = unique_unresolvable_host(i);
  2598. struct addrinfo *result = nullptr;
  2599. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2600. &result, /*timeout_sec=*/1);
  2601. if (rc == 0 && result) { freeaddrinfo(result); }
  2602. }
  2603. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2604. // stack region they still believe holds their gaicb.
  2605. std::this_thread::sleep_for(std::chrono::seconds(3));
  2606. }
  2607. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2608. if (!should_run_issue_2431_tests()) {
  2609. GTEST_SKIP()
  2610. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2611. }
  2612. std::atomic<bool> stop{false};
  2613. std::vector<std::thread> threads;
  2614. for (int t = 0; t < 8; ++t) {
  2615. threads.emplace_back([t, &stop] {
  2616. int i = 0;
  2617. while (!stop.load(std::memory_order_relaxed)) {
  2618. struct addrinfo hints;
  2619. memset(&hints, 0, sizeof(hints));
  2620. hints.ai_family = AF_UNSPEC;
  2621. hints.ai_socktype = SOCK_STREAM;
  2622. auto host = unique_unresolvable_host(t * 100000 + i++);
  2623. struct addrinfo *result = nullptr;
  2624. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2625. &result, /*timeout_sec=*/1);
  2626. if (rc == 0 && result) { freeaddrinfo(result); }
  2627. }
  2628. });
  2629. }
  2630. std::this_thread::sleep_for(std::chrono::seconds(8));
  2631. stop.store(true, std::memory_order_relaxed);
  2632. for (auto &th : threads) {
  2633. th.join();
  2634. }
  2635. std::this_thread::sleep_for(std::chrono::seconds(3));
  2636. }
  2637. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2638. if (!should_run_issue_2431_tests()) {
  2639. GTEST_SKIP()
  2640. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2641. }
  2642. std::atomic<bool> stop{false};
  2643. std::vector<std::thread> threads;
  2644. for (int t = 0; t < 8; ++t) {
  2645. threads.emplace_back([t, &stop] {
  2646. int i = 0;
  2647. while (!stop.load(std::memory_order_relaxed)) {
  2648. auto host = unique_unresolvable_host(t * 100000 + i++);
  2649. Client cli(host, 80);
  2650. cli.set_connection_timeout(1, 0);
  2651. cli.set_read_timeout(1, 0);
  2652. cli.set_write_timeout(1, 0);
  2653. (void)cli.Get("/");
  2654. }
  2655. });
  2656. }
  2657. std::this_thread::sleep_for(std::chrono::seconds(8));
  2658. stop.store(true, std::memory_order_relaxed);
  2659. for (auto &th : threads) {
  2660. th.join();
  2661. }
  2662. std::this_thread::sleep_for(std::chrono::seconds(3));
  2663. }
  2664. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2665. TEST(ConnectionErrorTest, InvalidHost) {
  2666. auto host = "-abcde.com";
  2667. #ifdef CPPHTTPLIB_SSL_ENABLED
  2668. auto port = 443;
  2669. SSLClient cli(host, port);
  2670. #else
  2671. auto port = 80;
  2672. Client cli(host, port);
  2673. #endif
  2674. cli.set_connection_timeout(std::chrono::seconds(2));
  2675. auto res = cli.Get("/");
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Connection, res.error());
  2678. }
  2679. TEST(ConnectionErrorTest, InvalidHost2) {
  2680. auto host = "httpcan.org/";
  2681. #ifdef CPPHTTPLIB_SSL_ENABLED
  2682. SSLClient cli(host);
  2683. #else
  2684. Client cli(host);
  2685. #endif
  2686. cli.set_connection_timeout(std::chrono::seconds(2));
  2687. auto res = cli.Get("/");
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Connection, res.error());
  2690. }
  2691. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2692. auto host = "httpcan.org/";
  2693. #ifdef CPPHTTPLIB_SSL_ENABLED
  2694. SSLClient cli(host);
  2695. #else
  2696. Client cli(host);
  2697. #endif
  2698. cli.set_connection_timeout(std::chrono::seconds(2));
  2699. auto res = cli.Get("/");
  2700. ASSERT_TRUE(!res);
  2701. stringstream s;
  2702. s << "error code: " << res.error();
  2703. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2704. }
  2705. TEST(ConnectionErrorTest, InvalidPort) {
  2706. auto host = "localhost";
  2707. auto port = 44380;
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. SSLClient cli(host, port);
  2710. #else
  2711. Client cli(host, port);
  2712. #endif
  2713. cli.set_connection_timeout(std::chrono::seconds(2));
  2714. auto res = cli.Get("/");
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_TRUE(Error::Connection == res.error() ||
  2717. Error::ConnectionTimeout == res.error());
  2718. }
  2719. TEST(ConnectionErrorTest, Timeout_Online) {
  2720. auto host = "google.com";
  2721. #ifdef CPPHTTPLIB_SSL_ENABLED
  2722. auto port = 44380;
  2723. SSLClient cli(host, port);
  2724. #else
  2725. auto port = 8080;
  2726. Client cli(host, port);
  2727. #endif
  2728. cli.set_connection_timeout(std::chrono::seconds(2));
  2729. // only probe one address type so that the error reason
  2730. // correlates to the timed-out IPv4, not the unsupported
  2731. // IPv6 connection attempt
  2732. cli.set_address_family(AF_INET);
  2733. auto res = cli.Get("/");
  2734. ASSERT_TRUE(!res);
  2735. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2736. }
  2737. TEST(CancelTest, NoCancel_Online) {
  2738. auto host = "httpbingo.org";
  2739. auto path = std::string{"/range/32"};
  2740. #ifdef CPPHTTPLIB_SSL_ENABLED
  2741. auto port = 443;
  2742. SSLClient cli(host, port);
  2743. #else
  2744. auto port = 80;
  2745. Client cli(host, port);
  2746. #endif
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res = retry_service_failures(
  2749. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2750. SKIP_ON_SERVICE_FAILURE(res);
  2751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2752. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2753. EXPECT_EQ(StatusCode::OK_200, res->status);
  2754. }
  2755. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2756. // Use /bytes with a large payload so that the DownloadProgress callback
  2757. // (which only fires for Content-Length responses) is invoked before the
  2758. // entire body is received, giving cancellation a chance to fire.
  2759. auto host = "httpbingo.org";
  2760. auto path = std::string{"/bytes/524288"};
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. auto port = 443;
  2763. SSLClient cli(host, port);
  2764. #else
  2765. auto port = 80;
  2766. Client cli(host, port);
  2767. #endif
  2768. auto res = retry_service_failures(
  2769. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2770. SKIP_ON_SERVICE_FAILURE(res);
  2771. cli.set_connection_timeout(std::chrono::seconds(5));
  2772. ASSERT_TRUE(!res);
  2773. EXPECT_EQ(Error::Canceled, res.error());
  2774. }
  2775. TEST(CancelTest, WithCancelLargePayload_Online) {
  2776. auto host = "httpbingo.org";
  2777. auto path = std::string{"/bytes/524288"};
  2778. #ifdef CPPHTTPLIB_SSL_ENABLED
  2779. auto port = 443;
  2780. SSLClient cli(host, port);
  2781. #else
  2782. auto port = 80;
  2783. Client cli(host, port);
  2784. #endif
  2785. cli.set_connection_timeout(std::chrono::seconds(5));
  2786. auto res = retry_service_failures([&] {
  2787. auto count = 0;
  2788. return cli.Get(path,
  2789. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2790. });
  2791. SKIP_ON_SERVICE_FAILURE(res);
  2792. ASSERT_TRUE(!res);
  2793. EXPECT_EQ(Error::Canceled, res.error());
  2794. }
  2795. TEST(CancelTest, NoCancelPost) {
  2796. Server svr;
  2797. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2798. res.set_content("Hello World!", "text/plain");
  2799. });
  2800. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2801. auto se = detail::scope_exit([&] {
  2802. svr.stop();
  2803. thread.join();
  2804. ASSERT_FALSE(svr.is_running());
  2805. });
  2806. svr.wait_until_ready();
  2807. Client cli(HOST, PORT);
  2808. cli.set_connection_timeout(std::chrono::seconds(5));
  2809. auto res =
  2810. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2811. "application/json", [](uint64_t, uint64_t) { return true; });
  2812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2813. EXPECT_EQ("Hello World!", res->body);
  2814. EXPECT_EQ(StatusCode::OK_200, res->status);
  2815. }
  2816. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2817. Server svr;
  2818. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2819. res.set_content("Hello World!", "text/plain");
  2820. });
  2821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2822. auto se = detail::scope_exit([&] {
  2823. svr.stop();
  2824. thread.join();
  2825. ASSERT_FALSE(svr.is_running());
  2826. });
  2827. svr.wait_until_ready();
  2828. Client cli(HOST, PORT);
  2829. cli.set_connection_timeout(std::chrono::seconds(5));
  2830. auto res =
  2831. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2832. "application/json", [](uint64_t, uint64_t) { return false; });
  2833. ASSERT_TRUE(!res);
  2834. EXPECT_EQ(Error::Canceled, res.error());
  2835. }
  2836. TEST(CancelTest, WithCancelLargePayloadPost) {
  2837. Server svr;
  2838. svr.set_payload_max_length(200 * 1024 * 1024);
  2839. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2840. res.set_content(LARGE_DATA, "text/plain");
  2841. });
  2842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2843. auto se = detail::scope_exit([&] {
  2844. svr.stop();
  2845. thread.join();
  2846. ASSERT_FALSE(svr.is_running());
  2847. });
  2848. svr.wait_until_ready();
  2849. Client cli(HOST, PORT);
  2850. cli.set_payload_max_length(200 * 1024 * 1024);
  2851. cli.set_connection_timeout(std::chrono::seconds(5));
  2852. auto res =
  2853. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2854. "application/json", [](uint64_t, uint64_t) { return false; });
  2855. ASSERT_TRUE(!res);
  2856. EXPECT_EQ(Error::Canceled, res.error());
  2857. }
  2858. TEST(CancelTest, NoCancelPut) {
  2859. Server svr;
  2860. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2861. res.set_content("Hello World!", "text/plain");
  2862. });
  2863. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2864. auto se = detail::scope_exit([&] {
  2865. svr.stop();
  2866. thread.join();
  2867. ASSERT_FALSE(svr.is_running());
  2868. });
  2869. svr.wait_until_ready();
  2870. Client cli(HOST, PORT);
  2871. cli.set_connection_timeout(std::chrono::seconds(5));
  2872. auto res =
  2873. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2874. "application/json", [](uint64_t, uint64_t) { return true; });
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ("Hello World!", res->body);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2880. Server svr;
  2881. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2882. res.set_content("Hello World!", "text/plain");
  2883. });
  2884. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2885. auto se = detail::scope_exit([&] {
  2886. svr.stop();
  2887. thread.join();
  2888. ASSERT_FALSE(svr.is_running());
  2889. });
  2890. svr.wait_until_ready();
  2891. Client cli(HOST, PORT);
  2892. cli.set_connection_timeout(std::chrono::seconds(5));
  2893. auto res =
  2894. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2895. "application/json", [](uint64_t, uint64_t) { return false; });
  2896. ASSERT_TRUE(!res);
  2897. EXPECT_EQ(Error::Canceled, res.error());
  2898. }
  2899. TEST(CancelTest, WithCancelLargePayloadPut) {
  2900. Server svr;
  2901. svr.set_payload_max_length(200 * 1024 * 1024);
  2902. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2903. res.set_content(LARGE_DATA, "text/plain");
  2904. });
  2905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2906. auto se = detail::scope_exit([&] {
  2907. svr.stop();
  2908. thread.join();
  2909. ASSERT_FALSE(svr.is_running());
  2910. });
  2911. svr.wait_until_ready();
  2912. Client cli(HOST, PORT);
  2913. cli.set_payload_max_length(200 * 1024 * 1024);
  2914. cli.set_connection_timeout(std::chrono::seconds(5));
  2915. auto res =
  2916. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2917. "application/json", [](uint64_t, uint64_t) { return false; });
  2918. ASSERT_TRUE(!res);
  2919. EXPECT_EQ(Error::Canceled, res.error());
  2920. }
  2921. TEST(CancelTest, NoCancelPatch) {
  2922. Server svr;
  2923. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2924. res.set_content("Hello World!", "text/plain");
  2925. });
  2926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2927. auto se = detail::scope_exit([&] {
  2928. svr.stop();
  2929. thread.join();
  2930. ASSERT_FALSE(svr.is_running());
  2931. });
  2932. svr.wait_until_ready();
  2933. Client cli(HOST, PORT);
  2934. cli.set_connection_timeout(std::chrono::seconds(5));
  2935. auto res =
  2936. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2937. "application/json", [](uint64_t, uint64_t) { return true; });
  2938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2939. EXPECT_EQ("Hello World!", res->body);
  2940. EXPECT_EQ(StatusCode::OK_200, res->status);
  2941. }
  2942. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2943. Server svr;
  2944. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2945. res.set_content("Hello World!", "text/plain");
  2946. });
  2947. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2948. auto se = detail::scope_exit([&] {
  2949. svr.stop();
  2950. thread.join();
  2951. ASSERT_FALSE(svr.is_running());
  2952. });
  2953. svr.wait_until_ready();
  2954. Client cli(HOST, PORT);
  2955. cli.set_connection_timeout(std::chrono::seconds(5));
  2956. auto res =
  2957. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2958. "application/json", [](uint64_t, uint64_t) { return false; });
  2959. ASSERT_TRUE(!res);
  2960. EXPECT_EQ(Error::Canceled, res.error());
  2961. }
  2962. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2963. Server svr;
  2964. svr.set_payload_max_length(200 * 1024 * 1024);
  2965. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2966. res.set_content(LARGE_DATA, "text/plain");
  2967. });
  2968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2969. auto se = detail::scope_exit([&] {
  2970. svr.stop();
  2971. thread.join();
  2972. ASSERT_FALSE(svr.is_running());
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, PORT);
  2976. cli.set_payload_max_length(200 * 1024 * 1024);
  2977. cli.set_connection_timeout(std::chrono::seconds(5));
  2978. auto res =
  2979. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2980. "application/json", [](uint64_t, uint64_t) { return false; });
  2981. ASSERT_TRUE(!res);
  2982. EXPECT_EQ(Error::Canceled, res.error());
  2983. }
  2984. TEST(CancelTest, NoCancelDelete) {
  2985. Server svr;
  2986. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2987. res.set_content("Hello World!", "text/plain");
  2988. });
  2989. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2990. auto se = detail::scope_exit([&] {
  2991. svr.stop();
  2992. thread.join();
  2993. ASSERT_FALSE(svr.is_running());
  2994. });
  2995. svr.wait_until_ready();
  2996. Client cli(HOST, PORT);
  2997. cli.set_connection_timeout(std::chrono::seconds(5));
  2998. auto res =
  2999. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3000. "application/json", [](uint64_t, uint64_t) { return true; });
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ("Hello World!", res->body);
  3003. EXPECT_EQ(StatusCode::OK_200, res->status);
  3004. }
  3005. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  3006. Server svr;
  3007. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3008. res.set_content("Hello World!", "text/plain");
  3009. });
  3010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3011. auto se = detail::scope_exit([&] {
  3012. svr.stop();
  3013. thread.join();
  3014. ASSERT_FALSE(svr.is_running());
  3015. });
  3016. svr.wait_until_ready();
  3017. Client cli(HOST, PORT);
  3018. cli.set_connection_timeout(std::chrono::seconds(5));
  3019. auto res =
  3020. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3021. "application/json", [](uint64_t, uint64_t) { return false; });
  3022. ASSERT_TRUE(!res);
  3023. EXPECT_EQ(Error::Canceled, res.error());
  3024. }
  3025. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3026. Server svr;
  3027. svr.set_payload_max_length(200 * 1024 * 1024);
  3028. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3029. res.set_content(LARGE_DATA, "text/plain");
  3030. });
  3031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3032. auto se = detail::scope_exit([&] {
  3033. svr.stop();
  3034. thread.join();
  3035. ASSERT_FALSE(svr.is_running());
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, PORT);
  3039. cli.set_payload_max_length(200 * 1024 * 1024);
  3040. cli.set_connection_timeout(std::chrono::seconds(5));
  3041. auto res =
  3042. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3043. "application/json", [](uint64_t, uint64_t) { return false; });
  3044. ASSERT_TRUE(!res);
  3045. EXPECT_EQ(Error::Canceled, res.error());
  3046. }
  3047. // One stop() from another thread ends a request that waits for the response
  3048. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3049. Server svr;
  3050. std::atomic<bool> received{false};
  3051. std::atomic<bool> done{false};
  3052. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3053. received.store(true);
  3054. while (!done.load()) {
  3055. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3056. }
  3057. res.set_content("Hello World!", "text/plain");
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3061. Client cli(HOST, port);
  3062. cli.set_read_timeout(std::chrono::seconds(30));
  3063. std::future<Result> request;
  3064. auto se = detail::scope_exit([&] {
  3065. done.store(true);
  3066. svr.stop();
  3067. thread.join();
  3068. ASSERT_FALSE(svr.is_running());
  3069. });
  3070. svr.wait_until_ready();
  3071. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3072. for (int i = 0; i < 500 && !received.load(); ++i) {
  3073. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3074. }
  3075. ASSERT_TRUE(received.load());
  3076. // Let the client block in the wait for the response
  3077. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3078. auto start = std::chrono::steady_clock::now();
  3079. cli.stop();
  3080. ASSERT_EQ(std::future_status::ready,
  3081. request.wait_for(std::chrono::seconds(5)));
  3082. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3083. auto res = request.get();
  3084. ASSERT_TRUE(!res);
  3085. EXPECT_EQ(Error::Read, res.error());
  3086. }
  3087. // A listener whose backlog completes the TCP connections of clients, and that
  3088. // never answers them
  3089. struct SilentListener {
  3090. socket_t sock = INVALID_SOCKET;
  3091. sockaddr_in addr{};
  3092. int port = 0;
  3093. explicit SilentListener(int backlog = 1) {
  3094. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3095. addr.sin_family = AF_INET;
  3096. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3097. socklen_t len = sizeof(addr);
  3098. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3099. ::listen(sock, backlog) != 0 ||
  3100. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3101. detail::close_socket(sock);
  3102. sock = INVALID_SOCKET;
  3103. }
  3104. port = ntohs(addr.sin_port);
  3105. }
  3106. ~SilentListener() { detail::close_socket(sock); }
  3107. // The next connection, whose reads give up after 5 seconds
  3108. socket_t accept() const {
  3109. auto peer = ::accept(sock, nullptr, nullptr);
  3110. if (peer != INVALID_SOCKET) {
  3111. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3112. }
  3113. return peer;
  3114. }
  3115. };
  3116. static bool receives_a_byte(socket_t peer) {
  3117. char c = 0;
  3118. return detail::read_socket(peer, &c, 1, 0) == 1;
  3119. }
  3120. // Runs op, stops cli once the listener receives the first byte op sends, and
  3121. // expects op to end with error soon after
  3122. template <typename ClientType, typename Op>
  3123. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3124. Op op, Error error = Error::Canceled) {
  3125. auto ended = std::async(std::launch::async, op);
  3126. auto peer = listener.accept();
  3127. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3128. ASSERT_NE(INVALID_SOCKET, peer);
  3129. ASSERT_TRUE(receives_a_byte(peer));
  3130. cli.stop();
  3131. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3132. EXPECT_EQ(error, ended.get());
  3133. }
  3134. // Stops itself from another thread as the connection opens, the last moment a
  3135. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3136. // waits for the connection fails the test instead of hanging it.
  3137. class StoppedAsConnectedClient : public ClientImpl {
  3138. public:
  3139. using ClientImpl::ClientImpl;
  3140. protected:
  3141. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3142. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3143. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3144. stopper_.wait_for(std::chrono::seconds(1));
  3145. return true;
  3146. }
  3147. private:
  3148. std::future<void> stopper_;
  3149. };
  3150. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3151. SilentListener listener;
  3152. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3153. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3154. cli.set_read_timeout(std::chrono::seconds(3));
  3155. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3156. auto peer = listener.accept();
  3157. EXPECT_FALSE(receives_a_byte(peer));
  3158. detail::close_socket(peer);
  3159. auto handle = cli.open_stream("GET", "/");
  3160. EXPECT_FALSE(handle.is_valid());
  3161. EXPECT_EQ(Error::Canceled, handle.error);
  3162. peer = listener.accept();
  3163. EXPECT_FALSE(receives_a_byte(peer));
  3164. detail::close_socket(peer);
  3165. }
  3166. #ifdef __linux__
  3167. // A connect that a listener with a full backlog never completes
  3168. TEST(ClientStopTest, StopEndsAConnect) {
  3169. SilentListener listener(0);
  3170. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3171. std::vector<socket_t> backlog;
  3172. auto close_backlog = detail::scope_exit([&] {
  3173. for (auto sock : backlog) {
  3174. detail::close_socket(sock);
  3175. }
  3176. });
  3177. for (int i = 0; i < 8; i++) {
  3178. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3179. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3180. sizeof(listener.addr));
  3181. backlog.push_back(sock);
  3182. }
  3183. Client cli("127.0.0.1", listener.port);
  3184. cli.set_connection_timeout(std::chrono::seconds(3));
  3185. auto ended =
  3186. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3187. // A stop() before the request starts does not apply to it, so it repeats
  3188. auto status = std::future_status::timeout;
  3189. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3190. cli.stop();
  3191. status = ended.wait_for(std::chrono::milliseconds(10));
  3192. }
  3193. EXPECT_EQ(std::future_status::ready, status);
  3194. EXPECT_EQ(Error::Canceled, ended.get());
  3195. }
  3196. #endif
  3197. // The stream holds the socket while it waits for the head, out of the reach
  3198. // of shutdown()
  3199. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3200. SilentListener listener;
  3201. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3202. Client cli("127.0.0.1", listener.port);
  3203. cli.set_read_timeout(std::chrono::seconds(3));
  3204. expect_stop_ends(
  3205. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3206. Error::Read);
  3207. }
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. // A server that never answers the ClientHello
  3210. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3211. SilentListener listener;
  3212. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3213. SSLClient cli("127.0.0.1", listener.port);
  3214. cli.enable_server_certificate_verification(false);
  3215. cli.set_connection_timeout(std::chrono::seconds(3));
  3216. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3217. expect_stop_ends(cli, listener,
  3218. [&] { return cli.open_stream("GET", "/").error; });
  3219. }
  3220. // A proxy that takes the CONNECT and never answers it
  3221. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3222. SilentListener listener;
  3223. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3224. SSLClient cli("example.com", 443);
  3225. cli.set_proxy("127.0.0.1", listener.port);
  3226. cli.set_read_timeout(std::chrono::seconds(3));
  3227. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3228. }
  3229. #endif
  3230. // A read timeout past what the clock reaches waits for the response
  3231. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3232. SilentListener listener;
  3233. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3234. Client cli("127.0.0.1", listener.port);
  3235. cli.set_read_timeout(
  3236. static_cast<time_t>((std::min)(static_cast<long long>(
  3237. (std::numeric_limits<time_t>::max)()),
  3238. 10000000000LL)),
  3239. 0);
  3240. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3241. auto peer = listener.accept();
  3242. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3243. ASSERT_NE(INVALID_SOCKET, peer);
  3244. ASSERT_TRUE(receives_a_byte(peer));
  3245. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3246. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3247. "Connection: close\r\n\r\nok";
  3248. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3249. auto result = res.get();
  3250. ASSERT_TRUE(result);
  3251. EXPECT_EQ("ok", result->body);
  3252. }
  3253. static std::string remove_whitespace(const std::string &input) {
  3254. std::string output;
  3255. output.reserve(input.size());
  3256. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3257. [](unsigned char c) { return !std::isspace(c); });
  3258. return output;
  3259. }
  3260. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3261. auto host = "httpbingo.org";
  3262. auto path = std::string{"/basic-auth/hello/world"};
  3263. #ifdef CPPHTTPLIB_SSL_ENABLED
  3264. auto port = 443;
  3265. SSLClient cli(host, port);
  3266. #else
  3267. auto port = 80;
  3268. Client cli(host, port);
  3269. #endif
  3270. {
  3271. auto res = retry_service_failures([&] { return cli.Get(path); });
  3272. SKIP_ON_SERVICE_FAILURE(res);
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3275. }
  3276. {
  3277. auto res = retry_service_failures([&] {
  3278. return cli.Get(
  3279. path, Headers{make_basic_authentication_header("hello", "world")});
  3280. });
  3281. SKIP_ON_SERVICE_FAILURE(res);
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. auto body = remove_whitespace(res->body);
  3284. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3285. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. }
  3288. {
  3289. cli.set_basic_auth("hello", "world");
  3290. auto res = retry_service_failures([&] { return cli.Get(path); });
  3291. SKIP_ON_SERVICE_FAILURE(res);
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. auto body = remove_whitespace(res->body);
  3294. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3295. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. {
  3299. cli.set_basic_auth("hello", "bad");
  3300. auto res = retry_service_failures([&] { return cli.Get(path); });
  3301. SKIP_ON_SERVICE_FAILURE(res);
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3304. }
  3305. {
  3306. cli.set_basic_auth("bad", "world");
  3307. auto res = retry_service_failures([&] { return cli.Get(path); });
  3308. SKIP_ON_SERVICE_FAILURE(res);
  3309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3310. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3311. }
  3312. }
  3313. #ifdef CPPHTTPLIB_SSL_ENABLED
  3314. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3315. auto host = "httpbingo.org";
  3316. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3317. auto paths = std::vector<std::string>{
  3318. "/digest-auth/auth/hello/world/MD5",
  3319. "/digest-auth/auth/hello/world/SHA-256",
  3320. };
  3321. auto port = 443;
  3322. SSLClient cli(host, port);
  3323. {
  3324. auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
  3325. SKIP_ON_SERVICE_FAILURE(res);
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3328. }
  3329. {
  3330. cli.set_digest_auth("hello", "world");
  3331. for (const auto &path : paths) {
  3332. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3333. SKIP_ON_SERVICE_FAILURE(res);
  3334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3335. auto body = remove_whitespace(res->body);
  3336. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3337. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. }
  3340. cli.set_digest_auth("hello", "bad");
  3341. for (const auto &path : paths) {
  3342. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3343. SKIP_ON_SERVICE_FAILURE(res);
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3346. }
  3347. }
  3348. }
  3349. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3350. // comma-separated list of challenges, and each challenge may itself carry a
  3351. // comma-separated auth-param list, so a server can legally offer Basic
  3352. // before Digest, either as two field lines or packed into one. Runs one 401
  3353. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3354. // value() joins them in receipt order) and checks that the retry carries a
  3355. // well-formed Digest Authorization header naming expected_realm.
  3356. static void
  3357. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3358. const std::string &expected_realm) {
  3359. std::atomic<int> hits{0};
  3360. Server svr;
  3361. svr.Get("/x", [&](const Request &req, Response &res) {
  3362. if (++hits == 1) {
  3363. res.status = StatusCode::Unauthorized_401;
  3364. for (const auto &challenge : challenges) {
  3365. res.set_header("WWW-Authenticate", challenge);
  3366. }
  3367. } else {
  3368. auto authorization = req.get_header_value("Authorization");
  3369. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3370. EXPECT_NE(std::string::npos,
  3371. authorization.find("realm=\"" + expected_realm + "\""));
  3372. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3373. res.set_content("ok", "text/plain");
  3374. }
  3375. });
  3376. auto port = svr.bind_to_any_port(HOST);
  3377. std::thread t([&]() { svr.listen_after_bind(); });
  3378. auto se = detail::scope_exit([&] {
  3379. svr.stop();
  3380. t.join();
  3381. });
  3382. svr.wait_until_ready();
  3383. Client cli(HOST, port);
  3384. cli.set_digest_auth("hello", "world");
  3385. auto res = cli.Get("/x");
  3386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3387. EXPECT_EQ(2, hits.load());
  3388. }
  3389. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3390. static const char *kDigestChallenge =
  3391. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3392. "algorithm=MD5";
  3393. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3394. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3395. "testrealm");
  3396. }
  3397. // Same challenge list with the schemes in the opposite order, to make sure
  3398. // the fix above didn't just special-case "Basic first".
  3399. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3400. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3401. "testrealm");
  3402. }
  3403. // A comma inside a quoted auth-param value must not be mistaken for the
  3404. // separator between two challenges (or two auth-params).
  3405. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3406. run_digest_challenge_list_test(
  3407. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3408. "algorithm=MD5"},
  3409. "test,realm");
  3410. }
  3411. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3412. // the params and leaves out the fragment.
  3413. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3414. Server svr;
  3415. std::string uri, target;
  3416. svr.Get("/a b", [&](const Request &req, Response &res) {
  3417. auto auth = req.get_header_value("Authorization");
  3418. if (auth.empty()) {
  3419. res.status = StatusCode::Unauthorized_401;
  3420. res.set_header("WWW-Authenticate",
  3421. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3422. return;
  3423. }
  3424. auto b = auth.find("uri=\"") + 5;
  3425. uri = auth.substr(b, auth.find('"', b) - b);
  3426. target = req.target;
  3427. });
  3428. auto port = svr.bind_to_any_port(HOST);
  3429. std::thread t([&]() { svr.listen_after_bind(); });
  3430. auto se = detail::scope_exit([&] {
  3431. svr.stop();
  3432. t.join();
  3433. });
  3434. svr.wait_until_ready();
  3435. Client cli(HOST, port);
  3436. cli.set_digest_auth("hello", "world");
  3437. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3439. EXPECT_EQ("/a%20b?x=1", target);
  3440. EXPECT_EQ(target, uri);
  3441. }
  3442. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3443. // make_digest_authentication_header() dereferences both unconditionally, so
  3444. // a server sending a challenge missing either one must not be treated as
  3445. // usable -- doing so used to crash the client with std::out_of_range.
  3446. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3447. Server svr;
  3448. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3449. res.status = StatusCode::Unauthorized_401;
  3450. res.set_header("WWW-Authenticate", challenge);
  3451. });
  3452. auto port = svr.bind_to_any_port(HOST);
  3453. std::thread t([&]() { svr.listen_after_bind(); });
  3454. auto se = detail::scope_exit([&] {
  3455. svr.stop();
  3456. t.join();
  3457. });
  3458. svr.wait_until_ready();
  3459. Client cli(HOST, port);
  3460. cli.set_digest_auth("hello", "world");
  3461. auto res = cli.Get("/x");
  3462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3463. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3464. }
  3465. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3466. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3467. }
  3468. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3469. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3470. }
  3471. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3472. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3473. }
  3474. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3475. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3476. // when storing the values, so the header builder has to re-escape them (and
  3477. // keep algorithm a bare token); otherwise the value breaks out of its
  3478. // quoted-string and injects extra auth-params into the client's Authorization.
  3479. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3480. std::atomic<int> hits{0};
  3481. std::string authorization;
  3482. Server svr;
  3483. svr.Get("/x", [&](const Request &req, Response &res) {
  3484. if (++hits == 1) {
  3485. res.status = StatusCode::Unauthorized_401;
  3486. // On the wire the quotes embedded in the values are backslash-escaped.
  3487. res.set_header("WWW-Authenticate",
  3488. "Digest realm=\"testrealm\", "
  3489. "nonce=\"n\\\"; injected=\\\"x\", "
  3490. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3491. } else {
  3492. authorization = req.get_header_value("Authorization");
  3493. res.set_content("ok", "text/plain");
  3494. }
  3495. });
  3496. auto port = svr.bind_to_any_port(HOST);
  3497. std::thread t([&]() { svr.listen_after_bind(); });
  3498. auto se = detail::scope_exit([&] {
  3499. svr.stop();
  3500. t.join();
  3501. });
  3502. svr.wait_until_ready();
  3503. Client cli(HOST, port);
  3504. cli.set_digest_auth("hello", "world");
  3505. auto res = cli.Get("/x");
  3506. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3507. EXPECT_EQ(2, hits.load());
  3508. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3509. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3510. // inside its quoted-string rather than starting an "injected" auth-param.
  3511. EXPECT_NE(std::string::npos,
  3512. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3513. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3514. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3515. }
  3516. #endif
  3517. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3518. auto host = "google.com";
  3519. auto another_host = "example.com";
  3520. auto wrong_ip = "0.0.0.0";
  3521. #ifdef CPPHTTPLIB_SSL_ENABLED
  3522. SSLClient cli(host);
  3523. #else
  3524. Client cli(host);
  3525. #endif
  3526. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3527. auto res = cli.Get("/");
  3528. // Any status: Google may redirect or rate-limit CI runners.
  3529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3530. }
  3531. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3532. auto host = "google.com";
  3533. auto wrong_ip = "0.0.0.0";
  3534. #ifdef CPPHTTPLIB_SSL_ENABLED
  3535. SSLClient cli(host);
  3536. #else
  3537. Client cli(host);
  3538. #endif
  3539. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3540. auto res = cli.Get("/");
  3541. ASSERT_TRUE(!res);
  3542. EXPECT_EQ(Error::Connection, res.error());
  3543. }
  3544. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3545. // A mapped value that is not an IP literal must be resolved. "localhost"
  3546. // resolves from the hosts file, so this test needs no external DNS.
  3547. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3548. auto host = "target.invalid";
  3549. Server svr;
  3550. std::string received_host;
  3551. svr.Get("/hi", [&](const Request &req, Response &res) {
  3552. received_host = req.get_header_value("Host");
  3553. res.set_content("Hello World!", "text/plain");
  3554. });
  3555. auto port = svr.bind_to_any_port(HOST);
  3556. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3557. auto se = detail::scope_exit([&] {
  3558. svr.stop();
  3559. thread.join();
  3560. ASSERT_FALSE(svr.is_running());
  3561. });
  3562. svr.wait_until_ready();
  3563. Client cli(host, port);
  3564. cli.set_direct_hostname_addr_map({{host, HOST}});
  3565. auto res = cli.Get("/hi");
  3566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3567. EXPECT_EQ(StatusCode::OK_200, res->status);
  3568. // The mapping only redirects the connection; the identity stays host_.
  3569. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3570. }
  3571. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3572. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3573. auto host = "target.invalid";
  3574. Server svr;
  3575. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3576. res.set_content("Hello World!", "text/plain");
  3577. });
  3578. auto port = svr.bind_to_any_port("127.0.0.1");
  3579. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3580. auto se = detail::scope_exit([&] {
  3581. svr.stop();
  3582. thread.join();
  3583. ASSERT_FALSE(svr.is_running());
  3584. });
  3585. svr.wait_until_ready();
  3586. Client cli(host, port);
  3587. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3588. auto res = cli.Get("/hi");
  3589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3590. EXPECT_EQ(StatusCode::OK_200, res->status);
  3591. }
  3592. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3593. // An empty mapped value must leave host_ as the connection target. Without
  3594. // that guard the empty value would become the host argument, getaddrinfo
  3595. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3596. // loopback - silently connecting somewhere the caller never asked for.
  3597. // The server listens on loopback, so such a fallback would succeed and is
  3598. // therefore observable as a failure of this test.
  3599. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3600. Server svr;
  3601. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3602. res.set_content("Hello World!", "text/plain");
  3603. });
  3604. auto port = svr.bind_to_any_port(HOST);
  3605. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3606. auto se = detail::scope_exit([&] {
  3607. svr.stop();
  3608. thread.join();
  3609. ASSERT_FALSE(svr.is_running());
  3610. });
  3611. svr.wait_until_ready();
  3612. Client cli(blackhole, port);
  3613. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3614. cli.set_connection_timeout(1);
  3615. auto res = cli.Get("/hi");
  3616. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3617. }
  3618. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3619. auto host = "target.invalid";
  3620. Server svr;
  3621. std::string received_host;
  3622. svr.Get("/hi", [&](const Request &req, Response &res) {
  3623. received_host = req.get_header_value("Host");
  3624. res.set_content("Hello World!", "text/plain");
  3625. });
  3626. auto port = svr.bind_to_any_port("127.0.0.1");
  3627. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3628. auto se = detail::scope_exit([&] {
  3629. svr.stop();
  3630. thread.join();
  3631. ASSERT_FALSE(svr.is_running());
  3632. });
  3633. svr.wait_until_ready();
  3634. Client cli(host, port);
  3635. #pragma GCC diagnostic push
  3636. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3637. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3638. #pragma GCC diagnostic pop
  3639. auto res = cli.Get("/hi");
  3640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3641. EXPECT_EQ(StatusCode::OK_200, res->status);
  3642. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3643. }
  3644. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3645. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3646. Server svr;
  3647. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3648. res.set_content("Hello World!", "text/plain");
  3649. });
  3650. auto port = svr.bind_to_any_port("127.0.0.1");
  3651. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3652. auto se = detail::scope_exit([&] {
  3653. svr.stop();
  3654. thread.join();
  3655. ASSERT_FALSE(svr.is_running());
  3656. });
  3657. svr.wait_until_ready();
  3658. Client cli("127.0.0.1", port);
  3659. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3660. cli.set_connection_timeout(1);
  3661. auto res = cli.Get("/hi");
  3662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3663. EXPECT_EQ(StatusCode::OK_200, res->status);
  3664. }
  3665. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3666. auto host = "httpbingo.org";
  3667. auto path = std::string{"/absolute-redirect/3"};
  3668. #ifdef CPPHTTPLIB_SSL_ENABLED
  3669. SSLClient cli(host);
  3670. #else
  3671. Client cli(host);
  3672. #endif
  3673. cli.set_follow_location(true);
  3674. auto res = retry_service_failures([&] { return cli.Get(path); });
  3675. SKIP_ON_SERVICE_FAILURE(res);
  3676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3677. EXPECT_EQ(StatusCode::OK_200, res->status);
  3678. }
  3679. TEST(RedirectTest, Redirect_Online) {
  3680. auto host = "httpbingo.org";
  3681. auto path = std::string{"/redirect/3"};
  3682. #ifdef CPPHTTPLIB_SSL_ENABLED
  3683. SSLClient cli(host);
  3684. #else
  3685. Client cli(host);
  3686. #endif
  3687. cli.set_follow_location(true);
  3688. auto res = retry_service_failures([&] { return cli.Get(path); });
  3689. SKIP_ON_SERVICE_FAILURE(res);
  3690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3691. EXPECT_EQ(StatusCode::OK_200, res->status);
  3692. }
  3693. TEST(RelativeRedirectTest, Redirect_Online) {
  3694. auto host = "httpbingo.org";
  3695. auto path = std::string{"/relative-redirect/3"};
  3696. #ifdef CPPHTTPLIB_SSL_ENABLED
  3697. SSLClient cli(host);
  3698. #else
  3699. Client cli(host);
  3700. #endif
  3701. cli.set_follow_location(true);
  3702. auto res = retry_service_failures([&] { return cli.Get(path); });
  3703. SKIP_ON_SERVICE_FAILURE(res);
  3704. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3705. EXPECT_EQ(StatusCode::OK_200, res->status);
  3706. }
  3707. TEST(TooManyRedirectTest, Redirect_Online) {
  3708. auto host = "httpbingo.org";
  3709. auto path = std::string{"/redirect/21"};
  3710. #ifdef CPPHTTPLIB_SSL_ENABLED
  3711. SSLClient cli(host);
  3712. #else
  3713. Client cli(host);
  3714. #endif
  3715. cli.set_follow_location(true);
  3716. auto res = retry_service_failures([&] { return cli.Get(path); });
  3717. SKIP_ON_SERVICE_FAILURE(res);
  3718. ASSERT_TRUE(!res);
  3719. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3720. }
  3721. #ifdef CPPHTTPLIB_SSL_ENABLED
  3722. TEST(YahooRedirectTest, Redirect_Online) {
  3723. Client cli("yahoo.com");
  3724. auto res = cli.Get("/");
  3725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3726. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3727. cli.set_follow_location(true);
  3728. res = cli.Get("/");
  3729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3730. EXPECT_EQ(StatusCode::OK_200, res->status);
  3731. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3732. }
  3733. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3734. #define REDIR_HOST "httpbingo.org"
  3735. #define REDIR_PATH "/redirect-to"
  3736. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3737. SSLClient cli(REDIR_HOST);
  3738. cli.set_follow_location(true);
  3739. auto res = retry_service_failures([&] {
  3740. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3741. });
  3742. SKIP_ON_SERVICE_FAILURE(res);
  3743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3744. EXPECT_EQ(StatusCode::OK_200, res->status);
  3745. }
  3746. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3747. SSLClient cli(REDIR_HOST);
  3748. cli.set_follow_location(true);
  3749. Params params;
  3750. params.emplace("url", "http://example.com");
  3751. params.emplace("status_code", "302");
  3752. auto res = retry_service_failures(
  3753. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3754. SKIP_ON_SERVICE_FAILURE(res);
  3755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3756. EXPECT_EQ(StatusCode::OK_200, res->status);
  3757. }
  3758. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3759. SSLClient cli(REDIR_HOST);
  3760. cli.set_follow_location(true);
  3761. Params params;
  3762. params.emplace("url", "http://example.com");
  3763. auto res = retry_service_failures([&] {
  3764. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3765. });
  3766. SKIP_ON_SERVICE_FAILURE(res);
  3767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3768. EXPECT_EQ(StatusCode::OK_200, res->status);
  3769. }
  3770. TEST(UrlWithSpace, Redirect_Online) {
  3771. SSLClient cli("edge.forgecdn.net");
  3772. cli.set_follow_location(true);
  3773. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3774. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3775. EXPECT_EQ(StatusCode::OK_200, res->status);
  3776. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3777. }
  3778. #endif
  3779. #if !defined(_WIN32) && !defined(_WIN64)
  3780. TEST(ReceiveSignals, Signal) {
  3781. auto setupSignalHandlers = []() {
  3782. struct sigaction act;
  3783. sigemptyset(&act.sa_mask);
  3784. act.sa_flags = SA_SIGINFO;
  3785. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3786. switch (sig) {
  3787. case SIGINT:
  3788. default: break;
  3789. }
  3790. };
  3791. ::sigaction(SIGINT, &act, nullptr);
  3792. };
  3793. Server svr;
  3794. int port = 0;
  3795. auto thread = std::thread([&]() {
  3796. setupSignalHandlers();
  3797. port = svr.bind_to_any_port(HOST);
  3798. svr.listen_after_bind();
  3799. });
  3800. auto se = detail::scope_exit([&] {
  3801. svr.stop();
  3802. thread.join();
  3803. ASSERT_FALSE(svr.is_running());
  3804. });
  3805. svr.wait_until_ready();
  3806. ASSERT_TRUE(svr.is_running());
  3807. pthread_kill(thread.native_handle(), SIGINT);
  3808. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3809. ASSERT_TRUE(svr.is_running());
  3810. }
  3811. #endif
  3812. TEST(RedirectToDifferentPort, Redirect) {
  3813. Server svr1;
  3814. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3815. res.set_content("Hello World!", "text/plain");
  3816. });
  3817. int svr1_port = 0;
  3818. auto thread1 = std::thread([&]() {
  3819. svr1_port = svr1.bind_to_any_port(HOST);
  3820. svr1.listen_after_bind();
  3821. });
  3822. Server svr2;
  3823. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3824. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3825. });
  3826. int svr2_port = 0;
  3827. auto thread2 = std::thread([&]() {
  3828. svr2_port = svr2.bind_to_any_port(HOST);
  3829. svr2.listen_after_bind();
  3830. });
  3831. auto se = detail::scope_exit([&] {
  3832. svr2.stop();
  3833. thread2.join();
  3834. svr1.stop();
  3835. thread1.join();
  3836. ASSERT_FALSE(svr2.is_running());
  3837. ASSERT_FALSE(svr1.is_running());
  3838. });
  3839. svr1.wait_until_ready();
  3840. svr2.wait_until_ready();
  3841. Client cli("localhost", svr2_port);
  3842. cli.set_follow_location(true);
  3843. auto res = cli.Get("/2");
  3844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3845. EXPECT_EQ(StatusCode::OK_200, res->status);
  3846. EXPECT_EQ("Hello World!", res->body);
  3847. }
  3848. // GET /redir on one server redirects to /target on another port, so the
  3849. // client follows it with a new client.
  3850. static Result
  3851. GetThroughRedirectToDifferentPort(Server::Handler target,
  3852. const std::function<void(Client &)> &setup,
  3853. const Headers &headers = Headers()) {
  3854. Server target_svr;
  3855. target_svr.Get("/target", target);
  3856. int target_port = 0;
  3857. auto target_thread = std::thread([&]() {
  3858. target_port = target_svr.bind_to_any_port(HOST);
  3859. target_svr.listen_after_bind();
  3860. });
  3861. Server origin_svr;
  3862. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3863. res.set_redirect(
  3864. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3865. });
  3866. int origin_port = 0;
  3867. auto origin_thread = std::thread([&]() {
  3868. origin_port = origin_svr.bind_to_any_port(HOST);
  3869. origin_svr.listen_after_bind();
  3870. });
  3871. auto se = detail::scope_exit([&] {
  3872. origin_svr.stop();
  3873. origin_thread.join();
  3874. target_svr.stop();
  3875. target_thread.join();
  3876. });
  3877. target_svr.wait_until_ready();
  3878. origin_svr.wait_until_ready();
  3879. Client cli("localhost", origin_port);
  3880. cli.set_follow_location(true);
  3881. setup(cli);
  3882. return cli.Get("/redir", headers);
  3883. }
  3884. static void
  3885. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3886. std::string captured_authorization;
  3887. auto result = GetThroughRedirectToDifferentPort(
  3888. [&](const Request &req, Response &res) {
  3889. captured_authorization = req.get_header_value("Authorization");
  3890. res.set_content("OK", "text/plain");
  3891. },
  3892. set_auth);
  3893. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3894. EXPECT_EQ(StatusCode::OK_200, result->status);
  3895. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3896. EXPECT_TRUE(captured_authorization.empty());
  3897. }
  3898. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3899. TestDoNotForwardCredentialsOnRedirect(
  3900. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3901. }
  3902. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3903. TestDoNotForwardCredentialsOnRedirect(
  3904. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3905. }
  3906. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3907. std::string captured_cookie;
  3908. auto result = GetThroughRedirectToDifferentPort(
  3909. [&](const Request &req, Response &res) {
  3910. captured_cookie = req.get_header_value("Cookie");
  3911. res.set_content("OK", "text/plain");
  3912. },
  3913. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3914. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3915. EXPECT_EQ(StatusCode::OK_200, result->status);
  3916. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3917. EXPECT_TRUE(captured_cookie.empty());
  3918. }
  3919. TEST(RedirectToSamePort, ForwardCookie) {
  3920. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3921. // header so that ordinary session flows keep working.
  3922. Server svr;
  3923. std::string captured_cookie;
  3924. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3925. res.set_redirect("/target", 302);
  3926. });
  3927. svr.Get("/target", [&](const Request &req, Response &res) {
  3928. captured_cookie = req.get_header_value("Cookie");
  3929. res.set_content("OK", "text/plain");
  3930. });
  3931. auto port = svr.bind_to_any_port(HOST);
  3932. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3933. auto se = detail::scope_exit([&] {
  3934. svr.stop();
  3935. thread.join();
  3936. ASSERT_FALSE(svr.is_running());
  3937. });
  3938. svr.wait_until_ready();
  3939. Client cli(HOST, port);
  3940. cli.set_follow_location(true);
  3941. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3942. auto res = cli.Get("/redir", headers);
  3943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3944. EXPECT_EQ(StatusCode::OK_200, res->status);
  3945. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3946. }
  3947. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3948. // The Location alone names the next target, on any origin.
  3949. Server target_svr;
  3950. std::string cross_target;
  3951. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3952. cross_target = req.target;
  3953. res.set_content("OK", "text/plain");
  3954. });
  3955. auto target_port = target_svr.bind_to_any_port(HOST);
  3956. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3957. Server origin_svr;
  3958. std::string same_target;
  3959. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3960. res.set_redirect(
  3961. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3962. });
  3963. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3964. res.set_redirect("/landing", 302);
  3965. });
  3966. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  3967. same_target = req.target;
  3968. res.set_content("OK", "text/plain");
  3969. });
  3970. auto origin_port = origin_svr.bind_to_any_port(HOST);
  3971. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  3972. auto se = detail::scope_exit([&] {
  3973. origin_svr.stop();
  3974. origin_thread.join();
  3975. target_svr.stop();
  3976. target_thread.join();
  3977. });
  3978. target_svr.wait_until_ready();
  3979. origin_svr.wait_until_ready();
  3980. Client cli("localhost", origin_port);
  3981. cli.set_follow_location(true);
  3982. Request req;
  3983. req.method = "GET";
  3984. req.params = {{"api_key", "SECRET"}};
  3985. req.path = "/cross";
  3986. auto res = cli.send(req);
  3987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3988. EXPECT_EQ("/landing", cross_target);
  3989. req.path = "/same";
  3990. res = cli.send(req);
  3991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3992. EXPECT_EQ("/landing", same_target);
  3993. }
  3994. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3995. std::string authorization;
  3996. std::string trace_id;
  3997. auto result = GetThroughRedirectToDifferentPort(
  3998. [&](const Request &req, Response &res) {
  3999. authorization = req.get_header_value("Authorization");
  4000. trace_id = req.get_header_value("X-Trace-Id");
  4001. res.set_content("OK", "text/plain");
  4002. },
  4003. [](Client &cli) {
  4004. cli.set_default_headers(
  4005. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4006. });
  4007. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4008. EXPECT_EQ(StatusCode::OK_200, result->status);
  4009. // Like a header given with the request, a default one goes along unless it
  4010. // carries credentials (RFC 9110 15.4).
  4011. EXPECT_TRUE(authorization.empty());
  4012. EXPECT_EQ("42", trace_id);
  4013. }
  4014. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4015. auto result = GetThroughRedirectToDifferentPort(
  4016. [](const Request &, Response &res) {
  4017. res.set_content(std::string(2048, 'x'), "text/plain");
  4018. },
  4019. [](Client &cli) { cli.set_payload_max_length(1024); });
  4020. EXPECT_FALSE(result);
  4021. }
  4022. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4023. auto result = GetThroughRedirectToDifferentPort(
  4024. [](const Request &req, Response &res) {
  4025. // Answer after a second, or once the client gives up.
  4026. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4027. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4028. }
  4029. res.set_content("late", "text/plain");
  4030. },
  4031. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4032. ASSERT_FALSE(result);
  4033. EXPECT_EQ(Error::Read, result.error());
  4034. }
  4035. #ifdef CPPHTTPLIB_SSL_ENABLED
  4036. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4037. auto result = GetThroughRedirectToDifferentPort(
  4038. [](const Request &, Response &res) {
  4039. res.status = StatusCode::Unauthorized_401;
  4040. res.set_header("WWW-Authenticate",
  4041. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4042. },
  4043. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4044. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4045. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4046. }
  4047. #endif
  4048. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4049. Server svr;
  4050. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4051. // Port number that overflows int — should not crash
  4052. res.set_redirect("http://localhost:99999999999999999999/target");
  4053. });
  4054. auto port = svr.bind_to_any_port(HOST);
  4055. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4056. auto se = detail::scope_exit([&] {
  4057. svr.stop();
  4058. thread.join();
  4059. ASSERT_FALSE(svr.is_running());
  4060. });
  4061. svr.wait_until_ready();
  4062. Client cli(HOST, port);
  4063. cli.set_follow_location(true);
  4064. auto res = cli.Get("/redir");
  4065. // Should fail gracefully, not crash (no valid response due to bad port)
  4066. EXPECT_FALSE(res);
  4067. }
  4068. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4069. Server svr;
  4070. auto port = svr.bind_to_any_port(HOST);
  4071. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4072. // The server's own port followed by junk must not be followed
  4073. res.set_redirect("http://" + std::string(HOST) + ":" +
  4074. std::to_string(port) + "junk/target");
  4075. });
  4076. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4077. res.set_content("target", "text/plain");
  4078. });
  4079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4080. auto se = detail::scope_exit([&] {
  4081. svr.stop();
  4082. thread.join();
  4083. ASSERT_FALSE(svr.is_running());
  4084. });
  4085. svr.wait_until_ready();
  4086. Client cli(HOST, port);
  4087. cli.set_follow_location(true);
  4088. auto res = cli.Get("/redir");
  4089. EXPECT_FALSE(res);
  4090. }
  4091. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4092. Server target_svr;
  4093. std::atomic<int> target_hits{0};
  4094. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4095. target_hits++;
  4096. res.set_content("target", "text/plain");
  4097. });
  4098. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4099. res.set_content("target", "text/plain");
  4100. });
  4101. int target_port = 0;
  4102. auto target_thread = std::thread([&]() {
  4103. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4104. target_svr.listen_after_bind();
  4105. });
  4106. Server origin_svr;
  4107. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4108. res.set_redirect(req.get_param_value("to"));
  4109. });
  4110. int origin_port = 0;
  4111. auto origin_thread = std::thread([&]() {
  4112. origin_port = origin_svr.bind_to_any_port(HOST);
  4113. origin_svr.listen_after_bind();
  4114. });
  4115. auto se = detail::scope_exit([&] {
  4116. origin_svr.stop();
  4117. origin_thread.join();
  4118. target_svr.stop();
  4119. target_thread.join();
  4120. ASSERT_FALSE(origin_svr.is_running());
  4121. ASSERT_FALSE(target_svr.is_running());
  4122. });
  4123. target_svr.wait_until_ready();
  4124. origin_svr.wait_until_ready();
  4125. auto port = std::to_string(target_port);
  4126. for (const auto &to :
  4127. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4128. Client cli(HOST, origin_port);
  4129. cli.set_follow_location(true);
  4130. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4131. EXPECT_FALSE(res) << to;
  4132. }
  4133. EXPECT_EQ(0, target_hits);
  4134. Client cli(HOST, origin_port);
  4135. cli.set_follow_location(true);
  4136. auto res = cli.Get("/redir?to=" +
  4137. encode_query_component("//127.0.0.1:" + port + "/target"));
  4138. ASSERT_TRUE(res) << to_string(res.error());
  4139. EXPECT_EQ(StatusCode::OK_200, res->status);
  4140. EXPECT_EQ("target", res->body);
  4141. }
  4142. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4143. Server svr;
  4144. std::atomic<bool> followed{false};
  4145. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4146. res.status = StatusCode::NotModified_304;
  4147. res.set_header("Location", "/target");
  4148. });
  4149. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4150. res.status = StatusCode::UseProxy_305;
  4151. res.set_header("Location", "/target");
  4152. });
  4153. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4154. followed = true;
  4155. res.set_content("target", "text/plain");
  4156. });
  4157. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4158. auto se = detail::scope_exit([&] {
  4159. svr.stop();
  4160. th.join();
  4161. ASSERT_FALSE(svr.is_running());
  4162. });
  4163. svr.wait_until_ready();
  4164. Client cli("localhost", PORT);
  4165. cli.set_follow_location(true);
  4166. auto res = cli.Get("/304");
  4167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4168. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4169. res = cli.Get("/305");
  4170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4171. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4172. EXPECT_FALSE(followed);
  4173. }
  4174. TEST(RedirectFromPageWithContent, Redirect) {
  4175. Server svr;
  4176. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4177. res.set_content("___", "text/plain");
  4178. res.set_redirect("/2");
  4179. });
  4180. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4181. res.set_content("Hello World!", "text/plain");
  4182. });
  4183. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4184. auto se = detail::scope_exit([&] {
  4185. svr.stop();
  4186. th.join();
  4187. ASSERT_FALSE(svr.is_running());
  4188. });
  4189. svr.wait_until_ready();
  4190. {
  4191. Client cli("localhost", PORT);
  4192. cli.set_follow_location(true);
  4193. std::string body;
  4194. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4195. body.append(data, data_length);
  4196. return true;
  4197. });
  4198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4199. EXPECT_EQ(StatusCode::OK_200, res->status);
  4200. EXPECT_EQ("Hello World!", body);
  4201. }
  4202. {
  4203. Client cli("localhost", PORT);
  4204. std::string body;
  4205. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4206. body.append(data, data_length);
  4207. return true;
  4208. });
  4209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4210. EXPECT_EQ(StatusCode::Found_302, res->status);
  4211. EXPECT_EQ("___", body);
  4212. }
  4213. }
  4214. // A server can close the connection after a request with "Connection: close"
  4215. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4216. // redirected request must go out on a new connection.
  4217. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4218. #ifndef _WIN32
  4219. signal(SIGPIPE, SIG_IGN);
  4220. #endif
  4221. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4222. default_socket_options(srv);
  4223. sockaddr_in addr{};
  4224. addr.sin_family = AF_INET;
  4225. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4226. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4227. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4228. ASSERT_EQ(0, ::listen(srv, 2));
  4229. auto send_text = [](socket_t sock, const std::string &text) {
  4230. ::send(sock,
  4231. #ifdef _WIN32
  4232. static_cast<const char *>(text.c_str()),
  4233. static_cast<int>(text.size()),
  4234. #else
  4235. text.c_str(), text.size(),
  4236. #endif
  4237. 0);
  4238. };
  4239. auto reused = false;
  4240. auto server_thread = std::thread([&] {
  4241. char buf[4096];
  4242. auto first = ::accept(srv, nullptr, nullptr);
  4243. if (first == INVALID_SOCKET) { return; }
  4244. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4245. ::recv(first, buf, sizeof(buf), 0);
  4246. send_text(
  4247. first,
  4248. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4249. auto next = first;
  4250. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4251. reused = true;
  4252. } else {
  4253. detail::close_socket(first);
  4254. next = ::accept(srv, nullptr, nullptr);
  4255. if (next == INVALID_SOCKET) { return; }
  4256. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4257. ::recv(next, buf, sizeof(buf), 0);
  4258. }
  4259. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4260. "Connection: close\r\n\r\nok");
  4261. detail::close_socket(next);
  4262. });
  4263. Client cli("127.0.0.1", PORT + 2);
  4264. cli.set_follow_location(true);
  4265. cli.set_read_timeout(5, 0);
  4266. auto res = cli.Get("/1");
  4267. server_thread.join();
  4268. detail::close_socket(srv);
  4269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4270. EXPECT_EQ(StatusCode::OK_200, res->status);
  4271. EXPECT_EQ("ok", res->body);
  4272. EXPECT_FALSE(reused);
  4273. }
  4274. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4275. Server svr;
  4276. auto port_str = std::to_string(PORT);
  4277. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4278. auto expected_host = "[::1]:" + port_str;
  4279. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4280. res.set_content("___", "text/plain");
  4281. // res.set_redirect("/2");
  4282. res.set_redirect(redirect_url);
  4283. });
  4284. svr.Get("/2", [&](const Request &req, Response &res) {
  4285. auto host_header = req.headers.find("Host");
  4286. ASSERT_TRUE(host_header != req.headers.end());
  4287. EXPECT_EQ(expected_host, host_header->second);
  4288. res.set_content("Hello World!", "text/plain");
  4289. });
  4290. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4291. auto se = detail::scope_exit([&] {
  4292. svr.stop();
  4293. th.join();
  4294. ASSERT_FALSE(svr.is_running());
  4295. });
  4296. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4297. // actually starts anything, so the condition !svr.is_running() will
  4298. // always remain true, and the loop never stops.
  4299. // This basically counts how many milliseconds have passed since the
  4300. // call to svr.listen(), and if after 5 seconds nothing started yet
  4301. // aborts the test.
  4302. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4303. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4304. ASSERT_LT(milliseconds, 5000U);
  4305. }
  4306. {
  4307. Client cli("::1", PORT);
  4308. cli.set_follow_location(true);
  4309. std::string body;
  4310. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4311. body.append(data, data_length);
  4312. return true;
  4313. });
  4314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4315. EXPECT_EQ(StatusCode::OK_200, res->status);
  4316. EXPECT_EQ("Hello World!", body);
  4317. }
  4318. {
  4319. Client cli("::1", PORT);
  4320. std::string body;
  4321. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4322. body.append(data, data_length);
  4323. return true;
  4324. });
  4325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4326. EXPECT_EQ(StatusCode::Found_302, res->status);
  4327. EXPECT_EQ("___", body);
  4328. }
  4329. }
  4330. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4331. Server svr;
  4332. svr.Get("/foo", [](const Request &req, Response &res) {
  4333. auto a = req.params.find("a");
  4334. if (a != req.params.end()) {
  4335. res.set_content((*a).second, "text/plain");
  4336. res.status = StatusCode::OK_200;
  4337. } else {
  4338. res.status = StatusCode::BadRequest_400;
  4339. }
  4340. });
  4341. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4342. auto se = detail::scope_exit([&] {
  4343. svr.stop();
  4344. thread.join();
  4345. ASSERT_FALSE(svr.is_running());
  4346. });
  4347. svr.wait_until_ready();
  4348. {
  4349. Client cli(HOST, PORT);
  4350. cli.set_path_encode(false);
  4351. auto res = cli.Get("/foo?a=explicitly+encoded");
  4352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4353. EXPECT_EQ(StatusCode::OK_200, res->status);
  4354. // This expects it back with a space, as the `+` won't have been
  4355. // url-encoded, and server-side the params get decoded turning `+`
  4356. // into spaces.
  4357. EXPECT_EQ("explicitly encoded", res->body);
  4358. }
  4359. }
  4360. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4361. // When path encoding is disabled the client must transmit the supplied
  4362. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4363. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4364. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4365. // than a space (0x20). Assert on the raw wire target to catch this.
  4366. Server svr;
  4367. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4368. svr.Get("/foo", [&](const Request &req, Response &res) {
  4369. EXPECT_EQ(expected_target, req.target);
  4370. res.status = StatusCode::OK_200;
  4371. });
  4372. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4373. auto se = detail::scope_exit([&] {
  4374. svr.stop();
  4375. thread.join();
  4376. ASSERT_FALSE(svr.is_running());
  4377. });
  4378. svr.wait_until_ready();
  4379. {
  4380. Client cli(HOST, PORT);
  4381. cli.set_path_encode(false);
  4382. auto res = cli.Get(expected_target.c_str());
  4383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4384. EXPECT_EQ(StatusCode::OK_200, res->status);
  4385. }
  4386. }
  4387. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4388. // `open_stream()` used to skip the path encoding that the buffered send
  4389. // path applies, so the same `path` produced different bytes in the request
  4390. // line depending on which API was used. Assert the two agree.
  4391. Server svr;
  4392. std::string target;
  4393. svr.Get(".*", [&](const Request &req, Response &res) {
  4394. target = req.target;
  4395. res.status = StatusCode::OK_200;
  4396. });
  4397. auto port = svr.bind_to_any_port(HOST);
  4398. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4399. auto se = detail::scope_exit([&] {
  4400. svr.stop();
  4401. thread.join();
  4402. ASSERT_FALSE(svr.is_running());
  4403. });
  4404. svr.wait_until_ready();
  4405. struct {
  4406. const char *path;
  4407. const char *expected;
  4408. } cases[] = {
  4409. {"/a b?x=1", "/a%20b?x=1"},
  4410. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4411. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4412. };
  4413. for (const auto &c : cases) {
  4414. Client cli(HOST, port);
  4415. target.clear();
  4416. auto res = cli.Get(c.path);
  4417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4418. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4419. auto buffered_target = target;
  4420. target.clear();
  4421. auto handle = cli.open_stream("GET", c.path);
  4422. EXPECT_TRUE(handle.is_valid())
  4423. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4424. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4425. }
  4426. }
  4427. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4428. // The `set_path_encode(false)` contract — transmit the supplied target
  4429. // verbatim — must hold for the streaming API too.
  4430. Server svr;
  4431. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4432. std::string target;
  4433. svr.Get("/foo", [&](const Request &req, Response &res) {
  4434. target = req.target;
  4435. res.status = StatusCode::OK_200;
  4436. });
  4437. auto port = svr.bind_to_any_port(HOST);
  4438. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4439. auto se = detail::scope_exit([&] {
  4440. svr.stop();
  4441. thread.join();
  4442. ASSERT_FALSE(svr.is_running());
  4443. });
  4444. svr.wait_until_ready();
  4445. {
  4446. Client cli(HOST, port);
  4447. cli.set_path_encode(false);
  4448. auto handle = cli.open_stream("GET", expected_target);
  4449. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4450. EXPECT_EQ(expected_target, target);
  4451. }
  4452. }
  4453. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4454. // With path encoding enabled a CR/LF in the target is percent-encoded
  4455. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4456. // write_request_line still backstops `set_path_encode(false)`, which is
  4457. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4458. Server svr;
  4459. // Captured before routing: the decoded path contains a newline, which a
  4460. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4461. std::string target;
  4462. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4463. target = req.target;
  4464. res.status = StatusCode::OK_200;
  4465. return Server::HandlerResponse::Handled;
  4466. });
  4467. auto port = svr.bind_to_any_port(HOST);
  4468. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4469. auto se = detail::scope_exit([&] {
  4470. svr.stop();
  4471. thread.join();
  4472. ASSERT_FALSE(svr.is_running());
  4473. });
  4474. svr.wait_until_ready();
  4475. {
  4476. Client cli(HOST, port);
  4477. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4478. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4479. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4480. }
  4481. }
  4482. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4483. // Every control character is percent-encoded, not just CR/LF, so the target
  4484. // passes the request-target check in write_request_line.
  4485. Server svr;
  4486. std::string target;
  4487. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4488. target = req.target;
  4489. res.status = StatusCode::OK_200;
  4490. return Server::HandlerResponse::Handled;
  4491. });
  4492. auto port = svr.bind_to_any_port(HOST);
  4493. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4494. auto se = detail::scope_exit([&] {
  4495. svr.stop();
  4496. thread.join();
  4497. ASSERT_FALSE(svr.is_running());
  4498. });
  4499. svr.wait_until_ready();
  4500. {
  4501. Client cli(HOST, port);
  4502. auto res = cli.Get("/a\tb\x1b\x7f");
  4503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4504. EXPECT_EQ("/a%09b%1B%7F", target);
  4505. }
  4506. }
  4507. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4508. // Nothing may reach the wire: a raw CR/LF target would split the request
  4509. // line and inject headers.
  4510. Server svr;
  4511. // Pre-routing so that "not called" means nothing reached the server at all,
  4512. // rather than merely failing to match a handler pattern.
  4513. auto handler_called = false;
  4514. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4515. handler_called = true;
  4516. res.status = StatusCode::OK_200;
  4517. return Server::HandlerResponse::Handled;
  4518. });
  4519. auto port = svr.bind_to_any_port(HOST);
  4520. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4521. auto se = detail::scope_exit([&] {
  4522. svr.stop();
  4523. thread.join();
  4524. ASSERT_FALSE(svr.is_running());
  4525. });
  4526. svr.wait_until_ready();
  4527. {
  4528. Client cli(HOST, port);
  4529. cli.set_path_encode(false);
  4530. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4531. EXPECT_FALSE(handle.is_valid());
  4532. EXPECT_EQ(Error::Write, handle.error);
  4533. EXPECT_FALSE(handler_called);
  4534. }
  4535. }
  4536. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4537. // Which of the two branches runs is decided by whether the query component
  4538. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4539. // an empty query and must still fall back to building one from
  4540. // `req.params`, while a non-empty query must win over `req.params`.
  4541. Server svr;
  4542. std::string target;
  4543. svr.Get("/foo", [&](const Request &req, Response &res) {
  4544. target = req.target;
  4545. res.status = StatusCode::OK_200;
  4546. });
  4547. auto port = svr.bind_to_any_port(HOST);
  4548. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4549. auto se = detail::scope_exit([&] {
  4550. svr.stop();
  4551. thread.join();
  4552. ASSERT_FALSE(svr.is_running());
  4553. });
  4554. svr.wait_until_ready();
  4555. {
  4556. // Trailing `?` -> empty query component -> `req.params` is used.
  4557. Client cli(HOST, port);
  4558. Request req;
  4559. req.method = "GET";
  4560. req.path = "/foo?";
  4561. req.params.emplace("a", "1");
  4562. target.clear();
  4563. auto res = cli.send(req);
  4564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4565. EXPECT_EQ("/foo?a=1", target);
  4566. }
  4567. {
  4568. // Non-empty query in `req.path` -> `req.params` is not appended.
  4569. Client cli(HOST, port);
  4570. Request req;
  4571. req.method = "GET";
  4572. req.path = "/foo?b=2";
  4573. req.params.emplace("a", "1");
  4574. target.clear();
  4575. auto res = cli.send(req);
  4576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4577. EXPECT_EQ("/foo?b=2", target);
  4578. }
  4579. }
  4580. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4581. Server svr;
  4582. svr.Get("/", [](const Request &req, Response &) {
  4583. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4584. });
  4585. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4586. auto se = detail::scope_exit([&] {
  4587. svr.stop();
  4588. thread.join();
  4589. ASSERT_FALSE(svr.is_running());
  4590. });
  4591. svr.wait_until_ready();
  4592. {
  4593. Client cli(HOST, PORT);
  4594. cli.set_path_encode(false);
  4595. auto res = cli.Get("/?something=%0A");
  4596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4597. EXPECT_EQ(StatusCode::OK_200, res->status);
  4598. }
  4599. }
  4600. TEST(BindServerTest, BindDualStack) {
  4601. Server svr;
  4602. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4603. res.set_content("Hello World!", "text/plain");
  4604. });
  4605. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4606. auto se = detail::scope_exit([&] {
  4607. svr.stop();
  4608. thread.join();
  4609. ASSERT_FALSE(svr.is_running());
  4610. });
  4611. svr.wait_until_ready();
  4612. {
  4613. Client cli("127.0.0.1", PORT);
  4614. auto res = cli.Get("/1");
  4615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4616. EXPECT_EQ(StatusCode::OK_200, res->status);
  4617. EXPECT_EQ("Hello World!", res->body);
  4618. }
  4619. {
  4620. Client cli("::1", PORT);
  4621. auto res = cli.Get("/1");
  4622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4623. EXPECT_EQ(StatusCode::OK_200, res->status);
  4624. EXPECT_EQ("Hello World!", res->body);
  4625. }
  4626. }
  4627. TEST(BindServerTest, BindAndListenSeparately) {
  4628. Server svr;
  4629. int port = svr.bind_to_any_port("0.0.0.0");
  4630. ASSERT_TRUE(svr.is_valid());
  4631. ASSERT_TRUE(port > 0);
  4632. svr.stop();
  4633. }
  4634. // Reports whether anything is still listening on a loopback port. A plain
  4635. // connect() is used instead of a Client request because a socket left bound by
  4636. // mistake accepts the connection into its backlog and never answers, which
  4637. // would hang the test instead of failing it.
  4638. static bool is_loopback_port_accepting(int port) {
  4639. sockaddr_in addr{};
  4640. addr.sin_family = AF_INET;
  4641. addr.sin_port = htons(static_cast<uint16_t>(port));
  4642. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4643. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4644. EXPECT_NE(sock, INVALID_SOCKET);
  4645. if (sock == INVALID_SOCKET) { return false; }
  4646. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4647. static_cast<socklen_t>(sizeof(addr)));
  4648. detail::close_socket(sock);
  4649. return ret == 0;
  4650. }
  4651. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4652. Server svr;
  4653. auto port = svr.bind_to_any_port("127.0.0.1");
  4654. ASSERT_TRUE(port > 0);
  4655. svr.stop();
  4656. // bind_to_any_port() already called listen(2), so until stop() closed the
  4657. // descriptor the port kept accepting connections into the backlog. ASSERT
  4658. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4659. // below blocks forever in the accept loop.
  4660. ASSERT_FALSE(is_loopback_port_accepting(port));
  4661. // Nothing is left to accept on, so listen_after_bind() must report failure
  4662. // instead of returning success without ever serving.
  4663. EXPECT_FALSE(svr.listen_after_bind());
  4664. // The failed listen marks the server decommissioned, so a waiter returns
  4665. // instead of spinning forever.
  4666. svr.wait_until_ready();
  4667. }
  4668. #ifdef CPPHTTPLIB_SSL_ENABLED
  4669. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4671. CLIENT_CA_CERT_DIR);
  4672. int port = svr.bind_to_any_port("0.0.0.0");
  4673. ASSERT_TRUE(svr.is_valid());
  4674. ASSERT_TRUE(port > 0);
  4675. svr.stop();
  4676. }
  4677. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4678. // or a rejected CustomRoute() registration would not stop the server binding.
  4679. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4680. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4681. CLIENT_CA_CERT_DIR);
  4682. ASSERT_TRUE(svr.is_valid());
  4683. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4684. EXPECT_FALSE(svr.is_valid());
  4685. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4686. }
  4687. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4688. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4689. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4690. int port = svr.bind_to_any_port("0.0.0.0");
  4691. ASSERT_TRUE(svr.is_valid());
  4692. ASSERT_TRUE(port > 0);
  4693. svr.stop();
  4694. }
  4695. TEST(BindServerTest, UpdateCertsPem) {
  4696. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4697. int port = svr.bind_to_any_port("0.0.0.0");
  4698. ASSERT_TRUE(svr.is_valid());
  4699. ASSERT_TRUE(port > 0);
  4700. // Read PEM files
  4701. std::string cert_pem, key_pem, ca_pem;
  4702. read_file(SERVER_CERT_FILE, cert_pem);
  4703. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4704. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4705. // Update server certificates using PEM API
  4706. ASSERT_TRUE(
  4707. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4708. ASSERT_TRUE(svr.is_valid());
  4709. svr.stop();
  4710. }
  4711. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4712. // Start server with client CA (enables client auth)
  4713. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4714. ASSERT_TRUE(svr.is_valid());
  4715. bool handler_called = false;
  4716. svr.Get("/test", [&](const Request &req, Response &res) {
  4717. handler_called = true;
  4718. // Verify client certificate is present
  4719. auto cert = req.peer_cert();
  4720. EXPECT_TRUE(static_cast<bool>(cert));
  4721. res.set_content("ok", "text/plain");
  4722. });
  4723. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4724. auto se = detail::scope_exit([&] {
  4725. svr.stop();
  4726. t.join();
  4727. ASSERT_FALSE(svr.is_running());
  4728. });
  4729. svr.wait_until_ready();
  4730. // Read PEM files
  4731. std::string cert_pem, key_pem, ca_pem;
  4732. read_file(SERVER_CERT_FILE, cert_pem);
  4733. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4734. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4735. // Update server certificates and client CA using PEM API while server running
  4736. ASSERT_TRUE(
  4737. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4738. // Connect with client certificate
  4739. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4740. cli.enable_server_certificate_verification(false);
  4741. cli.set_connection_timeout(30);
  4742. auto res = cli.Get("/test");
  4743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4744. ASSERT_EQ(StatusCode::OK_200, res->status);
  4745. ASSERT_TRUE(handler_called);
  4746. EXPECT_EQ("ok", res->body);
  4747. }
  4748. // Puts a CA that did not sign the client's certificate in the old one's place.
  4749. static bool replace_client_ca(SSLServer &svr) {
  4750. std::string cert_pem, key_pem, ca_pem;
  4751. read_file(SERVER_CERT_FILE, cert_pem);
  4752. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4753. read_file(SERVER_CERT2_FILE, ca_pem);
  4754. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4755. ca_pem.c_str());
  4756. }
  4757. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4758. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4759. ASSERT_TRUE(svr.is_valid());
  4760. svr.Get("/test", [](const Request &, Response &res) {
  4761. res.set_content("ok", "text/plain");
  4762. });
  4763. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4764. auto se = detail::scope_exit([&] {
  4765. svr.stop();
  4766. t.join();
  4767. ASSERT_FALSE(svr.is_running());
  4768. });
  4769. svr.wait_until_ready();
  4770. auto get = [] {
  4771. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4772. cli.enable_server_certificate_verification(false);
  4773. return cli.Get("/test");
  4774. };
  4775. ASSERT_TRUE(get());
  4776. ASSERT_TRUE(replace_client_ca(svr));
  4777. EXPECT_FALSE(get());
  4778. }
  4779. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4780. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4781. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4782. ASSERT_TRUE(svr.is_valid());
  4783. tls::set_verify_callback(svr.tls_context(),
  4784. [](const tls::VerifyContext &) -> bool {
  4785. throw std::runtime_error("verify");
  4786. });
  4787. svr.Get("/test", [](const Request &, Response &res) {
  4788. res.set_content("ok", "text/plain");
  4789. });
  4790. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4791. auto se = detail::scope_exit([&] {
  4792. svr.stop();
  4793. t.join();
  4794. ASSERT_FALSE(svr.is_running());
  4795. });
  4796. svr.wait_until_ready();
  4797. auto get = [] {
  4798. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4799. cli.enable_server_certificate_verification(false);
  4800. return cli.Get("/test");
  4801. };
  4802. EXPECT_FALSE(get());
  4803. // The handshake is over, so an update does not wait for it.
  4804. std::string cert_pem, key_pem;
  4805. read_file(SERVER_CERT_FILE, cert_pem);
  4806. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4807. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4808. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4809. return v.preverify_ok;
  4810. });
  4811. auto res = get();
  4812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4813. EXPECT_EQ("ok", res->body);
  4814. }
  4815. #endif
  4816. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4817. // Sends each request over a new connection with a client certificate,
  4818. // resuming the session of the one before when there is one.
  4819. class ResumingClient {
  4820. public:
  4821. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4822. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4823. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4824. SSL_FILETYPE_PEM);
  4825. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4826. // callback, not through SSL_get1_session().
  4827. SSL_CTX_set_app_data(ctx_, this);
  4828. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4829. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4830. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4831. auto self = static_cast<ResumingClient *>(
  4832. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4833. SSL_SESSION_free(self->session_);
  4834. self->session_ = session;
  4835. return 1; // Keeps the reference
  4836. });
  4837. }
  4838. ~ResumingClient() {
  4839. SSL_SESSION_free(session_);
  4840. SSL_CTX_free(ctx_);
  4841. }
  4842. // Tells whether the request was answered.
  4843. bool get() {
  4844. auto error = Error::Success;
  4845. auto sock = detail::create_client_socket(
  4846. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4847. /*connection_timeout_sec=*/5, 0,
  4848. /*read_timeout_sec=*/5, 0,
  4849. /*write_timeout_sec=*/5, 0, std::string(), error);
  4850. if (sock == INVALID_SOCKET) { return false; }
  4851. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4852. auto ssl = SSL_new(ctx_);
  4853. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4854. SSL_set_fd(ssl, static_cast<int>(sock));
  4855. if (session_) { SSL_set_session(ssl, session_); }
  4856. if (SSL_connect(ssl) != 1) { return false; }
  4857. reused_ = SSL_session_reused(ssl) == 1;
  4858. // Reading the response also takes in a TLS 1.3 session ticket.
  4859. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4860. "Connection: close\r\n\r\n";
  4861. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4862. std::string res;
  4863. char buf[256];
  4864. int n;
  4865. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4866. res.append(buf, static_cast<size_t>(n));
  4867. }
  4868. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4869. SSL_shutdown(ssl);
  4870. return res.find("200 OK") != std::string::npos;
  4871. }
  4872. // Whether the last connection resumed a session
  4873. bool reused() const { return reused_; }
  4874. private:
  4875. SSL_CTX *ctx_;
  4876. SSL_SESSION *session_ = nullptr;
  4877. bool reused_ = false;
  4878. };
  4879. // A client that resumes its session gets through, but not once the client CA
  4880. // has changed, as a resumed session does not show the certificate again.
  4881. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4882. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4883. ASSERT_TRUE(svr.is_valid());
  4884. svr.Get("/test", [](const Request &, Response &res) {
  4885. res.set_content("ok", "text/plain");
  4886. });
  4887. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4888. auto se = detail::scope_exit([&] {
  4889. svr.stop();
  4890. t.join();
  4891. ASSERT_FALSE(svr.is_running());
  4892. });
  4893. svr.wait_until_ready();
  4894. ResumingClient cli;
  4895. ASSERT_TRUE(cli.get());
  4896. ASSERT_TRUE(cli.get());
  4897. EXPECT_TRUE(cli.reused());
  4898. ASSERT_TRUE(replace_client_ca(svr));
  4899. EXPECT_FALSE(cli.get());
  4900. }
  4901. // A resumed session does not show the certificate again, so the server does
  4902. // not resume one with a verify callback to run on it.
  4903. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4904. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4905. ASSERT_TRUE(svr.is_valid());
  4906. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4907. return v.preverify_ok;
  4908. });
  4909. svr.Get("/test", [](const Request &, Response &res) {
  4910. res.set_content("ok", "text/plain");
  4911. });
  4912. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4913. auto se = detail::scope_exit([&] {
  4914. svr.stop();
  4915. t.join();
  4916. ASSERT_FALSE(svr.is_running());
  4917. });
  4918. svr.wait_until_ready();
  4919. ResumingClient cli;
  4920. ASSERT_TRUE(cli.get());
  4921. ASSERT_TRUE(cli.get());
  4922. EXPECT_FALSE(cli.reused());
  4923. }
  4924. #endif
  4925. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4926. // wolfSSL shares its session cache between contexts, so a resumed session
  4927. // could carry a client certificate checked against another server's CA, or
  4928. // against a client CA since replaced.
  4929. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4931. ASSERT_TRUE(svr.is_valid());
  4932. // Trusts a CA that did not sign the client's certificate.
  4933. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4934. ASSERT_TRUE(other.is_valid());
  4935. for (auto s : {&svr, &other}) {
  4936. s->Get("/test", [](const Request &, Response &res) {
  4937. res.set_content("ok", "text/plain");
  4938. });
  4939. }
  4940. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4941. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4942. auto se = detail::scope_exit([&] {
  4943. other.stop();
  4944. svr.stop();
  4945. t2.join();
  4946. t.join();
  4947. });
  4948. svr.wait_until_ready();
  4949. other.wait_until_ready();
  4950. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4951. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4952. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4953. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4954. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4955. ASSERT_EQ(WOLFSSL_SUCCESS,
  4956. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4957. WOLFSSL_FILETYPE_PEM));
  4958. WOLFSSL_SESSION *session = nullptr;
  4959. auto session_se = detail::scope_exit([&] {
  4960. if (session) { wolfSSL_SESSION_free(session); }
  4961. });
  4962. // A request over a new connection, resuming `session` when there is one and
  4963. // keeping the connection's own in its place. Tells whether it was answered.
  4964. auto get = [&](int port) {
  4965. auto error = Error::Success;
  4966. auto sock = detail::create_client_socket(
  4967. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4968. /*connection_timeout_sec=*/5, 0,
  4969. /*read_timeout_sec=*/5, 0,
  4970. /*write_timeout_sec=*/5, 0, std::string(), error);
  4971. if (sock == INVALID_SOCKET) { return false; }
  4972. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4973. auto ssl = wolfSSL_new(ctx);
  4974. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4975. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4976. if (session) { wolfSSL_set_session(ssl, session); }
  4977. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4978. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4979. "Connection: close\r\n\r\n";
  4980. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4981. std::string res;
  4982. char buf[256];
  4983. int n;
  4984. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4985. res.append(buf, static_cast<size_t>(n));
  4986. }
  4987. wolfSSL_shutdown(ssl);
  4988. if (session) { wolfSSL_SESSION_free(session); }
  4989. session = wolfSSL_get1_session(ssl);
  4990. return res.find("200 OK") != std::string::npos;
  4991. };
  4992. ASSERT_TRUE(get(PORT));
  4993. EXPECT_FALSE(get(PORT + 1));
  4994. ASSERT_TRUE(get(PORT));
  4995. ASSERT_TRUE(replace_client_ca(svr));
  4996. EXPECT_FALSE(get(PORT));
  4997. }
  4998. #endif
  4999. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  5000. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5001. ASSERT_TRUE(svr.is_valid());
  5002. // Keep-alive parking would wait for the ClientHello without a handshake.
  5003. svr.set_keep_alive_parking(false);
  5004. svr.Get("/test", [](const Request &, Response &res) {
  5005. res.set_content("ok", "text/plain");
  5006. });
  5007. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5008. auto se = detail::scope_exit([&] {
  5009. svr.stop();
  5010. t.join();
  5011. ASSERT_FALSE(svr.is_running());
  5012. });
  5013. svr.wait_until_ready();
  5014. // A connection that sends no ClientHello keeps its handshake in progress,
  5015. // once the server has had a moment to start it.
  5016. auto error = Error::Success;
  5017. auto sock = detail::create_client_socket(
  5018. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5019. /*connection_timeout_sec=*/5, 0,
  5020. /*read_timeout_sec=*/5, 0,
  5021. /*write_timeout_sec=*/5, 0, std::string(), error);
  5022. ASSERT_NE(INVALID_SOCKET, sock);
  5023. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5024. std::string cert_pem, key_pem;
  5025. read_file(SERVER_CERT_FILE, cert_pem);
  5026. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5027. auto update = std::async(std::launch::async, [&]() {
  5028. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5029. });
  5030. EXPECT_EQ(std::future_status::timeout,
  5031. update.wait_for(std::chrono::milliseconds(200)));
  5032. detail::close_socket(sock);
  5033. EXPECT_TRUE(update.get());
  5034. SSLClient cli(HOST, PORT);
  5035. cli.enable_server_certificate_verification(false);
  5036. auto res = cli.Get("/test");
  5037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5038. EXPECT_EQ(StatusCode::OK_200, res->status);
  5039. }
  5040. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5041. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5042. ASSERT_TRUE(svr.is_valid());
  5043. // Keep-alive parking would wait for the ClientHello without a handshake.
  5044. svr.set_keep_alive_parking(false);
  5045. svr.set_read_timeout(10, 0);
  5046. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5047. auto se = detail::scope_exit([&] {
  5048. svr.stop();
  5049. if (t.joinable()) { t.join(); }
  5050. });
  5051. svr.wait_until_ready();
  5052. // A connection that sends no ClientHello keeps its handshake in progress,
  5053. // once the server has had a moment to start it.
  5054. auto error = Error::Success;
  5055. auto sock = detail::create_client_socket(
  5056. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5057. /*connection_timeout_sec=*/5, 0,
  5058. /*read_timeout_sec=*/5, 0,
  5059. /*write_timeout_sec=*/5, 0, std::string(), error);
  5060. ASSERT_NE(INVALID_SOCKET, sock);
  5061. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5062. auto start = std::chrono::steady_clock::now();
  5063. svr.stop();
  5064. t.join();
  5065. auto elapsed = std::chrono::steady_clock::now() - start;
  5066. detail::close_socket(sock);
  5067. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5068. }
  5069. #endif
  5070. TEST(ErrorHandlerTest, ContentLength) {
  5071. Server svr;
  5072. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5073. res.status = StatusCode::OK_200;
  5074. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5075. "text/html"); // <= Content-Length still 13
  5076. });
  5077. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5078. res.set_content("Hello World!\n", "text/plain");
  5079. res.status = 524;
  5080. });
  5081. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5082. auto se = detail::scope_exit([&] {
  5083. svr.stop();
  5084. thread.join();
  5085. ASSERT_FALSE(svr.is_running());
  5086. });
  5087. svr.wait_until_ready();
  5088. {
  5089. Client cli(HOST, PORT);
  5090. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5092. EXPECT_EQ(StatusCode::OK_200, res->status);
  5093. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5094. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5095. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5096. }
  5097. }
  5098. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5099. TEST(ExceptionTest, WithoutExceptionHandler) {
  5100. Server svr;
  5101. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5102. throw std::runtime_error("exception...");
  5103. });
  5104. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5105. throw std::runtime_error("exception\r\n...");
  5106. });
  5107. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5108. auto se = detail::scope_exit([&] {
  5109. svr.stop();
  5110. listen_thread.join();
  5111. ASSERT_FALSE(svr.is_running());
  5112. });
  5113. svr.wait_until_ready();
  5114. Client cli("localhost", PORT);
  5115. {
  5116. auto res = cli.Get("/exception");
  5117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5118. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5119. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5120. }
  5121. {
  5122. auto res = cli.Get("/unknown");
  5123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5124. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5125. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5126. }
  5127. }
  5128. TEST(ExceptionTest, WithExceptionHandler) {
  5129. Server svr;
  5130. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5131. std::exception_ptr ep) {
  5132. EXPECT_FALSE(ep == nullptr);
  5133. try {
  5134. std::rethrow_exception(ep);
  5135. } catch (std::exception &e) {
  5136. EXPECT_EQ("abc", std::string(e.what()));
  5137. } catch (...) {}
  5138. res.status = StatusCode::InternalServerError_500;
  5139. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5140. "text/html"); // <= Content-Length still 13 at this point
  5141. });
  5142. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5143. res.set_content("Hello World!\n", "text/plain");
  5144. throw std::runtime_error("abc");
  5145. });
  5146. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5147. auto se = detail::scope_exit([&] {
  5148. svr.stop();
  5149. thread.join();
  5150. ASSERT_FALSE(svr.is_running());
  5151. });
  5152. svr.wait_until_ready();
  5153. for (size_t i = 0; i < 10; i++) {
  5154. Client cli(HOST, PORT);
  5155. for (size_t j = 0; j < 100; j++) {
  5156. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5158. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5159. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5160. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5161. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5162. }
  5163. cli.set_keep_alive(true);
  5164. for (size_t j = 0; j < 100; j++) {
  5165. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5167. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5168. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5169. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5170. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5171. }
  5172. }
  5173. }
  5174. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5175. Server svr;
  5176. svr.set_exception_handler(
  5177. [](const Request &, Response &res, std::exception_ptr) {
  5178. res.set_content("oops", "text/plain");
  5179. });
  5180. svr.Get("/throw", [](const Request &, Response &) {
  5181. throw std::runtime_error("throw");
  5182. });
  5183. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5184. res.status = StatusCode::Created_201;
  5185. throw std::runtime_error("created-then-throw");
  5186. });
  5187. auto port = svr.bind_to_any_port(HOST);
  5188. ASSERT_GT(port, 0);
  5189. thread t = thread([&] { svr.listen_after_bind(); });
  5190. auto se = detail::scope_exit([&] {
  5191. svr.stop();
  5192. t.join();
  5193. ASSERT_FALSE(svr.is_running());
  5194. });
  5195. svr.wait_until_ready();
  5196. Client cli(HOST, port);
  5197. for (auto path : {"/throw", "/created-then-throw"}) {
  5198. auto res = cli.Get(path);
  5199. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5200. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5201. }
  5202. }
  5203. TEST(ExceptionTest, AndErrorHandler) {
  5204. Server svr;
  5205. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5206. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5207. });
  5208. svr.set_exception_handler(
  5209. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5210. EXPECT_FALSE(ep == nullptr);
  5211. try {
  5212. std::rethrow_exception(ep);
  5213. } catch (std::exception &e) {
  5214. res.set_content(e.what(), "text/html");
  5215. } catch (...) {}
  5216. res.status = StatusCode::InternalServerError_500;
  5217. });
  5218. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5219. throw std::runtime_error("EXCEPTION");
  5220. });
  5221. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5222. res.set_content("ERROR", "text/html");
  5223. res.status = StatusCode::InternalServerError_500;
  5224. });
  5225. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5226. auto se = detail::scope_exit([&] {
  5227. svr.stop();
  5228. thread.join();
  5229. ASSERT_FALSE(svr.is_running());
  5230. });
  5231. svr.wait_until_ready();
  5232. Client cli(HOST, PORT);
  5233. {
  5234. auto res = cli.Get("/exception");
  5235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5236. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5237. EXPECT_EQ("EXCEPTION", res->body);
  5238. }
  5239. {
  5240. auto res = cli.Get("/error");
  5241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5242. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5243. EXPECT_EQ("ERROR", res->body);
  5244. }
  5245. {
  5246. auto res = cli.Get("/invalid");
  5247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5248. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5249. EXPECT_EQ("NOT_FOUND", res->body);
  5250. }
  5251. }
  5252. #endif
  5253. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5254. // An exception from a user callback outside process_request()'s try/catch
  5255. // used to unwind into the task queue - which does not catch - and terminate
  5256. // the process. Each test below runs the server on a single worker thread: a
  5257. // guard that catches the exception but still loses the thread would otherwise
  5258. // be hidden by a spare worker serving the follow-up request. Note that a
  5259. // regression here aborts the whole test binary rather than failing one test.
  5260. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5261. Server svr;
  5262. svr.new_task_queue = [] { return new ThreadPool(1); };
  5263. std::atomic<int> reported{0};
  5264. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5265. if (err == Error::UserCallbackException) { reported++; }
  5266. });
  5267. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5268. res.set_content_provider(
  5269. 1024, "text/plain",
  5270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5271. sink.write("hello", 5);
  5272. throw std::runtime_error("from the content provider");
  5273. });
  5274. });
  5275. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5276. res.set_content("ok", "text/plain");
  5277. });
  5278. auto port = svr.bind_to_any_port(HOST);
  5279. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5280. auto se = detail::scope_exit([&] {
  5281. svr.stop();
  5282. listen_thread.join();
  5283. ASSERT_FALSE(svr.is_running());
  5284. });
  5285. svr.wait_until_ready();
  5286. {
  5287. Client cli(HOST, port);
  5288. cli.set_read_timeout(5, 0);
  5289. EXPECT_FALSE(cli.Get("/throw"));
  5290. }
  5291. EXPECT_TRUE(svr.is_running());
  5292. EXPECT_EQ(1, reported.load());
  5293. // A request on a fresh connection is still served.
  5294. {
  5295. Client cli(HOST, port);
  5296. auto res = cli.Get("/ok");
  5297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5298. EXPECT_EQ(StatusCode::OK_200, res->status);
  5299. EXPECT_EQ("ok", res->body);
  5300. }
  5301. }
  5302. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5303. Server svr;
  5304. svr.new_task_queue = [] { return new ThreadPool(1); };
  5305. std::atomic<bool> should_throw{true};
  5306. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5307. res.set_content("hi", "text/plain");
  5308. });
  5309. svr.set_post_routing_handler(
  5310. [&](const Request & /*req*/, Response & /*res*/) {
  5311. if (should_throw) {
  5312. throw std::runtime_error("from the post-routing handler");
  5313. }
  5314. });
  5315. auto port = svr.bind_to_any_port(HOST);
  5316. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5317. auto se = detail::scope_exit([&] {
  5318. svr.stop();
  5319. listen_thread.join();
  5320. ASSERT_FALSE(svr.is_running());
  5321. });
  5322. svr.wait_until_ready();
  5323. {
  5324. Client cli(HOST, port);
  5325. cli.set_read_timeout(5, 0);
  5326. EXPECT_FALSE(cli.Get("/hi"));
  5327. }
  5328. EXPECT_TRUE(svr.is_running());
  5329. should_throw = false;
  5330. {
  5331. Client cli(HOST, port);
  5332. auto res = cli.Get("/hi");
  5333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5334. EXPECT_EQ(StatusCode::OK_200, res->status);
  5335. EXPECT_EQ("hi", res->body);
  5336. }
  5337. }
  5338. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5339. // The guard reports the caught exception through the error logger, which is
  5340. // a user callback too. A logger that throws has to be contained as well, or
  5341. // the process would terminate from inside the catch.
  5342. Server svr;
  5343. svr.new_task_queue = [] { return new ThreadPool(1); };
  5344. std::atomic<int> reported{0};
  5345. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5346. if (err == Error::UserCallbackException) {
  5347. reported++;
  5348. throw std::runtime_error("from the error logger");
  5349. }
  5350. });
  5351. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5352. res.set_content_provider(
  5353. 1024, "text/plain",
  5354. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5355. sink.write("hello", 5);
  5356. throw std::runtime_error("from the content provider");
  5357. });
  5358. });
  5359. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5360. res.set_content("ok", "text/plain");
  5361. });
  5362. auto port = svr.bind_to_any_port(HOST);
  5363. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5364. auto se = detail::scope_exit([&] {
  5365. svr.stop();
  5366. listen_thread.join();
  5367. ASSERT_FALSE(svr.is_running());
  5368. });
  5369. svr.wait_until_ready();
  5370. {
  5371. Client cli(HOST, port);
  5372. cli.set_read_timeout(5, 0);
  5373. EXPECT_FALSE(cli.Get("/throw"));
  5374. }
  5375. EXPECT_TRUE(svr.is_running());
  5376. EXPECT_EQ(1, reported.load());
  5377. {
  5378. Client cli(HOST, port);
  5379. auto res = cli.Get("/ok");
  5380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5381. EXPECT_EQ(StatusCode::OK_200, res->status);
  5382. EXPECT_EQ("ok", res->body);
  5383. }
  5384. }
  5385. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5386. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5387. // so the exception unwinds through the ws::WebSocket object on its way to
  5388. // the guard. None of the HTTP cases above cross that.
  5389. Server svr;
  5390. svr.new_task_queue = [] { return new ThreadPool(1); };
  5391. std::atomic<int> reported{0};
  5392. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5393. if (err == Error::UserCallbackException) { reported++; }
  5394. });
  5395. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5396. throw std::runtime_error("from the WebSocket handler");
  5397. });
  5398. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5399. res.set_content("ok", "text/plain");
  5400. });
  5401. auto port = svr.bind_to_any_port(HOST);
  5402. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5403. auto se = detail::scope_exit([&] {
  5404. svr.stop();
  5405. listen_thread.join();
  5406. ASSERT_FALSE(svr.is_running());
  5407. });
  5408. svr.wait_until_ready();
  5409. {
  5410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5411. "/ws");
  5412. auto res = client.connect();
  5413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5414. // The server dropped the connection instead of dying.
  5415. std::string msg;
  5416. EXPECT_FALSE(client.read(msg));
  5417. client.close();
  5418. }
  5419. EXPECT_TRUE(svr.is_running());
  5420. EXPECT_EQ(1, reported.load());
  5421. {
  5422. Client cli(HOST, port);
  5423. auto res = cli.Get("/ok");
  5424. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5425. EXPECT_EQ(StatusCode::OK_200, res->status);
  5426. EXPECT_EQ("ok", res->body);
  5427. }
  5428. }
  5429. #ifdef CPPHTTPLIB_SSL_ENABLED
  5430. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5431. // SSLServer::process_and_close_socket() is a separate overload with its own
  5432. // guard, so it is exercised on its own.
  5433. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5434. ASSERT_TRUE(svr.is_valid());
  5435. svr.new_task_queue = [] { return new ThreadPool(1); };
  5436. std::atomic<int> reported{0};
  5437. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5438. if (err == Error::UserCallbackException) { reported++; }
  5439. });
  5440. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5441. res.set_content_provider(
  5442. 1024, "text/plain",
  5443. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5444. sink.write("hello", 5);
  5445. throw std::runtime_error("from the content provider");
  5446. });
  5447. });
  5448. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5449. res.set_content("ok", "text/plain");
  5450. });
  5451. auto port = svr.bind_to_any_port(HOST);
  5452. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5453. auto se = detail::scope_exit([&] {
  5454. svr.stop();
  5455. listen_thread.join();
  5456. ASSERT_FALSE(svr.is_running());
  5457. });
  5458. svr.wait_until_ready();
  5459. {
  5460. SSLClient cli(HOST, port);
  5461. cli.enable_server_certificate_verification(false);
  5462. cli.set_read_timeout(5, 0);
  5463. EXPECT_FALSE(cli.Get("/throw"));
  5464. }
  5465. EXPECT_TRUE(svr.is_running());
  5466. EXPECT_EQ(1, reported.load());
  5467. {
  5468. SSLClient cli(HOST, port);
  5469. cli.enable_server_certificate_verification(false);
  5470. auto res = cli.Get("/ok");
  5471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5472. EXPECT_EQ(StatusCode::OK_200, res->status);
  5473. EXPECT_EQ("ok", res->body);
  5474. }
  5475. }
  5476. #endif
  5477. #endif
  5478. TEST(NoContentTest, ContentLength) {
  5479. Server svr;
  5480. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5481. res.status = StatusCode::NoContent_204;
  5482. });
  5483. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5484. auto se = detail::scope_exit([&] {
  5485. svr.stop();
  5486. thread.join();
  5487. ASSERT_FALSE(svr.is_running());
  5488. });
  5489. svr.wait_until_ready();
  5490. {
  5491. Client cli(HOST, PORT);
  5492. auto res = cli.Get("/hi");
  5493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5494. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5495. // RFC 9110 8.6: none in a 204 response
  5496. EXPECT_FALSE(res->has_header("Content-Length"));
  5497. }
  5498. }
  5499. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5500. Server svr;
  5501. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5502. res.set_header("Content-Length", "5");
  5503. res.set_content("hello world", "text/plain");
  5504. });
  5505. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5506. // A body that reads as the last chunk, were it taken as chunked
  5507. res.set_header("Transfer-Encoding", "chunked");
  5508. res.set_content("0\r\n\r\n", "text/plain");
  5509. });
  5510. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5511. res.set_header("Content-Length", "2");
  5512. res.set_content_provider(5, "text/plain",
  5513. [](size_t offset, size_t length, DataSink &sink) {
  5514. sink.write(&"hello"[offset], length);
  5515. return true;
  5516. });
  5517. });
  5518. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5519. res.set_header("Content-Length", "1234");
  5520. });
  5521. thread t = thread([&] { svr.listen(HOST, PORT); });
  5522. auto se = detail::scope_exit([&] {
  5523. svr.stop();
  5524. t.join();
  5525. ASSERT_FALSE(svr.is_running());
  5526. });
  5527. svr.wait_until_ready();
  5528. Client cli(HOST, PORT);
  5529. cli.set_read_timeout(1, 0);
  5530. auto expect_body = [&](const Result &res, const std::string &body) {
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(body, res->body);
  5533. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5534. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5535. };
  5536. Headers identity{{"Accept-Encoding", ""}};
  5537. expect_body(cli.Get("/body", identity), "hello world");
  5538. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5539. expect_body(cli.Get("/body",
  5540. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5541. "he");
  5542. expect_body(cli.Get("/provider", identity), "hello");
  5543. expect_body(cli.Get("/empty", identity), "");
  5544. // A HEAD response may give the length of the body a GET would get.
  5545. auto res = cli.Head("/empty");
  5546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5547. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5548. }
  5549. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5550. Server svr;
  5551. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5552. res.set_content("short", "text/plain");
  5553. });
  5554. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5555. res.body += " with a footer";
  5556. res.set_header("Transfer-Encoding", "chunked");
  5557. });
  5558. thread t = thread([&] { svr.listen(HOST, PORT); });
  5559. auto se = detail::scope_exit([&] {
  5560. svr.stop();
  5561. t.join();
  5562. ASSERT_FALSE(svr.is_running());
  5563. });
  5564. svr.wait_until_ready();
  5565. Client cli(HOST, PORT);
  5566. cli.set_read_timeout(1, 0);
  5567. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5569. EXPECT_EQ("short with a footer", res->body);
  5570. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5571. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5572. }
  5573. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5574. Server svr;
  5575. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5576. res.set_header("Content-Length", "3");
  5577. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5578. sink.write("abc", 3);
  5579. sink.done();
  5580. return true;
  5581. });
  5582. });
  5583. thread t = thread([&] { svr.listen(HOST, PORT); });
  5584. auto se = detail::scope_exit([&] {
  5585. svr.stop();
  5586. t.join();
  5587. ASSERT_FALSE(svr.is_running());
  5588. });
  5589. svr.wait_until_ready();
  5590. Client cli(HOST, PORT);
  5591. cli.set_keep_alive(true);
  5592. auto res = cli.Get("/");
  5593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5594. EXPECT_EQ("abc", res->body);
  5595. EXPECT_FALSE(res->has_header("Content-Length"));
  5596. EXPECT_EQ("close", res->get_header_value("Connection"));
  5597. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5598. // No body to delimit
  5599. auto head = cli.Head("/");
  5600. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5601. EXPECT_FALSE(head->has_header("Connection"));
  5602. }
  5603. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5604. #ifdef CPPHTTPLIB_SSL_ENABLED
  5605. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5606. ASSERT_TRUE(svr.is_valid());
  5607. #else
  5608. Server svr;
  5609. #endif
  5610. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5611. if (req.path == "/routing_handler") {
  5612. res.set_header("PRE_ROUTING", "on");
  5613. res.set_content("Routing Handler", "text/plain");
  5614. return httplib::Server::HandlerResponse::Handled;
  5615. }
  5616. return httplib::Server::HandlerResponse::Unhandled;
  5617. });
  5618. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5619. res.set_content("Error", "text/html");
  5620. });
  5621. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5622. if (req.path == "/routing_handler") {
  5623. res.set_header("POST_ROUTING", "on");
  5624. }
  5625. });
  5626. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5627. res.set_content("Hello World!\n", "text/plain");
  5628. });
  5629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5630. auto se = detail::scope_exit([&] {
  5631. svr.stop();
  5632. thread.join();
  5633. ASSERT_FALSE(svr.is_running());
  5634. });
  5635. svr.wait_until_ready();
  5636. {
  5637. #ifdef CPPHTTPLIB_SSL_ENABLED
  5638. SSLClient cli(HOST, PORT);
  5639. cli.enable_server_certificate_verification(false);
  5640. #else
  5641. Client cli(HOST, PORT);
  5642. #endif
  5643. auto res = cli.Get("/routing_handler");
  5644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5645. EXPECT_EQ(StatusCode::OK_200, res->status);
  5646. EXPECT_EQ("Routing Handler", res->body);
  5647. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5648. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5649. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5650. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5651. }
  5652. {
  5653. #ifdef CPPHTTPLIB_SSL_ENABLED
  5654. SSLClient cli(HOST, PORT);
  5655. cli.enable_server_certificate_verification(false);
  5656. #else
  5657. Client cli(HOST, PORT);
  5658. #endif
  5659. auto res = cli.Get("/hi");
  5660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5661. EXPECT_EQ(StatusCode::OK_200, res->status);
  5662. EXPECT_EQ("Hello World!\n", res->body);
  5663. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5664. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5665. }
  5666. {
  5667. #ifdef CPPHTTPLIB_SSL_ENABLED
  5668. SSLClient cli(HOST, PORT);
  5669. cli.enable_server_certificate_verification(false);
  5670. #else
  5671. Client cli(HOST, PORT);
  5672. #endif
  5673. auto res = cli.Get("/aaa");
  5674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5675. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5676. EXPECT_EQ("Error", res->body);
  5677. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5678. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5679. }
  5680. }
  5681. TEST(RequestHandlerTest, PreRequestHandler) {
  5682. auto route_path = "/user/:user";
  5683. Server svr;
  5684. svr.Get("/hi", [](const Request &, Response &res) {
  5685. res.set_content("hi", "text/plain");
  5686. });
  5687. svr.Get(route_path, [](const Request &req, Response &res) {
  5688. res.set_content(req.path_params.at("user"), "text/plain");
  5689. });
  5690. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5691. if (req.matched_route == route_path) {
  5692. auto user = req.path_params.at("user");
  5693. if (user != "john") {
  5694. res.status = StatusCode::Forbidden_403;
  5695. res.set_content("error", "text/html");
  5696. return Server::HandlerResponse::Handled;
  5697. }
  5698. }
  5699. return Server::HandlerResponse::Unhandled;
  5700. });
  5701. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5702. auto se = detail::scope_exit([&] {
  5703. svr.stop();
  5704. thread.join();
  5705. ASSERT_FALSE(svr.is_running());
  5706. });
  5707. svr.wait_until_ready();
  5708. Client cli(HOST, PORT);
  5709. {
  5710. auto res = cli.Get("/hi");
  5711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5712. EXPECT_EQ(StatusCode::OK_200, res->status);
  5713. EXPECT_EQ("hi", res->body);
  5714. }
  5715. {
  5716. auto res = cli.Get("/user/john");
  5717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5718. EXPECT_EQ(StatusCode::OK_200, res->status);
  5719. EXPECT_EQ("john", res->body);
  5720. }
  5721. {
  5722. auto res = cli.Get("/user/invalid-user");
  5723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5724. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5725. EXPECT_EQ("error", res->body);
  5726. }
  5727. }
  5728. // The pre-request handler must run before the request body is read, so a
  5729. // rejected request never forces the server to buffer a (potentially large)
  5730. // body. Here the posted body is larger than the payload limit: if the body
  5731. // were read first the server would answer 413, but because the pre-request
  5732. // handler runs first it answers 403 and the body is never read.
  5733. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5734. Server svr;
  5735. svr.set_payload_max_length(8);
  5736. auto handler_ran = false;
  5737. svr.Post("/reject", [&](const Request &req, Response &res) {
  5738. handler_ran = true;
  5739. res.set_content(req.body, "text/plain");
  5740. });
  5741. svr.Post("/accept", [](const Request &req, Response &res) {
  5742. res.set_content(req.body, "text/plain");
  5743. });
  5744. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5745. if (req.matched_route == "/reject") {
  5746. res.status = StatusCode::Forbidden_403;
  5747. res.set_content("denied", "text/plain");
  5748. return Server::HandlerResponse::Handled;
  5749. }
  5750. return Server::HandlerResponse::Unhandled;
  5751. });
  5752. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5753. auto se = detail::scope_exit([&] {
  5754. svr.stop();
  5755. thread.join();
  5756. ASSERT_FALSE(svr.is_running());
  5757. });
  5758. svr.wait_until_ready();
  5759. Client cli(HOST, PORT);
  5760. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5761. // rejects with 403 before the body is read, so 413 is never reached.
  5762. {
  5763. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5765. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5766. EXPECT_EQ("denied", res->body);
  5767. EXPECT_FALSE(handler_ran);
  5768. }
  5769. // An approved route still reads the body and enforces the payload limit.
  5770. {
  5771. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5773. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5774. }
  5775. }
  5776. TEST(UserDataTest, BasicOperations) {
  5777. httplib::UserData ud;
  5778. // Initially empty
  5779. EXPECT_FALSE(ud.has("key"));
  5780. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5781. // set and get
  5782. ud.set("key", 42);
  5783. EXPECT_TRUE(ud.has("key"));
  5784. auto *p = ud.get<int>("key");
  5785. ASSERT_NE(nullptr, p);
  5786. EXPECT_EQ(42, *p);
  5787. // Type mismatch → nullptr
  5788. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5789. // Overwrite with different type
  5790. ud.set("key", std::string("hello"));
  5791. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5792. auto *s = ud.get<std::string>("key");
  5793. ASSERT_NE(nullptr, s);
  5794. EXPECT_EQ("hello", *s);
  5795. // erase
  5796. ud.erase("key");
  5797. EXPECT_FALSE(ud.has("key"));
  5798. // clear
  5799. ud.set("a", 1);
  5800. ud.set("b", 2);
  5801. ud.clear();
  5802. EXPECT_FALSE(ud.has("a"));
  5803. EXPECT_FALSE(ud.has("b"));
  5804. }
  5805. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5806. struct AuthCtx {
  5807. std::string user_id;
  5808. };
  5809. Server svr;
  5810. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5811. res.user_data.set("auth", AuthCtx{"alice"});
  5812. return Server::HandlerResponse::Unhandled;
  5813. });
  5814. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5815. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5816. ASSERT_NE(nullptr, ctx);
  5817. res.set_content("Hello " + ctx->user_id, "text/plain");
  5818. });
  5819. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5820. auto se = detail::scope_exit([&] {
  5821. svr.stop();
  5822. thread.join();
  5823. ASSERT_FALSE(svr.is_running());
  5824. });
  5825. svr.wait_until_ready();
  5826. Client cli(HOST, PORT);
  5827. auto res = cli.Get("/me");
  5828. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5829. EXPECT_EQ(StatusCode::OK_200, res->status);
  5830. EXPECT_EQ("Hello alice", res->body);
  5831. }
  5832. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5833. struct RoleCtx {
  5834. std::string role;
  5835. };
  5836. Server svr;
  5837. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5838. res.user_data.set("role", RoleCtx{"admin"});
  5839. return Server::HandlerResponse::Unhandled;
  5840. });
  5841. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5842. auto *ctx = res.user_data.get<RoleCtx>("role");
  5843. ASSERT_NE(nullptr, ctx);
  5844. res.set_content(ctx->role, "text/plain");
  5845. });
  5846. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5847. auto se = detail::scope_exit([&] {
  5848. svr.stop();
  5849. thread.join();
  5850. ASSERT_FALSE(svr.is_running());
  5851. });
  5852. svr.wait_until_ready();
  5853. Client cli(HOST, PORT);
  5854. auto res = cli.Get("/role");
  5855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5856. EXPECT_EQ(StatusCode::OK_200, res->status);
  5857. EXPECT_EQ("admin", res->body);
  5858. }
  5859. TEST(InvalidFormatTest, StatusCode) {
  5860. Server svr;
  5861. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5862. res.set_content("Hello World!\n", "text/plain");
  5863. res.status = 9999; // Status should be a three-digit code...
  5864. });
  5865. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5866. auto se = detail::scope_exit([&] {
  5867. svr.stop();
  5868. thread.join();
  5869. ASSERT_FALSE(svr.is_running());
  5870. });
  5871. svr.wait_until_ready();
  5872. {
  5873. Client cli(HOST, PORT);
  5874. auto res = cli.Get("/hi");
  5875. ASSERT_FALSE(res);
  5876. }
  5877. }
  5878. TEST(URLFragmentTest, WithFragment) {
  5879. Server svr;
  5880. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5881. EXPECT_TRUE(req.target == "/hi");
  5882. });
  5883. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5884. auto se = detail::scope_exit([&] {
  5885. svr.stop();
  5886. thread.join();
  5887. ASSERT_FALSE(svr.is_running());
  5888. });
  5889. svr.wait_until_ready();
  5890. {
  5891. Client cli(HOST, PORT);
  5892. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5893. EXPECT_TRUE(res);
  5894. EXPECT_EQ(StatusCode::OK_200, res->status);
  5895. res = cli.Get("/hi%23key1=val1=key2=val2");
  5896. EXPECT_TRUE(res);
  5897. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5898. }
  5899. }
  5900. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5901. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5902. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5903. Server svr;
  5904. std::vector<std::string> targets;
  5905. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5906. targets.push_back(req.target);
  5907. });
  5908. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5909. auto se = detail::scope_exit([&] {
  5910. svr.stop();
  5911. thread.join();
  5912. ASSERT_FALSE(svr.is_running());
  5913. });
  5914. svr.wait_until_ready();
  5915. Client cli(HOST, PORT);
  5916. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5917. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5918. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5919. // A '?' after the '#' belongs to the fragment, not to the query.
  5920. Request req;
  5921. req.method = "GET";
  5922. req.path = "/hi#f?x=1";
  5923. req.params.emplace("a", "1");
  5924. Response res;
  5925. auto error = Error::Success;
  5926. EXPECT_TRUE(cli.send(req, res, error));
  5927. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5928. "/hi?a=1"}),
  5929. targets);
  5930. }
  5931. TEST(HeaderWriter, SetHeaderWriter) {
  5932. Server svr;
  5933. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5934. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5935. return detail::write_headers(strm, hdrs);
  5936. });
  5937. svr.Get("/hi", [](const Request &req, Response &res) {
  5938. auto it = req.headers.find("CustomClientHeader");
  5939. EXPECT_TRUE(it != req.headers.end());
  5940. EXPECT_EQ(it->second, "CustomClientValue");
  5941. res.set_content("Hello World!\n", "text/plain");
  5942. });
  5943. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5944. auto se = detail::scope_exit([&] {
  5945. svr.stop();
  5946. thread.join();
  5947. ASSERT_FALSE(svr.is_running());
  5948. });
  5949. svr.wait_until_ready();
  5950. {
  5951. Client cli(HOST, PORT);
  5952. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5953. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5954. return detail::write_headers(strm, hdrs);
  5955. });
  5956. auto res = cli.Get("/hi");
  5957. EXPECT_TRUE(res);
  5958. EXPECT_EQ(StatusCode::OK_200, res->status);
  5959. auto it = res->headers.find("CustomServerHeader");
  5960. EXPECT_TRUE(it != res->headers.end());
  5961. EXPECT_EQ(it->second, "CustomServerValue");
  5962. }
  5963. }
  5964. class ServerTest : public ::testing::Test {
  5965. protected:
  5966. ServerTest()
  5967. : cli_(HOST, PORT)
  5968. #ifdef CPPHTTPLIB_SSL_ENABLED
  5969. ,
  5970. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5971. #endif
  5972. {
  5973. #ifdef CPPHTTPLIB_SSL_ENABLED
  5974. cli_.enable_server_certificate_verification(false);
  5975. #endif
  5976. // Allow LARGE_DATA (100MB) responses
  5977. cli_.set_payload_max_length(200 * 1024 * 1024);
  5978. }
  5979. virtual void SetUp() {
  5980. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5981. svr_.set_payload_max_length(200 * 1024 * 1024);
  5982. svr_.set_mount_point("/", "./www");
  5983. svr_.set_mount_point("/mount", "./www2");
  5984. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5985. svr_.Get("/hi",
  5986. [&](const Request & /*req*/, Response &res) {
  5987. res.set_content("Hello World!", "text/plain");
  5988. })
  5989. .Get("/file_content",
  5990. [&](const Request & /*req*/, Response &res) {
  5991. res.set_file_content("./www/dir/test.html");
  5992. })
  5993. .Get("/file_content_with_content_type",
  5994. [&](const Request & /*req*/, Response &res) {
  5995. res.set_file_content("./www/file", "text/plain");
  5996. })
  5997. .Get("/invalid_file_content",
  5998. [&](const Request & /*req*/, Response &res) {
  5999. res.set_file_content("./www/dir/invalid_file_path");
  6000. })
  6001. .Get("/http_response_splitting",
  6002. [&](const Request & /*req*/, Response &res) {
  6003. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6004. EXPECT_EQ(0U, res.headers.size());
  6005. EXPECT_FALSE(res.has_header("a"));
  6006. res.set_header("a", "1\nSet-Cookie: a=1");
  6007. EXPECT_EQ(0U, res.headers.size());
  6008. EXPECT_FALSE(res.has_header("a"));
  6009. res.set_header("a", "1\rSet-Cookie: a=1");
  6010. EXPECT_EQ(0U, res.headers.size());
  6011. EXPECT_FALSE(res.has_header("a"));
  6012. res.set_header("a\r\nb", "0");
  6013. EXPECT_EQ(0U, res.headers.size());
  6014. EXPECT_FALSE(res.has_header("a"));
  6015. res.set_header("a\rb", "0");
  6016. EXPECT_EQ(0U, res.headers.size());
  6017. EXPECT_FALSE(res.has_header("a"));
  6018. res.set_header("a\nb", "0");
  6019. EXPECT_EQ(0U, res.headers.size());
  6020. EXPECT_FALSE(res.has_header("a"));
  6021. res.set_redirect("1\r\nSet-Cookie: a=1");
  6022. EXPECT_EQ(0U, res.headers.size());
  6023. EXPECT_FALSE(res.has_header("Location"));
  6024. })
  6025. .Get("/slow",
  6026. [&](const Request & /*req*/, Response &res) {
  6027. std::this_thread::sleep_for(std::chrono::seconds(4));
  6028. res.set_content("slow", "text/plain");
  6029. })
  6030. #if 0
  6031. .Post("/slowpost",
  6032. [&](const Request & /*req*/, Response &res) {
  6033. std::this_thread::sleep_for(std::chrono::seconds(2));
  6034. res.set_content("slow", "text/plain");
  6035. })
  6036. #endif
  6037. .Get("/remote_addr",
  6038. [&](const Request &req, Response &res) {
  6039. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6040. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6041. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6042. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6043. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6044. #endif
  6045. res.set_content(req.remote_addr, "text/plain");
  6046. })
  6047. .Get("/local_addr",
  6048. [&](const Request &req, Response &res) {
  6049. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6050. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6051. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6052. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6053. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6054. #endif
  6055. auto local_addr = req.local_addr;
  6056. auto local_port = std::to_string(req.local_port);
  6057. res.set_content(local_addr.append(":").append(local_port),
  6058. "text/plain");
  6059. })
  6060. .Get("/endwith%",
  6061. [&](const Request & /*req*/, Response &res) {
  6062. res.set_content("Hello World!", "text/plain");
  6063. })
  6064. .Get("/a\\+\\+b",
  6065. [&](const Request &req, Response &res) {
  6066. ASSERT_TRUE(req.has_param("a +b"));
  6067. auto val = req.get_param_value("a +b");
  6068. res.set_content(val, "text/plain");
  6069. })
  6070. .Get("/", [&](const Request & /*req*/,
  6071. Response &res) { res.set_redirect("/hi"); })
  6072. .Post("/1",
  6073. [](const Request & /*req*/, Response &res) {
  6074. res.set_redirect("/2", StatusCode::SeeOther_303);
  6075. })
  6076. .Get("/2",
  6077. [](const Request & /*req*/, Response &res) {
  6078. res.set_content("redirected.", "text/plain");
  6079. res.status = StatusCode::OK_200;
  6080. })
  6081. .Post("/person",
  6082. [&](const Request &req, Response &res) {
  6083. if (req.has_param("name") && req.has_param("note")) {
  6084. persons_[req.get_param_value("name")] =
  6085. req.get_param_value("note");
  6086. } else {
  6087. res.status = StatusCode::BadRequest_400;
  6088. }
  6089. })
  6090. .Put("/person",
  6091. [&](const Request &req, Response &res) {
  6092. if (req.has_param("name") && req.has_param("note")) {
  6093. persons_[req.get_param_value("name")] =
  6094. req.get_param_value("note");
  6095. } else {
  6096. res.status = StatusCode::BadRequest_400;
  6097. }
  6098. })
  6099. .Get("/person/(.*)",
  6100. [&](const Request &req, Response &res) {
  6101. string name = req.matches[1];
  6102. if (persons_.find(name) != persons_.end()) {
  6103. auto note = persons_[name];
  6104. res.set_content(note, "text/plain");
  6105. } else {
  6106. res.status = StatusCode::NotFound_404;
  6107. }
  6108. })
  6109. .Delete("/person",
  6110. [&](const Request &req, Response &res) {
  6111. if (req.has_param("name")) {
  6112. string name = req.get_param_value("name");
  6113. if (persons_.find(name) != persons_.end()) {
  6114. persons_.erase(name);
  6115. res.set_content("DELETED", "text/plain");
  6116. } else {
  6117. res.status = StatusCode::NotFound_404;
  6118. }
  6119. } else {
  6120. res.status = StatusCode::BadRequest_400;
  6121. }
  6122. })
  6123. .Post("/x-www-form-urlencoded-json",
  6124. [&](const Request &req, Response &res) {
  6125. auto json = req.get_param_value("json");
  6126. ASSERT_EQ(JSON_DATA, json);
  6127. res.set_content(json, "appliation/json");
  6128. res.status = StatusCode::OK_200;
  6129. })
  6130. .Get("/streamed-chunked",
  6131. [&](const Request & /*req*/, Response &res) {
  6132. res.set_chunked_content_provider(
  6133. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6134. sink.os << "123";
  6135. sink.os << "456";
  6136. sink.os << "789";
  6137. sink.done();
  6138. return true;
  6139. });
  6140. })
  6141. .Get("/streamed-chunked-with-prohibited-trailer",
  6142. [&](const Request & /*req*/, Response &res) {
  6143. auto i = new int(0);
  6144. // Declare both a prohibited trailer (Content-Length) and an
  6145. // allowed one
  6146. res.set_header("Trailer", "Content-Length, X-Allowed");
  6147. res.set_chunked_content_provider(
  6148. "text/plain",
  6149. [i](size_t /*offset*/, DataSink &sink) {
  6150. switch (*i) {
  6151. case 0: sink.os << "123"; break;
  6152. case 1: sink.os << "456"; break;
  6153. case 2: sink.os << "789"; break;
  6154. case 3: {
  6155. sink.done_with_trailer(
  6156. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6157. } break;
  6158. }
  6159. (*i)++;
  6160. return true;
  6161. },
  6162. [i](bool success) {
  6163. EXPECT_TRUE(success);
  6164. delete i;
  6165. });
  6166. })
  6167. .Get("/streamed-chunked2",
  6168. [&](const Request & /*req*/, Response &res) {
  6169. auto i = new int(0);
  6170. res.set_chunked_content_provider(
  6171. "text/plain",
  6172. [i](size_t /*offset*/, DataSink &sink) {
  6173. switch (*i) {
  6174. case 0: sink.os << "123"; break;
  6175. case 1: sink.os << "456"; break;
  6176. case 2: sink.os << "789"; break;
  6177. case 3: sink.done(); break;
  6178. }
  6179. (*i)++;
  6180. return true;
  6181. },
  6182. [i](bool success) {
  6183. EXPECT_TRUE(success);
  6184. delete i;
  6185. });
  6186. })
  6187. .Get("/streamed-chunked-with-trailer",
  6188. [&](const Request & /*req*/, Response &res) {
  6189. auto i = new int(0);
  6190. res.set_header("Trailer", "Dummy1, Dummy2");
  6191. res.set_chunked_content_provider(
  6192. "text/plain",
  6193. [i](size_t /*offset*/, DataSink &sink) {
  6194. switch (*i) {
  6195. case 0: sink.os << "123"; break;
  6196. case 1: sink.os << "456"; break;
  6197. case 2: sink.os << "789"; break;
  6198. case 3: {
  6199. sink.done_with_trailer(
  6200. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6201. } break;
  6202. }
  6203. (*i)++;
  6204. return true;
  6205. },
  6206. [i](bool success) {
  6207. EXPECT_TRUE(success);
  6208. delete i;
  6209. });
  6210. })
  6211. .Get("/streamed",
  6212. [&](const Request & /*req*/, Response &res) {
  6213. res.set_content_provider(
  6214. 6, "text/plain",
  6215. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6216. sink.os << (offset < 3 ? "a" : "b");
  6217. return true;
  6218. });
  6219. })
  6220. .Get("/streamed-without-length",
  6221. [&](const Request & /*req*/, Response &res) {
  6222. auto data = new std::string("abcdefg");
  6223. res.set_content_provider(
  6224. "text/plain",
  6225. [data](size_t offset, DataSink &sink) {
  6226. if (offset < data->size()) {
  6227. sink.os << data->substr(offset);
  6228. }
  6229. sink.done();
  6230. return true;
  6231. },
  6232. [data](bool success) {
  6233. EXPECT_TRUE(success);
  6234. delete data;
  6235. });
  6236. })
  6237. .Get("/streamed-with-range",
  6238. [&](const Request &req, Response &res) {
  6239. auto data = new std::string("abcdefg");
  6240. // An explicit status keeps the server from picking the 206 it
  6241. // would otherwise choose for a ranged request, so the response
  6242. // is not a partial representation.
  6243. auto status = req.get_param_value("status");
  6244. if (status == "200") {
  6245. res.status = StatusCode::OK_200;
  6246. } else if (status == "403") {
  6247. res.status = StatusCode::Forbidden_403;
  6248. }
  6249. res.set_content_provider(
  6250. data->size(), "text/plain",
  6251. [data](size_t offset, size_t length, DataSink &sink) {
  6252. size_t DATA_CHUNK_SIZE = 4;
  6253. const auto &d = *data;
  6254. auto out_len =
  6255. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6256. auto ret =
  6257. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6258. EXPECT_TRUE(ret);
  6259. return true;
  6260. },
  6261. [data, &req](bool success) {
  6262. EXPECT_EQ(success, !req.has_param("error"));
  6263. delete data;
  6264. });
  6265. })
  6266. .Get("/streamed-cancel",
  6267. [&](const Request & /*req*/, Response &res) {
  6268. res.set_content_provider(
  6269. size_t(-1), "text/plain",
  6270. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6271. sink.os << "data_chunk";
  6272. return true;
  6273. });
  6274. })
  6275. .Get("/regex-with-delimiter",
  6276. [&](const Request &req, Response & /*res*/) {
  6277. ASSERT_TRUE(req.has_param("key"));
  6278. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6279. })
  6280. .Get("/with-range",
  6281. [&](const Request & /*req*/, Response &res) {
  6282. res.set_content("abcdefg", "text/plain");
  6283. })
  6284. .Get("/test-start-time",
  6285. [&](const Request &req, Response & /*res*/) {
  6286. EXPECT_NE(req.start_time_,
  6287. std::chrono::steady_clock::time_point::min());
  6288. })
  6289. .Get("/with-range-customized-response",
  6290. [&](const Request & /*req*/, Response &res) {
  6291. res.status = StatusCode::BadRequest_400;
  6292. res.set_content(JSON_DATA, "application/json");
  6293. })
  6294. .Post("/chunked",
  6295. [&](const Request &req, Response & /*res*/) {
  6296. EXPECT_EQ(req.body, "dechunked post body");
  6297. })
  6298. .Post("/large-chunked",
  6299. [&](const Request &req, Response & /*res*/) {
  6300. std::string expected(6 * 30 * 1024u, 'a');
  6301. EXPECT_EQ(req.body, expected);
  6302. })
  6303. .Post("/multipart",
  6304. [&](const Request &req, Response & /*res*/) {
  6305. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6306. req.form.get_field_count("text2") +
  6307. req.form.get_field_count("file3") +
  6308. req.form.get_field_count("file4"));
  6309. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6310. req.form.get_file_count("file2"));
  6311. ASSERT_TRUE(!req.form.has_file("???"));
  6312. ASSERT_TRUE(!req.form.has_field("???"));
  6313. ASSERT_TRUE(req.body.empty());
  6314. {
  6315. const auto &text = req.form.get_field("text1");
  6316. EXPECT_EQ("text default", text);
  6317. }
  6318. {
  6319. const auto &text = req.form.get_field("text2");
  6320. EXPECT_EQ("aωb", text);
  6321. }
  6322. {
  6323. const auto &file = req.form.get_file("file1");
  6324. EXPECT_EQ("hello.txt", file.filename);
  6325. EXPECT_EQ("text/plain", file.content_type);
  6326. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6327. }
  6328. {
  6329. const auto &file = req.form.get_file("file2");
  6330. EXPECT_EQ("world.json", file.filename);
  6331. EXPECT_EQ("application/json", file.content_type);
  6332. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6333. }
  6334. {
  6335. const auto &text = req.form.get_field("file3");
  6336. EXPECT_EQ(0u, text.size());
  6337. }
  6338. {
  6339. const auto &text = req.form.get_field("file4");
  6340. EXPECT_EQ(0u, text.size());
  6341. }
  6342. })
  6343. .Post("/multipart/multi_file_values",
  6344. [&](const Request &req, Response & /*res*/) {
  6345. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6346. req.form.get_field_count("multi_text1"));
  6347. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6348. ASSERT_TRUE(!req.form.has_file("???"));
  6349. ASSERT_TRUE(!req.form.has_field("???"));
  6350. ASSERT_TRUE(req.body.empty());
  6351. {
  6352. const auto &text = req.form.get_field("text");
  6353. EXPECT_EQ("default text", text);
  6354. }
  6355. {
  6356. const auto &text1_values = req.form.get_fields("multi_text1");
  6357. EXPECT_EQ(2u, text1_values.size());
  6358. EXPECT_EQ("aaaaa", text1_values[0]);
  6359. EXPECT_EQ("bbbbb", text1_values[1]);
  6360. }
  6361. {
  6362. const auto &file1_values = req.form.get_files("multi_file1");
  6363. EXPECT_EQ(2u, file1_values.size());
  6364. auto file1 = file1_values[0];
  6365. EXPECT_EQ(file1.filename, "hello.txt");
  6366. EXPECT_EQ(file1.content_type, "text/plain");
  6367. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6368. auto file2 = file1_values[1];
  6369. EXPECT_EQ(file2.filename, "world.json");
  6370. EXPECT_EQ(file2.content_type, "application/json");
  6371. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6372. }
  6373. })
  6374. .Post("/empty",
  6375. [&](const Request &req, Response &res) {
  6376. EXPECT_EQ(req.body, "");
  6377. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6378. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6379. res.set_content("empty", "text/plain");
  6380. })
  6381. .Post("/empty-no-content-type",
  6382. [&](const Request &req, Response &res) {
  6383. EXPECT_EQ(req.body, "");
  6384. EXPECT_FALSE(req.has_header("Content-Type"));
  6385. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6386. res.set_content("empty-no-content-type", "text/plain");
  6387. })
  6388. .Post("/path-only",
  6389. [&](const Request &req, Response &res) {
  6390. EXPECT_EQ(req.body, "");
  6391. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6392. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6393. res.set_content("path-only", "text/plain");
  6394. })
  6395. .Post("/path-headers-only",
  6396. [&](const Request &req, Response &res) {
  6397. EXPECT_EQ(req.body, "");
  6398. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6399. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6400. EXPECT_EQ("world", req.get_header_value("hello"));
  6401. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6402. res.set_content("path-headers-only", "text/plain");
  6403. })
  6404. .Post("/post-large",
  6405. [&](const Request &req, Response &res) {
  6406. EXPECT_EQ(req.body, LARGE_DATA);
  6407. res.set_content(req.body, "text/plain");
  6408. })
  6409. .Post("/post-loopback",
  6410. [&](const Request &, Response &res,
  6411. ContentReader const &content_reader) {
  6412. std::string body;
  6413. content_reader([&](const char *data, size_t data_length) {
  6414. body.append(data, data_length);
  6415. return true;
  6416. });
  6417. res.set_content(body, "text/plain");
  6418. })
  6419. .Put("/put-loopback",
  6420. [&](const Request &, Response &res,
  6421. ContentReader const &content_reader) {
  6422. std::string body;
  6423. content_reader([&](const char *data, size_t data_length) {
  6424. body.append(data, data_length);
  6425. return true;
  6426. });
  6427. res.set_content(body, "text/plain");
  6428. })
  6429. .Patch("/patch-loopback",
  6430. [&](const Request &, Response &res,
  6431. ContentReader const &content_reader) {
  6432. std::string body;
  6433. content_reader([&](const char *data, size_t data_length) {
  6434. body.append(data, data_length);
  6435. return true;
  6436. });
  6437. res.set_content(body, "text/plain");
  6438. })
  6439. .Put("/empty-no-content-type",
  6440. [&](const Request &req, Response &res) {
  6441. EXPECT_EQ(req.body, "");
  6442. EXPECT_FALSE(req.has_header("Content-Type"));
  6443. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6444. res.set_content("empty-no-content-type", "text/plain");
  6445. })
  6446. .Put("/put",
  6447. [&](const Request &req, Response &res) {
  6448. EXPECT_EQ(req.body, "PUT");
  6449. res.set_content(req.body, "text/plain");
  6450. })
  6451. .Put("/put-large",
  6452. [&](const Request &req, Response &res) {
  6453. EXPECT_EQ(req.body, LARGE_DATA);
  6454. res.set_content(req.body, "text/plain");
  6455. })
  6456. .Patch("/patch",
  6457. [&](const Request &req, Response &res) {
  6458. EXPECT_EQ(req.body, "PATCH");
  6459. res.set_content(req.body, "text/plain");
  6460. })
  6461. .Delete("/delete",
  6462. [&](const Request & /*req*/, Response &res) {
  6463. res.set_content("DELETE", "text/plain");
  6464. })
  6465. .Delete("/delete-body",
  6466. [&](const Request &req, Response &res) {
  6467. EXPECT_EQ(req.body, "content");
  6468. res.set_content(req.body, "text/plain");
  6469. })
  6470. .Options(R"(\*)",
  6471. [&](const Request & /*req*/, Response &res) {
  6472. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6473. })
  6474. .CustomRoute("PROPFIND", "/dav/:id",
  6475. [&](const Request &req, Response &res) {
  6476. res.set_header("x-body-size",
  6477. std::to_string(req.body.size()));
  6478. res.set_header("x-matched-route", req.matched_route);
  6479. res.set_header("x-dav-id", req.path_params.at("id"));
  6480. res.status = StatusCode::MultiStatus_207;
  6481. res.set_content(req.body, "application/xml");
  6482. })
  6483. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6484. [&](const Request &req, Response &res) {
  6485. res.set_header("x-dav-match", req.matches[1]);
  6486. res.status = StatusCode::MultiStatus_207;
  6487. })
  6488. .CustomRoute("MKCOL", "/dav-mkcol",
  6489. [&](const Request &req, Response &res) {
  6490. EXPECT_TRUE(req.body.empty());
  6491. res.status = StatusCode::Created_201;
  6492. })
  6493. .CustomRoute(
  6494. "REPORT", "/dav-report",
  6495. [&](const Request & /*req*/, Response &res,
  6496. const ContentReader &content_reader) {
  6497. std::string body;
  6498. content_reader([&](const char *data, size_t data_length) {
  6499. body.append(data, data_length);
  6500. return true;
  6501. });
  6502. res.set_header("x-body-size", std::to_string(body.size()));
  6503. res.status = StatusCode::MultiStatus_207;
  6504. res.set_content(body, "application/xml");
  6505. })
  6506. .Get("/request-target",
  6507. [&](const Request &req, Response & /*res*/) {
  6508. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6509. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6510. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6511. })
  6512. .Get("/long-query-value",
  6513. [&](const Request &req, Response & /*res*/) {
  6514. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6515. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6516. })
  6517. .Get("/too-long-query-value",
  6518. [&](const Request &req, Response & /*res*/) {
  6519. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6520. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6521. })
  6522. .Get("/array-param",
  6523. [&](const Request &req, Response & /*res*/) {
  6524. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6525. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6526. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6527. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6528. })
  6529. .Get("/array-param-values",
  6530. [&](const Request &req, Response & /*res*/) {
  6531. auto values = req.get_param_values("array");
  6532. EXPECT_EQ(3u, values.size());
  6533. EXPECT_EQ("value1", values[0]);
  6534. EXPECT_EQ("value2", values[1]);
  6535. EXPECT_EQ("value3", values[2]);
  6536. auto empty = req.get_param_values("nonexistent");
  6537. EXPECT_TRUE(empty.empty());
  6538. })
  6539. .Post("/validate-no-multiple-headers",
  6540. [&](const Request &req, Response & /*res*/) {
  6541. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6542. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6543. })
  6544. .Post("/content_receiver",
  6545. [&](const Request &req, Response &res,
  6546. const ContentReader &content_reader) {
  6547. if (req.is_multipart_form_data()) {
  6548. std::vector<FormData> items;
  6549. content_reader(
  6550. [&](const FormData &file) {
  6551. items.push_back(file);
  6552. return true;
  6553. },
  6554. [&](const char *data, size_t data_length) {
  6555. items.back().content.append(data, data_length);
  6556. return true;
  6557. });
  6558. EXPECT_EQ(5u, items.size());
  6559. {
  6560. const auto &file = get_file_value(items, "text1");
  6561. EXPECT_TRUE(file.filename.empty());
  6562. EXPECT_EQ("text default", file.content);
  6563. }
  6564. {
  6565. const auto &file = get_file_value(items, "text2");
  6566. EXPECT_TRUE(file.filename.empty());
  6567. EXPECT_EQ("aωb", file.content);
  6568. }
  6569. {
  6570. const auto &file = get_file_value(items, "file1");
  6571. EXPECT_EQ("hello.txt", file.filename);
  6572. EXPECT_EQ("text/plain", file.content_type);
  6573. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6574. }
  6575. {
  6576. const auto &file = get_file_value(items, "file2");
  6577. EXPECT_EQ("world.json", file.filename);
  6578. EXPECT_EQ("application/json", file.content_type);
  6579. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6580. }
  6581. {
  6582. const auto &file = get_file_value(items, "file3");
  6583. EXPECT_TRUE(file.filename.empty());
  6584. EXPECT_EQ("application/octet-stream", file.content_type);
  6585. EXPECT_EQ(0u, file.content.size());
  6586. }
  6587. } else {
  6588. std::string body;
  6589. content_reader([&](const char *data, size_t data_length) {
  6590. EXPECT_EQ(7U, data_length);
  6591. body.append(data, data_length);
  6592. return true;
  6593. });
  6594. EXPECT_EQ(body, "content");
  6595. res.set_content(body, "text/plain");
  6596. }
  6597. })
  6598. .Put("/content_receiver",
  6599. [&](const Request & /*req*/, Response &res,
  6600. const ContentReader &content_reader) {
  6601. std::string body;
  6602. content_reader([&](const char *data, size_t data_length) {
  6603. body.append(data, data_length);
  6604. return true;
  6605. });
  6606. EXPECT_EQ(body, "content");
  6607. res.set_content(body, "text/plain");
  6608. })
  6609. .Patch("/content_receiver",
  6610. [&](const Request & /*req*/, Response &res,
  6611. const ContentReader &content_reader) {
  6612. std::string body;
  6613. content_reader([&](const char *data, size_t data_length) {
  6614. body.append(data, data_length);
  6615. return true;
  6616. });
  6617. EXPECT_EQ(body, "content");
  6618. res.set_content(body, "text/plain");
  6619. })
  6620. .Post("/query-string-and-body",
  6621. [&](const Request &req, Response & /*res*/) {
  6622. ASSERT_TRUE(req.has_param("key"));
  6623. EXPECT_EQ(req.get_param_value("key"), "value");
  6624. EXPECT_EQ(req.body, "content");
  6625. })
  6626. .Get("/last-request",
  6627. [&](const Request &req, Response & /*res*/) {
  6628. EXPECT_EQ("close", req.get_header_value("Connection"));
  6629. })
  6630. .Get(R"(/redirect/(\d+))",
  6631. [&](const Request &req, Response &res) {
  6632. auto num = std::stoi(req.matches[1]) + 1;
  6633. std::string url = "/redirect/" + std::to_string(num);
  6634. res.set_redirect(url);
  6635. })
  6636. .Post("/binary",
  6637. [&](const Request &req, Response &res) {
  6638. EXPECT_EQ(4U, req.body.size());
  6639. EXPECT_EQ("application/octet-stream",
  6640. req.get_header_value("Content-Type"));
  6641. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6642. res.set_content(req.body, "application/octet-stream");
  6643. })
  6644. .Put("/binary",
  6645. [&](const Request &req, Response &res) {
  6646. EXPECT_EQ(4U, req.body.size());
  6647. EXPECT_EQ("application/octet-stream",
  6648. req.get_header_value("Content-Type"));
  6649. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6650. res.set_content(req.body, "application/octet-stream");
  6651. })
  6652. .Patch("/binary",
  6653. [&](const Request &req, Response &res) {
  6654. EXPECT_EQ(4U, req.body.size());
  6655. EXPECT_EQ("application/octet-stream",
  6656. req.get_header_value("Content-Type"));
  6657. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6658. res.set_content(req.body, "application/octet-stream");
  6659. })
  6660. .Delete("/binary",
  6661. [&](const Request &req, Response &res) {
  6662. EXPECT_EQ(4U, req.body.size());
  6663. EXPECT_EQ("application/octet-stream",
  6664. req.get_header_value("Content-Type"));
  6665. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6666. res.set_content(req.body, "application/octet-stream");
  6667. })
  6668. .Get("/issue1772",
  6669. [&](const Request & /*req*/, Response &res) {
  6670. res.status = 401;
  6671. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6672. })
  6673. .Delete("/issue609",
  6674. [](const httplib::Request &, httplib::Response &res,
  6675. const httplib::ContentReader &) {
  6676. res.set_content("ok", "text/plain");
  6677. })
  6678. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6679. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6680. .Get("/compress",
  6681. [&](const Request & /*req*/, Response &res) {
  6682. res.set_content(
  6683. "12345678901234567890123456789012345678901234567890123456789"
  6684. "01234567890123456789012345678901234567890",
  6685. "text/plain");
  6686. })
  6687. .Get("/compress-with-charset",
  6688. [&](const Request & /*req*/, Response &res) {
  6689. res.set_content(
  6690. "12345678901234567890123456789012345678901234567890123456789"
  6691. "01234567890123456789012345678901234567890",
  6692. "application/json; charset=utf-8");
  6693. })
  6694. .Get("/nocompress",
  6695. [&](const Request & /*req*/, Response &res) {
  6696. res.set_content(
  6697. "12345678901234567890123456789012345678901234567890123456789"
  6698. "01234567890123456789012345678901234567890",
  6699. "application/octet-stream");
  6700. })
  6701. .Post("/compress-multipart",
  6702. [&](const Request &req, Response & /*res*/) {
  6703. EXPECT_EQ(2u, req.form.fields.size());
  6704. ASSERT_TRUE(!req.form.has_field("???"));
  6705. {
  6706. const auto &text = req.form.get_field("key1");
  6707. EXPECT_EQ("test", text);
  6708. }
  6709. {
  6710. const auto &text = req.form.get_field("key2");
  6711. EXPECT_EQ("--abcdefg123", text);
  6712. }
  6713. })
  6714. #endif
  6715. ;
  6716. persons_["john"] = "programmer";
  6717. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6718. svr_.wait_until_ready();
  6719. }
  6720. virtual void TearDown() {
  6721. svr_.stop();
  6722. if (!request_threads_.empty()) {
  6723. std::this_thread::sleep_for(std::chrono::seconds(1));
  6724. for (auto &t : request_threads_) {
  6725. t.join();
  6726. }
  6727. }
  6728. t_.join();
  6729. }
  6730. map<string, string> persons_;
  6731. #ifdef CPPHTTPLIB_SSL_ENABLED
  6732. SSLClient cli_;
  6733. SSLServer svr_;
  6734. #else
  6735. Client cli_;
  6736. Server svr_;
  6737. #endif
  6738. thread t_;
  6739. std::vector<thread> request_threads_;
  6740. };
  6741. TEST_F(ServerTest, GetMethod200) {
  6742. auto res = cli_.Get("/hi");
  6743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6744. EXPECT_EQ("HTTP/1.1", res->version);
  6745. EXPECT_EQ(StatusCode::OK_200, res->status);
  6746. EXPECT_EQ("OK", res->reason);
  6747. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6748. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6749. EXPECT_EQ("Hello World!", res->body);
  6750. }
  6751. TEST_F(ServerTest, GetEmptyFile) {
  6752. auto res = cli_.Get("/empty_file");
  6753. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6754. EXPECT_EQ(StatusCode::OK_200, res->status);
  6755. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6756. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6757. EXPECT_EQ("", res->body);
  6758. }
  6759. TEST_F(ServerTest, GetFileContent) {
  6760. auto res = cli_.Get("/file_content");
  6761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6762. EXPECT_EQ(StatusCode::OK_200, res->status);
  6763. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6764. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6765. EXPECT_EQ("test.html", res->body);
  6766. }
  6767. TEST_F(ServerTest, GetFileContentWithRange) {
  6768. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6770. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6771. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6772. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6773. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6774. EXPECT_EQ("est", res->body);
  6775. }
  6776. TEST_F(ServerTest, GetFileContentWithContentType) {
  6777. auto res = cli_.Get("/file_content_with_content_type");
  6778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6779. EXPECT_EQ(StatusCode::OK_200, res->status);
  6780. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6781. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6782. EXPECT_EQ("file\n", res->body);
  6783. }
  6784. TEST_F(ServerTest, GetInvalidFileContent) {
  6785. auto res = cli_.Get("/invalid_file_content");
  6786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6787. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6788. }
  6789. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6790. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6791. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6792. EXPECT_EQ("HTTP/1.1", res->version);
  6793. EXPECT_EQ(StatusCode::OK_200, res->status);
  6794. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6795. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6796. EXPECT_EQ("Hello World!", res->body);
  6797. }
  6798. TEST_F(ServerTest, GetMethod302) {
  6799. auto res = cli_.Get("/");
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::Found_302, res->status);
  6802. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6803. }
  6804. TEST_F(ServerTest, GetMethod302Redirect) {
  6805. cli_.set_follow_location(true);
  6806. auto res = cli_.Get("/");
  6807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6808. EXPECT_EQ(StatusCode::OK_200, res->status);
  6809. EXPECT_EQ("Hello World!", res->body);
  6810. EXPECT_EQ("/hi", res->location);
  6811. }
  6812. TEST_F(ServerTest, GetMethod404) {
  6813. auto res = cli_.Get("/invalid");
  6814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6815. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6816. }
  6817. TEST_F(ServerTest, HeadMethod200) {
  6818. auto res = cli_.Head("/hi");
  6819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6820. EXPECT_EQ(StatusCode::OK_200, res->status);
  6821. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6822. EXPECT_TRUE(res->body.empty());
  6823. }
  6824. TEST_F(ServerTest, HeadMethod200Static) {
  6825. auto res = cli_.Head("/mount/dir/index.html");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6829. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6830. EXPECT_TRUE(res->body.empty());
  6831. }
  6832. TEST_F(ServerTest, HeadMethod404) {
  6833. auto res = cli_.Head("/invalid");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6836. EXPECT_TRUE(res->body.empty());
  6837. }
  6838. TEST_F(ServerTest, GetMethodPersonJohn) {
  6839. auto res = cli_.Get("/person/john");
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ(StatusCode::OK_200, res->status);
  6842. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6843. EXPECT_EQ("programmer", res->body);
  6844. }
  6845. TEST_F(ServerTest, PostMethod1) {
  6846. auto res = cli_.Get("/person/john1");
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6849. res = cli_.Post("/person", "name=john1&note=coder",
  6850. "application/x-www-form-urlencoded");
  6851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6852. ASSERT_EQ(StatusCode::OK_200, res->status);
  6853. res = cli_.Get("/person/john1");
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. ASSERT_EQ(StatusCode::OK_200, res->status);
  6856. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6857. ASSERT_EQ("coder", res->body);
  6858. }
  6859. TEST_F(ServerTest, PostMethod2) {
  6860. auto res = cli_.Get("/person/john2");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6863. Params params;
  6864. params.emplace("name", "john2");
  6865. params.emplace("note", "coder");
  6866. res = cli_.Post("/person", params);
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. ASSERT_EQ(StatusCode::OK_200, res->status);
  6869. res = cli_.Get("/person/john2");
  6870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6871. ASSERT_EQ(StatusCode::OK_200, res->status);
  6872. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6873. ASSERT_EQ("coder", res->body);
  6874. }
  6875. TEST_F(ServerTest, PutMethod3) {
  6876. auto res = cli_.Get("/person/john3");
  6877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6878. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6879. Params params;
  6880. params.emplace("name", "john3");
  6881. params.emplace("note", "coder");
  6882. res = cli_.Put("/person", params);
  6883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6884. ASSERT_EQ(StatusCode::OK_200, res->status);
  6885. res = cli_.Get("/person/john3");
  6886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6887. ASSERT_EQ(StatusCode::OK_200, res->status);
  6888. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6889. ASSERT_EQ("coder", res->body);
  6890. }
  6891. TEST_F(ServerTest, DeleteMethod1) {
  6892. auto res = cli_.Get("/person/john4");
  6893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6894. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6895. Params params;
  6896. params.emplace("name", "john4");
  6897. params.emplace("note", "coder");
  6898. res = cli_.Post("/person", params);
  6899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6900. ASSERT_EQ(StatusCode::OK_200, res->status);
  6901. res = cli_.Get("/person/john4");
  6902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6903. ASSERT_EQ(StatusCode::OK_200, res->status);
  6904. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6905. ASSERT_EQ("coder", res->body);
  6906. Params delete_params;
  6907. delete_params.emplace("name", "john4");
  6908. res = cli_.Delete("/person", delete_params);
  6909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6910. ASSERT_EQ(StatusCode::OK_200, res->status);
  6911. ASSERT_EQ("DELETED", res->body);
  6912. res = cli_.Get("/person/john4");
  6913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6914. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6915. }
  6916. TEST_F(ServerTest, DeleteMethod2) {
  6917. auto res = cli_.Get("/person/john5");
  6918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6919. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6920. Params params;
  6921. params.emplace("name", "john5");
  6922. params.emplace("note", "developer");
  6923. res = cli_.Post("/person", params);
  6924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6925. ASSERT_EQ(StatusCode::OK_200, res->status);
  6926. res = cli_.Get("/person/john5");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::OK_200, res->status);
  6929. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6930. ASSERT_EQ("developer", res->body);
  6931. Params delete_params;
  6932. delete_params.emplace("name", "john5");
  6933. Headers headers;
  6934. headers.emplace("Custom-Header", "test-value");
  6935. res = cli_.Delete("/person", headers, delete_params);
  6936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6937. ASSERT_EQ(StatusCode::OK_200, res->status);
  6938. ASSERT_EQ("DELETED", res->body);
  6939. res = cli_.Get("/person/john5");
  6940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6941. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6942. }
  6943. TEST_F(ServerTest, DeleteMethod3) {
  6944. auto res = cli_.Get("/person/john6");
  6945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6946. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6947. Params params;
  6948. params.emplace("name", "john6");
  6949. params.emplace("note", "tester");
  6950. res = cli_.Post("/person", params);
  6951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6952. ASSERT_EQ(StatusCode::OK_200, res->status);
  6953. res = cli_.Get("/person/john6");
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. ASSERT_EQ(StatusCode::OK_200, res->status);
  6956. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6957. ASSERT_EQ("tester", res->body);
  6958. Params delete_params;
  6959. delete_params.emplace("name", "john6");
  6960. Headers headers;
  6961. headers.emplace("Custom-Header", "test-value");
  6962. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6964. ASSERT_EQ(StatusCode::OK_200, res->status);
  6965. ASSERT_EQ("DELETED", res->body);
  6966. res = cli_.Get("/person/john6");
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6969. }
  6970. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6971. Params params;
  6972. params.emplace("json", JSON_DATA);
  6973. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. ASSERT_EQ(StatusCode::OK_200, res->status);
  6976. ASSERT_EQ(JSON_DATA, res->body);
  6977. }
  6978. TEST_F(ServerTest, PostEmptyContent) {
  6979. auto res = cli_.Post("/empty", "", "text/plain");
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. ASSERT_EQ(StatusCode::OK_200, res->status);
  6982. ASSERT_EQ("empty", res->body);
  6983. }
  6984. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6985. auto res = cli_.Post("/empty-no-content-type");
  6986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6987. ASSERT_EQ(StatusCode::OK_200, res->status);
  6988. ASSERT_EQ("empty-no-content-type", res->body);
  6989. }
  6990. TEST_F(ServerTest, PostPathOnly) {
  6991. auto res = cli_.Post("/path-only");
  6992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6993. ASSERT_EQ(StatusCode::OK_200, res->status);
  6994. ASSERT_EQ("path-only", res->body);
  6995. }
  6996. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6997. auto res = cli_.Post("/path-headers-only",
  6998. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7000. ASSERT_EQ(StatusCode::OK_200, res->status);
  7001. ASSERT_EQ("path-headers-only", res->body);
  7002. }
  7003. TEST_F(ServerTest, PostLarge) {
  7004. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7005. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7006. ASSERT_EQ(StatusCode::OK_200, res->status);
  7007. EXPECT_EQ(LARGE_DATA, res->body);
  7008. }
  7009. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7010. auto res = cli_.Put("/empty-no-content-type");
  7011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7012. ASSERT_EQ(StatusCode::OK_200, res->status);
  7013. ASSERT_EQ("empty-no-content-type", res->body);
  7014. }
  7015. TEST_F(ServerTest, GetMethodDir) {
  7016. auto res = cli_.Get("/dir/");
  7017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7018. EXPECT_EQ(StatusCode::OK_200, res->status);
  7019. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7020. auto body = R"(<html>
  7021. <head>
  7022. </head>
  7023. <body>
  7024. <a href="/dir/test.html">Test</a>
  7025. <a href="/hi">hi</a>
  7026. </body>
  7027. </html>
  7028. )";
  7029. EXPECT_EQ(body, res->body);
  7030. }
  7031. TEST_F(ServerTest, GetMethodDirTest) {
  7032. auto res = cli_.Get("/dir/test.html");
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. EXPECT_EQ(StatusCode::OK_200, res->status);
  7035. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7036. EXPECT_EQ("test.html", res->body);
  7037. }
  7038. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7039. auto res = cli_.Get("/dir/../dir/test.html");
  7040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7041. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7042. }
  7043. TEST_F(ServerTest, GetMethodInvalidPath) {
  7044. auto res = cli_.Get("/dir/../test.html");
  7045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7046. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7047. }
  7048. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7049. auto res = cli_.Get("/../www/dir/test.html");
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7052. }
  7053. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7054. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7055. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7056. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7057. }
  7058. TEST_F(ServerTest, GetMethodDirMountTest) {
  7059. auto res = cli_.Get("/mount/dir/test.html");
  7060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7061. EXPECT_EQ(StatusCode::OK_200, res->status);
  7062. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7063. EXPECT_EQ("test.html", res->body);
  7064. }
  7065. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7066. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7069. }
  7070. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7071. auto res = cli_.Get("/mount/dir/../test.html");
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7074. }
  7075. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7076. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7078. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7079. }
  7080. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7081. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7083. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7084. }
  7085. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7086. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7088. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7089. }
  7090. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7091. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7093. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7094. }
  7095. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7096. auto res = cli_.Get("/mount/dir");
  7097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7098. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7099. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7100. }
  7101. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7102. auto res = cli_.Get("//dir");
  7103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7104. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7105. EXPECT_FALSE(res->has_header("Location"));
  7106. }
  7107. TEST_F(ServerTest, PostMethod303) {
  7108. auto res = cli_.Post("/1", "body", "text/plain");
  7109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7110. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7111. EXPECT_EQ("/2", res->get_header_value("Location"));
  7112. }
  7113. TEST_F(ServerTest, PostMethod303Redirect) {
  7114. cli_.set_follow_location(true);
  7115. auto res = cli_.Post("/1", "body", "text/plain");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::OK_200, res->status);
  7118. EXPECT_EQ("redirected.", res->body);
  7119. EXPECT_EQ("/2", res->location);
  7120. }
  7121. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7122. auto res = cli_.Get("/dir/test.abcde");
  7123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7124. EXPECT_EQ(StatusCode::OK_200, res->status);
  7125. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7126. EXPECT_EQ("abcde", res->body);
  7127. }
  7128. TEST_F(ServerTest, StaticFileRange) {
  7129. auto res =
  7130. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7133. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7134. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7135. EXPECT_EQ(true, res->has_header("Content-Range"));
  7136. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7137. EXPECT_EQ(std::string("cd"), res->body);
  7138. }
  7139. TEST_F(ServerTest, StaticFileRanges) {
  7140. auto res = cli_.Get("/dir/test.abcde",
  7141. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7142. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7143. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7144. EXPECT_TRUE(
  7145. res->get_header_value("Content-Type")
  7146. .find(
  7147. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7148. 0);
  7149. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7150. }
  7151. TEST_F(ServerTest, StaticFileRangeHead) {
  7152. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7155. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7156. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7157. EXPECT_EQ(true, res->has_header("Content-Range"));
  7158. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7159. }
  7160. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7161. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7163. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7164. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7165. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7166. EXPECT_EQ(true, res->has_header("Content-Range"));
  7167. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7168. res->get_header_value("Content-Range"));
  7169. EXPECT_EQ("LAST\n", res->body);
  7170. }
  7171. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7172. auto res =
  7173. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7175. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7177. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7178. EXPECT_EQ(true, res->has_header("Content-Range"));
  7179. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7180. }
  7181. TEST_F(ServerTest, StaticFileBigFile) {
  7182. auto res = cli_.Get("/dir/1MB.txt");
  7183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7184. EXPECT_EQ(StatusCode::OK_200, res->status);
  7185. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7186. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7187. }
  7188. TEST_F(ServerTest, InvalidBaseDirMount) {
  7189. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7190. }
  7191. TEST_F(ServerTest, Binary) {
  7192. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7193. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7194. "application/octet-stream");
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. ASSERT_EQ(StatusCode::OK_200, res->status);
  7197. ASSERT_EQ(4U, res->body.size());
  7198. res = cli_.Put("/binary", binary.data(), binary.size(),
  7199. "application/octet-stream");
  7200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7201. ASSERT_EQ(StatusCode::OK_200, res->status);
  7202. ASSERT_EQ(4U, res->body.size());
  7203. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7204. "application/octet-stream");
  7205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7206. ASSERT_EQ(StatusCode::OK_200, res->status);
  7207. ASSERT_EQ(4U, res->body.size());
  7208. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7209. "application/octet-stream");
  7210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7211. ASSERT_EQ(StatusCode::OK_200, res->status);
  7212. ASSERT_EQ(4U, res->body.size());
  7213. }
  7214. TEST_F(ServerTest, BinaryString) {
  7215. auto binary = std::string("\x00\x01\x02\x03", 4);
  7216. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. ASSERT_EQ(StatusCode::OK_200, res->status);
  7219. ASSERT_EQ(4U, res->body.size());
  7220. res = cli_.Put("/binary", binary, "application/octet-stream");
  7221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7222. ASSERT_EQ(StatusCode::OK_200, res->status);
  7223. ASSERT_EQ(4U, res->body.size());
  7224. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7226. ASSERT_EQ(StatusCode::OK_200, res->status);
  7227. ASSERT_EQ(4U, res->body.size());
  7228. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. ASSERT_EQ(StatusCode::OK_200, res->status);
  7231. ASSERT_EQ(4U, res->body.size());
  7232. }
  7233. TEST_F(ServerTest, EmptyRequest) {
  7234. auto res = cli_.Get("");
  7235. ASSERT_TRUE(!res);
  7236. EXPECT_EQ(Error::Connection, res.error());
  7237. }
  7238. TEST_F(ServerTest, LongRequest) {
  7239. std::string request;
  7240. for (size_t i = 0; i < 545; i++) {
  7241. request += "/TooLongRequest";
  7242. }
  7243. request += "OK";
  7244. auto res = cli_.Get(request.c_str());
  7245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7246. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7247. }
  7248. TEST_F(ServerTest, TooLongRequest) {
  7249. std::string request;
  7250. for (size_t i = 0; i < 546; i++) {
  7251. request += "/TooLongRequest";
  7252. }
  7253. request += "_NG";
  7254. auto start = std::chrono::high_resolution_clock::now();
  7255. cli_.set_keep_alive(true);
  7256. auto res = cli_.Get(request.c_str());
  7257. auto end = std::chrono::high_resolution_clock::now();
  7258. auto elapsed =
  7259. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7260. .count();
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7263. EXPECT_LE(elapsed, 1000);
  7264. EXPECT_EQ("close", res->get_header_value("Connection"));
  7265. EXPECT_FALSE(cli_.is_socket_open());
  7266. }
  7267. TEST_F(ServerTest, AlmostTooLongRequest) {
  7268. // test for #2046 - URI length check shouldn't include other content on req
  7269. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7270. // leading /, space, HTTP/1.1)
  7271. std::string request =
  7272. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7273. auto res = cli_.Get(request.c_str());
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7276. }
  7277. TEST_F(ServerTest, LongHeader) {
  7278. Request req;
  7279. req.method = "GET";
  7280. req.path = "/hi";
  7281. std::string host_and_port;
  7282. host_and_port += HOST;
  7283. host_and_port += ":";
  7284. host_and_port += std::to_string(PORT);
  7285. req.headers.emplace("Host", host_and_port.c_str());
  7286. req.headers.emplace("Accept", "*/*");
  7287. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7288. req.headers.emplace(
  7289. "Header-Name",
  7290. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7291. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7292. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7293. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7294. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7295. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7296. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7297. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7298. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7299. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7300. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7301. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7302. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7303. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7304. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7305. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7306. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7307. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7308. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7309. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7310. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7311. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7312. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7313. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7314. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7315. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7316. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7317. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7318. "@@@@@@@@@@@@@@@@");
  7319. auto res = std::make_shared<Response>();
  7320. auto error = Error::Success;
  7321. auto ret = cli_.send(req, *res, error);
  7322. ASSERT_TRUE(ret);
  7323. EXPECT_EQ(StatusCode::OK_200, res->status);
  7324. }
  7325. TEST_F(ServerTest, LongQueryValue) {
  7326. auto start = std::chrono::high_resolution_clock::now();
  7327. cli_.set_keep_alive(true);
  7328. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7329. auto end = std::chrono::high_resolution_clock::now();
  7330. auto elapsed =
  7331. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7332. .count();
  7333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7334. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7335. EXPECT_LE(elapsed, 1000);
  7336. EXPECT_EQ("close", res->get_header_value("Connection"));
  7337. EXPECT_FALSE(cli_.is_socket_open());
  7338. }
  7339. TEST_F(ServerTest, TooLongQueryValue) {
  7340. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7341. ASSERT_FALSE(res);
  7342. EXPECT_EQ(Error::Read, res.error());
  7343. }
  7344. TEST_F(ServerTest, TooLongHeader) {
  7345. Request req;
  7346. req.method = "GET";
  7347. req.path = "/hi";
  7348. std::string host_and_port;
  7349. host_and_port += HOST;
  7350. host_and_port += ":";
  7351. host_and_port += std::to_string(PORT);
  7352. req.headers.emplace("Host", host_and_port.c_str());
  7353. req.headers.emplace("Accept", "*/*");
  7354. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7355. req.headers.emplace(
  7356. "Header-Name",
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7359. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7360. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7361. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7362. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7363. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7364. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7365. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7366. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7367. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7368. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7369. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7370. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7371. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7372. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7373. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7374. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7375. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7376. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7377. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7378. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7379. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7380. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7381. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7382. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7383. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7384. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7385. "@@@@@@@@@@@@@@@@@");
  7386. auto res = std::make_shared<Response>();
  7387. auto error = Error::Success;
  7388. auto ret = cli_.send(req, *res, error);
  7389. ASSERT_TRUE(ret);
  7390. EXPECT_EQ(StatusCode::OK_200, res->status);
  7391. }
  7392. TEST_F(ServerTest, HeaderCountAtLimit) {
  7393. // Test with headers just under the 100 limit
  7394. httplib::Headers headers;
  7395. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7396. // This should keep us just under the 100 header limit
  7397. for (int i = 0; i < 95; i++) {
  7398. std::string name = "X-Test-Header-" + std::to_string(i);
  7399. std::string value = "value" + std::to_string(i);
  7400. headers.emplace(name, value);
  7401. }
  7402. // This should work fine as we're under the limit
  7403. auto res = cli_.Get("/hi", headers);
  7404. EXPECT_TRUE(res);
  7405. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7406. }
  7407. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7408. // Test with many headers to exceed the 100 limit
  7409. httplib::Headers headers;
  7410. // Add 150 headers to definitely exceed the 100 limit
  7411. for (int i = 0; i < 150; i++) {
  7412. std::string name = "X-Test-Header-" + std::to_string(i);
  7413. std::string value = "value" + std::to_string(i);
  7414. headers.emplace(name, value);
  7415. }
  7416. // This should fail due to exceeding header count limit
  7417. cli_.set_keep_alive(true);
  7418. auto res = cli_.Get("/hi", headers);
  7419. // The server should respond with 400 Bad Request
  7420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7421. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7422. EXPECT_EQ("close", res->get_header_value("Connection"));
  7423. EXPECT_FALSE(cli_.is_socket_open());
  7424. }
  7425. TEST_F(ServerTest, PercentEncoding) {
  7426. auto res = cli_.Get("/e%6edwith%");
  7427. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7428. EXPECT_EQ(StatusCode::OK_200, res->status);
  7429. }
  7430. TEST_F(ServerTest, PercentEncodingUnicode) {
  7431. auto res = cli_.Get("/e%u006edwith%");
  7432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7433. EXPECT_EQ(StatusCode::OK_200, res->status);
  7434. }
  7435. TEST_F(ServerTest, InvalidPercentEncoding) {
  7436. auto res = cli_.Get("/%endwith%");
  7437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7438. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7439. }
  7440. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7441. auto res = cli_.Get("/%uendwith%");
  7442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7443. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7444. }
  7445. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7446. auto res = cli_.Get("/hello?aaa=bbb%");
  7447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7448. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7449. }
  7450. TEST_F(ServerTest, PlusSignEncoding) {
  7451. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7453. EXPECT_EQ(StatusCode::OK_200, res->status);
  7454. EXPECT_EQ("a +b", res->body);
  7455. }
  7456. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7457. // This test simulates a potential DoS attack using many headers
  7458. // to verify our security fix prevents memory exhaustion
  7459. httplib::Headers attack_headers;
  7460. // Attempt to add many headers like an attacker would (200 headers to far
  7461. // exceed limit)
  7462. for (int i = 0; i < 200; i++) {
  7463. std::string name = "X-Attack-Header-" + std::to_string(i);
  7464. std::string value = "attack_payload_" + std::to_string(i);
  7465. attack_headers.emplace(name, value);
  7466. }
  7467. // Try to POST with excessive headers
  7468. cli_.set_keep_alive(true);
  7469. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7470. // Should either fail or return 400 Bad Request due to security limit
  7471. if (res) {
  7472. // If we get a response, it should be 400 Bad Request
  7473. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7474. EXPECT_EQ("close", res->get_header_value("Connection"));
  7475. }
  7476. EXPECT_FALSE(cli_.is_socket_open());
  7477. }
  7478. TEST_F(ServerTest, MultipartFormData) {
  7479. UploadFormDataItems items = {
  7480. {"text1", "text default", "", ""},
  7481. {"text2", "aωb", "", ""},
  7482. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7483. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7484. {"file3", "", "", "application/octet-stream"},
  7485. {"file4", "", "", " application/json tmp-string "}};
  7486. auto res = cli_.Post("/multipart", items);
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::OK_200, res->status);
  7489. }
  7490. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7491. UploadFormDataItems items = {
  7492. {"text", "default text", "", ""},
  7493. {"multi_text1", "aaaaa", "", ""},
  7494. {"multi_text1", "bbbbb", "", ""},
  7495. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7496. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7497. "application/json"},
  7498. };
  7499. auto res = cli_.Post("/multipart/multi_file_values", items);
  7500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7501. EXPECT_EQ(StatusCode::OK_200, res->status);
  7502. }
  7503. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7504. auto res = cli_.Get("/hi");
  7505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7506. EXPECT_EQ(StatusCode::OK_200, res->status);
  7507. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7508. EXPECT_EQ("Hello World!", res->body);
  7509. }
  7510. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7511. Request req;
  7512. req.method = "POST";
  7513. req.path = "/chunked";
  7514. std::string host_and_port;
  7515. host_and_port += HOST;
  7516. host_and_port += ":";
  7517. host_and_port += std::to_string(PORT);
  7518. req.headers.emplace("Host", host_and_port.c_str());
  7519. req.headers.emplace("Accept", "*/*");
  7520. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7521. req.headers.emplace("Content-Type", "text/plain");
  7522. req.headers.emplace("Content-Length", "0");
  7523. req.headers.emplace(
  7524. "Transfer-Encoding",
  7525. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7526. // Client does not chunk, so make a chunked body manually.
  7527. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7528. auto res = std::make_shared<Response>();
  7529. auto error = Error::Success;
  7530. auto ret = cli_.send(req, *res, error);
  7531. ASSERT_TRUE(ret);
  7532. EXPECT_EQ(StatusCode::OK_200, res->status);
  7533. }
  7534. template <typename ClientT>
  7535. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7536. int expected_status) {
  7537. Request req;
  7538. req.method = "POST";
  7539. req.path = "/chunked";
  7540. std::string host_and_port;
  7541. host_and_port += HOST;
  7542. host_and_port += ":";
  7543. host_and_port += std::to_string(PORT);
  7544. req.headers.emplace("Host", host_and_port.c_str());
  7545. req.headers.emplace("Content-Length", "0");
  7546. req.headers.emplace("Transfer-Encoding", "chunked");
  7547. req.body = body;
  7548. auto res = std::make_shared<Response>();
  7549. auto error = Error::Success;
  7550. ASSERT_TRUE(cli.send(req, *res, error));
  7551. EXPECT_EQ(expected_status, res->status);
  7552. }
  7553. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7554. // rather than treat them as valid lengths.
  7555. template <typename ClientT>
  7556. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7557. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7558. }
  7559. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7560. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7561. }
  7562. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7563. expect_chunked_body_rejected(
  7564. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7565. }
  7566. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7567. // chunk-size line carries no CR, LF or other control character ahead of its
  7568. // terminator. Such a line must be refused rather than read as extension text.
  7569. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7570. expect_chunked_body_rejected(
  7571. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7572. }
  7573. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7574. expect_chunked_body_rejected(
  7575. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7576. }
  7577. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7578. expect_chunked_body_rejected(
  7579. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7580. }
  7581. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7582. // The literal stays split: a hex escape consumes every hex digit that
  7583. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7584. expect_chunked_body_rejected(
  7585. cli_, "4;a\x01"
  7586. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7587. }
  7588. // The bytes around chunk data are no payload, so they cannot ride on the
  7589. // payload limit
  7590. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7591. // Small enough that the whole request is sent before the server turns it
  7592. // down, yet past the limit by the last chunks
  7593. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7594. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7595. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7596. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7597. SCOPED_TRACE(size_line.substr(0, 2));
  7598. std::string body;
  7599. for (auto c : std::string("dechunked post body")) {
  7600. body += size_line + "\r\n" + c + "\r\n";
  7601. }
  7602. body += "0\r\n\r\n";
  7603. expect_chunked_body_rejected(cli_, body.c_str());
  7604. }
  7605. }
  7606. TEST_F(ServerTest, AcceptsChunkExtension) {
  7607. expect_chunked_body_status(cli_,
  7608. "4;name=value\r\ndech\r\n"
  7609. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7610. "0;last\r\n\r\n",
  7611. StatusCode::OK_200);
  7612. }
  7613. TEST_F(ServerTest, GetStreamed2) {
  7614. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7616. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7617. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7618. EXPECT_EQ(true, res->has_header("Content-Range"));
  7619. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7620. EXPECT_EQ(std::string("ab"), res->body);
  7621. }
  7622. TEST_F(ServerTest, GetStreamed) {
  7623. auto res = cli_.Get("/streamed");
  7624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7625. EXPECT_EQ(StatusCode::OK_200, res->status);
  7626. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7627. EXPECT_EQ(std::string("aaabbb"), res->body);
  7628. }
  7629. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7630. auto res = cli_.Get("/streamed-without-length",
  7631. Headers{make_range_header({{0, -1}})});
  7632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7633. EXPECT_EQ(StatusCode::OK_200, res->status);
  7634. EXPECT_EQ(false, res->has_header("Content-Length"));
  7635. EXPECT_EQ(false, res->has_header("Content-Range"));
  7636. EXPECT_EQ(std::string("abcdefg"), res->body);
  7637. }
  7638. TEST_F(ServerTest, GetStreamedWithRange1) {
  7639. auto res =
  7640. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7642. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7643. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7644. EXPECT_EQ(true, res->has_header("Content-Range"));
  7645. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7646. EXPECT_EQ(std::string("def"), res->body);
  7647. }
  7648. TEST_F(ServerTest, GetStreamedWithRange2) {
  7649. auto res =
  7650. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7652. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7653. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7654. EXPECT_EQ(true, res->has_header("Content-Range"));
  7655. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7656. EXPECT_EQ(std::string("bcdefg"), res->body);
  7657. }
  7658. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7659. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7662. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7663. EXPECT_EQ(true, res->has_header("Content-Range"));
  7664. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7665. EXPECT_EQ(std::string("efg"), res->body);
  7666. }
  7667. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7668. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7669. // the entire representation.
  7670. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7671. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7674. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7675. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7676. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7677. }
  7678. }
  7679. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7680. auto res =
  7681. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7683. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7684. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7685. EXPECT_EQ(false, res->has_header("Content-Range"));
  7686. EXPECT_EQ(0U, res->body.size());
  7687. }
  7688. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7689. // Only a 206 is served as a partial representation. Under any other status
  7690. // `apply_ranges()` reported the full content length, so the body must match
  7691. // that header, and the content provider must never be asked for an offset
  7692. // outside the representation.
  7693. auto check = [&](int status, const char *range) {
  7694. auto path =
  7695. std::string("/streamed-with-range?status=") + std::to_string(status);
  7696. auto ctx = path + " Range: " + range;
  7697. auto res = cli_.Get(path, Headers{{"Range", range}});
  7698. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7699. EXPECT_EQ(status, res->status) << ctx;
  7700. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7701. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7702. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7703. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7704. };
  7705. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7706. check(403, "bytes=3-5");
  7707. // The offset is far past the representation.
  7708. check(403, "bytes=100000-100200");
  7709. // `first_pos` is still -1 here, and the bounds asserts in
  7710. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7711. check(403, "bytes=-3");
  7712. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7713. // multipart branch would have written one that is empty.
  7714. check(403, "bytes=1-2, 4-5");
  7715. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7716. // covers the whole representation.
  7717. check(200, "bytes=3-5");
  7718. check(200, "bytes=1-2, 4-5");
  7719. }
  7720. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7721. auto res =
  7722. cli_.Get("/streamed-with-range",
  7723. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7724. "92233720368547758079223372036854775807"}});
  7725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7726. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7727. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7728. EXPECT_EQ(false, res->has_header("Content-Range"));
  7729. EXPECT_EQ(0U, res->body.size());
  7730. }
  7731. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7732. auto res = cli_.Get(
  7733. "/with-range",
  7734. Headers{{"Range",
  7735. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7736. {"Accept-Encoding", ""}});
  7737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7738. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7739. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7740. EXPECT_EQ(true, res->has_header("Content-Range"));
  7741. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7742. EXPECT_EQ(std::string("abcdefg"), res->body);
  7743. }
  7744. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7745. auto res = cli_.Get("/with-range", Headers{
  7746. {"Range", "bytes=0-"},
  7747. {"Accept-Encoding", ""},
  7748. });
  7749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7750. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7751. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7752. EXPECT_EQ(true, res->has_header("Content-Range"));
  7753. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7754. EXPECT_EQ(std::string("abcdefg"), res->body);
  7755. }
  7756. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7757. auto res = cli_.Get("/streamed-with-range",
  7758. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7761. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7762. EXPECT_EQ(false, res->has_header("Content-Range"));
  7763. EXPECT_EQ(267U, res->body.size());
  7764. // Check that both range contents are present
  7765. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7766. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7767. // Check that Content-Range headers are present for both ranges
  7768. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7769. std::string::npos);
  7770. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7771. std::string::npos);
  7772. }
  7773. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7774. Ranges ranges;
  7775. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7776. ranges.emplace_back(0, -1);
  7777. }
  7778. auto res = cli_.Get("/streamed-with-range?error",
  7779. Headers{{make_range_header(ranges)}});
  7780. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7781. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7782. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7783. EXPECT_EQ(false, res->has_header("Content-Range"));
  7784. EXPECT_EQ(0U, res->body.size());
  7785. }
  7786. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7787. auto res = cli_.Get("/streamed-with-range",
  7788. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7791. EXPECT_EQ(5U, res->body.size());
  7792. // Check that overlapping ranges are coalesced into a single range
  7793. EXPECT_EQ("bcdef", res->body);
  7794. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7795. // Should be single range, not multipart
  7796. EXPECT_TRUE(res->has_header("Content-Range"));
  7797. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7798. }
  7799. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7800. auto res = cli_.Get("/streamed-with-range",
  7801. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7804. EXPECT_EQ(268U, res->body.size());
  7805. // Check that both range contents are present
  7806. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7807. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7808. // Check that Content-Range headers are present for both ranges
  7809. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7810. std::string::npos);
  7811. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7812. std::string::npos);
  7813. }
  7814. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7815. auto res = cli_.Get("/streamed-with-range",
  7816. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7817. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7818. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7819. EXPECT_EQ(269U, res->body.size());
  7820. // Check that both duplicate range contents are present
  7821. size_t first_abc = res->body.find("abc\r\n");
  7822. EXPECT_TRUE(first_abc != std::string::npos);
  7823. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7824. EXPECT_TRUE(second_abc != std::string::npos);
  7825. // Check that Content-Range headers are present for both ranges
  7826. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7827. EXPECT_TRUE(first_range != std::string::npos);
  7828. size_t second_range =
  7829. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7830. EXPECT_TRUE(second_range != std::string::npos);
  7831. }
  7832. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7833. auto res =
  7834. cli_.Get("/streamed-with-range?error",
  7835. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7838. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7839. EXPECT_EQ(false, res->has_header("Content-Range"));
  7840. EXPECT_EQ(0U, res->body.size());
  7841. }
  7842. TEST_F(ServerTest, GetStreamedEndless) {
  7843. uint64_t offset = 0;
  7844. auto res = cli_.Get("/streamed-cancel",
  7845. [&](const char * /*data*/, uint64_t data_length) {
  7846. if (offset < 100) {
  7847. offset += data_length;
  7848. return true;
  7849. }
  7850. return false;
  7851. });
  7852. ASSERT_TRUE(!res);
  7853. EXPECT_EQ(Error::Canceled, res.error());
  7854. }
  7855. TEST_F(ServerTest, ClientStop) {
  7856. std::atomic_size_t count{4};
  7857. std::vector<std::thread> threads;
  7858. for (auto i = count.load(); i != 0; --i) {
  7859. threads.emplace_back([&]() {
  7860. auto res = cli_.Get("/streamed-cancel",
  7861. [&](const char *, uint64_t) { return true; });
  7862. --count;
  7863. ASSERT_TRUE(!res);
  7864. EXPECT_TRUE(res.error() == Error::Canceled ||
  7865. res.error() == Error::Read || res.error() == Error::Write);
  7866. });
  7867. }
  7868. std::this_thread::sleep_for(std::chrono::seconds(2));
  7869. while (count != 0) {
  7870. cli_.stop();
  7871. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7872. }
  7873. for (auto &t : threads) {
  7874. t.join();
  7875. }
  7876. }
  7877. TEST_F(ServerTest, GetWithRange1) {
  7878. auto res = cli_.Get("/with-range", Headers{
  7879. make_range_header({{3, 5}}),
  7880. {"Accept-Encoding", ""},
  7881. });
  7882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7883. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7884. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7885. EXPECT_EQ(true, res->has_header("Content-Range"));
  7886. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7887. EXPECT_EQ(std::string("def"), res->body);
  7888. }
  7889. TEST_F(ServerTest, GetWithRange2) {
  7890. auto res = cli_.Get("/with-range", Headers{
  7891. make_range_header({{1, -1}}),
  7892. {"Accept-Encoding", ""},
  7893. });
  7894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7895. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7896. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7897. EXPECT_EQ(true, res->has_header("Content-Range"));
  7898. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7899. EXPECT_EQ(std::string("bcdefg"), res->body);
  7900. }
  7901. TEST_F(ServerTest, GetWithRange3) {
  7902. auto res = cli_.Get("/with-range", Headers{
  7903. make_range_header({{0, 0}}),
  7904. {"Accept-Encoding", ""},
  7905. });
  7906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7907. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7908. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7909. EXPECT_EQ(true, res->has_header("Content-Range"));
  7910. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7911. EXPECT_EQ(std::string("a"), res->body);
  7912. }
  7913. TEST_F(ServerTest, GetWithRange4) {
  7914. auto res = cli_.Get("/with-range", Headers{
  7915. make_range_header({{-1, 2}}),
  7916. {"Accept-Encoding", ""},
  7917. });
  7918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7919. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7920. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7921. EXPECT_EQ(true, res->has_header("Content-Range"));
  7922. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7923. EXPECT_EQ(std::string("fg"), res->body);
  7924. }
  7925. TEST_F(ServerTest, GetWithRange5) {
  7926. auto res = cli_.Get("/with-range", Headers{
  7927. make_range_header({{0, 5}}),
  7928. {"Accept-Encoding", ""},
  7929. });
  7930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7931. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7932. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7933. EXPECT_EQ(true, res->has_header("Content-Range"));
  7934. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7935. EXPECT_EQ(std::string("abcdef"), res->body);
  7936. }
  7937. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7938. auto res =
  7939. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7942. }
  7943. TEST_F(ServerTest, GetWithRangeMultipart) {
  7944. auto res =
  7945. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7948. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7949. EXPECT_EQ(false, res->has_header("Content-Range"));
  7950. EXPECT_EQ(267U, res->body.size());
  7951. }
  7952. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7953. auto res = cli_.Get("/with-range",
  7954. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7956. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7957. }
  7958. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7959. auto res = cli_.Get("/with-range-customized-response",
  7960. Headers{{make_range_header({{1, 2}})}});
  7961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7962. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7963. EXPECT_EQ(true, res->has_header("Content-Length"));
  7964. EXPECT_EQ(false, res->has_header("Content-Range"));
  7965. EXPECT_EQ(JSON_DATA, res->body);
  7966. }
  7967. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7968. auto res = cli_.Get("/with-range-customized-response",
  7969. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7972. EXPECT_EQ(true, res->has_header("Content-Length"));
  7973. EXPECT_EQ(false, res->has_header("Content-Range"));
  7974. EXPECT_EQ(JSON_DATA, res->body);
  7975. }
  7976. TEST_F(ServerTest, Issue1772) {
  7977. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7979. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7980. }
  7981. TEST_F(ServerTest, Issue609) {
  7982. auto res = cli_.Delete("/issue609");
  7983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7984. EXPECT_EQ(StatusCode::OK_200, res->status);
  7985. EXPECT_EQ(std::string("ok"), res->body);
  7986. }
  7987. TEST_F(ServerTest, GetStreamedChunked) {
  7988. auto res = cli_.Get("/streamed-chunked");
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(StatusCode::OK_200, res->status);
  7991. EXPECT_EQ(std::string("123456789"), res->body);
  7992. }
  7993. TEST_F(ServerTest, GetStreamedChunked2) {
  7994. auto res = cli_.Get("/streamed-chunked2");
  7995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7996. EXPECT_EQ(StatusCode::OK_200, res->status);
  7997. EXPECT_EQ(std::string("123456789"), res->body);
  7998. }
  7999. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  8000. auto res = cli_.Get("/streamed-chunked-with-trailer");
  8001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8002. EXPECT_EQ(StatusCode::OK_200, res->status);
  8003. EXPECT_EQ(std::string("123456789"), res->body);
  8004. EXPECT_TRUE(res->has_header("Trailer"));
  8005. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8006. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8007. // Trailers are now stored separately from headers (security fix)
  8008. EXPECT_EQ(2U, res->trailers.size());
  8009. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8010. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8011. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8012. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8013. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8014. // Verify trailers are NOT in headers (security verification)
  8015. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8016. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8017. }
  8018. TEST_F(ServerTest, LargeChunkedPost) {
  8019. Request req;
  8020. req.method = "POST";
  8021. req.path = "/large-chunked";
  8022. std::string host_and_port;
  8023. host_and_port += HOST;
  8024. host_and_port += ":";
  8025. host_and_port += std::to_string(PORT);
  8026. req.headers.emplace("Host", host_and_port.c_str());
  8027. req.headers.emplace("Accept", "*/*");
  8028. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8029. req.headers.emplace("Content-Type", "text/plain");
  8030. req.headers.emplace("Content-Length", "0");
  8031. req.headers.emplace("Transfer-Encoding", "chunked");
  8032. std::string long_string(30 * 1024u, 'a');
  8033. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8034. // Attempt to make a large enough post to exceed OS buffers, to test that
  8035. // the server handles short reads if the full chunk data isn't available.
  8036. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8037. auto res = std::make_shared<Response>();
  8038. auto error = Error::Success;
  8039. auto ret = cli_.send(req, *res, error);
  8040. ASSERT_TRUE(ret);
  8041. EXPECT_EQ(StatusCode::OK_200, res->status);
  8042. }
  8043. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8044. auto res = cli_.Get("/remote_addr");
  8045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8046. EXPECT_EQ(StatusCode::OK_200, res->status);
  8047. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8048. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8049. }
  8050. TEST_F(ServerTest, GetMethodLocalAddr) {
  8051. auto res = cli_.Get("/local_addr");
  8052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8053. EXPECT_EQ(StatusCode::OK_200, res->status);
  8054. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8055. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8056. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8057. }
  8058. TEST_F(ServerTest, HTTPResponseSplitting) {
  8059. auto res = cli_.Get("/http_response_splitting");
  8060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8061. EXPECT_EQ(StatusCode::OK_200, res->status);
  8062. }
  8063. TEST_F(ServerTest, SlowRequest) {
  8064. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8065. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8066. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8067. }
  8068. #if 0
  8069. TEST_F(ServerTest, SlowPost) {
  8070. char buffer[64 * 1024];
  8071. memset(buffer, 0x42, sizeof(buffer));
  8072. auto res = cli_.Post(
  8073. "/slowpost", 64 * 1024 * 1024,
  8074. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8075. auto ret = sink.write(buffer, sizeof(buffer));
  8076. EXPECT_TRUE(ret);
  8077. return true;
  8078. },
  8079. "text/plain");
  8080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. TEST_F(ServerTest, SlowPostFail) {
  8084. char buffer[64 * 1024];
  8085. memset(buffer, 0x42, sizeof(buffer));
  8086. cli_.set_write_timeout(std::chrono::seconds(0));
  8087. auto res = cli_.Post(
  8088. "/slowpost", 64 * 1024 * 1024,
  8089. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8090. sink.write(buffer, sizeof(buffer));
  8091. return true;
  8092. },
  8093. "text/plain");
  8094. ASSERT_TRUE(!res);
  8095. EXPECT_EQ(Error::Write, res.error());
  8096. }
  8097. #endif
  8098. TEST_F(ServerTest, Put) {
  8099. auto res = cli_.Put("/put", "PUT", "text/plain");
  8100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8101. EXPECT_EQ(StatusCode::OK_200, res->status);
  8102. EXPECT_EQ("PUT", res->body);
  8103. }
  8104. TEST_F(ServerTest, PutWithContentProvider) {
  8105. auto res = cli_.Put(
  8106. "/put", 3,
  8107. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8108. sink.os << "PUT";
  8109. return true;
  8110. },
  8111. "text/plain");
  8112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8113. EXPECT_EQ(StatusCode::OK_200, res->status);
  8114. EXPECT_EQ("PUT", res->body);
  8115. }
  8116. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8117. auto res = cli_.Post(
  8118. "/post", 42,
  8119. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8120. return false;
  8121. },
  8122. "text/plain");
  8123. ASSERT_TRUE(!res);
  8124. EXPECT_EQ(Error::Canceled, res.error());
  8125. }
  8126. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8127. auto res = cli_.Put(
  8128. "/put",
  8129. [](size_t /*offset*/, DataSink &sink) {
  8130. sink.os << "PUT";
  8131. sink.done();
  8132. return true;
  8133. },
  8134. "text/plain");
  8135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8136. EXPECT_EQ(StatusCode::OK_200, res->status);
  8137. EXPECT_EQ("PUT", res->body);
  8138. }
  8139. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8140. auto res = cli_.Post(
  8141. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8142. "text/plain");
  8143. ASSERT_TRUE(!res);
  8144. EXPECT_EQ(Error::Canceled, res.error());
  8145. }
  8146. TEST_F(ServerTest, PostLoopBack) {
  8147. std::string body;
  8148. auto res = cli_.Post(
  8149. "/post-loopback", 9,
  8150. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8151. EXPECT_EQ(9u, length);
  8152. sink.write("123", 3);
  8153. sink.write("456", 3);
  8154. sink.write("789", 3);
  8155. return true;
  8156. },
  8157. "text/plain",
  8158. [&body](const char *data, size_t data_length) {
  8159. body.append(data, data_length);
  8160. return true;
  8161. });
  8162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8163. EXPECT_EQ(StatusCode::OK_200, res->status);
  8164. EXPECT_EQ("123456789", body);
  8165. }
  8166. TEST_F(ServerTest, PutLoopBack) {
  8167. std::string body;
  8168. auto res = cli_.Put(
  8169. "/put-loopback", 9,
  8170. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8171. EXPECT_EQ(9u, length);
  8172. sink.write("123", 3);
  8173. sink.write("456", 3);
  8174. sink.write("789", 3);
  8175. return true;
  8176. },
  8177. "text/plain",
  8178. [&body](const char *data, size_t data_length) {
  8179. body.append(data, data_length);
  8180. return true;
  8181. });
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("123456789", body);
  8185. }
  8186. TEST_F(ServerTest, PatchLoopBack) {
  8187. std::string body;
  8188. auto res = cli_.Patch(
  8189. "/patch-loopback", 9,
  8190. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8191. EXPECT_EQ(9u, length);
  8192. sink.write("123", 3);
  8193. sink.write("456", 3);
  8194. sink.write("789", 3);
  8195. return true;
  8196. },
  8197. "text/plain",
  8198. [&body](const char *data, size_t data_length) {
  8199. body.append(data, data_length);
  8200. return true;
  8201. });
  8202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8203. EXPECT_EQ(StatusCode::OK_200, res->status);
  8204. EXPECT_EQ("123456789", body);
  8205. }
  8206. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8207. std::string body;
  8208. auto res = cli_.Post(
  8209. "/post-loopback",
  8210. [](size_t /*offset*/, DataSink &sink) {
  8211. sink.write("123", 3);
  8212. sink.write("456", 3);
  8213. sink.write("789", 3);
  8214. sink.done();
  8215. return true;
  8216. },
  8217. "text/plain",
  8218. [&body](const char *data, size_t data_length) {
  8219. body.append(data, data_length);
  8220. return true;
  8221. });
  8222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8223. EXPECT_EQ(StatusCode::OK_200, res->status);
  8224. EXPECT_EQ("123456789", body);
  8225. }
  8226. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8227. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8228. cli_.set_compress(true);
  8229. auto res = cli_.Put(
  8230. "/put", 3,
  8231. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8232. sink.os << "PUT";
  8233. return true;
  8234. },
  8235. "text/plain");
  8236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8237. EXPECT_EQ(StatusCode::OK_200, res->status);
  8238. EXPECT_EQ("PUT", res->body);
  8239. }
  8240. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8241. cli_.set_compress(true);
  8242. auto res = cli_.Post(
  8243. "/post", 42,
  8244. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8245. return false;
  8246. },
  8247. "text/plain");
  8248. ASSERT_TRUE(!res);
  8249. EXPECT_EQ(Error::Canceled, res.error());
  8250. }
  8251. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8252. cli_.set_compress(true);
  8253. auto res = cli_.Put(
  8254. "/put",
  8255. [](size_t /*offset*/, DataSink &sink) {
  8256. sink.os << "PUT";
  8257. sink.done();
  8258. return true;
  8259. },
  8260. "text/plain");
  8261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8262. EXPECT_EQ(StatusCode::OK_200, res->status);
  8263. EXPECT_EQ("PUT", res->body);
  8264. }
  8265. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8266. cli_.set_compress(true);
  8267. auto res = cli_.Post(
  8268. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8269. "text/plain");
  8270. ASSERT_TRUE(!res);
  8271. EXPECT_EQ(Error::Canceled, res.error());
  8272. }
  8273. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8274. cli_.set_compress(true);
  8275. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::OK_200, res->status);
  8278. EXPECT_EQ(LARGE_DATA, res->body);
  8279. }
  8280. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8281. #ifdef CPPHTTPLIB_SSL_ENABLED
  8282. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8283. Client cli(s.c_str());
  8284. cli.enable_server_certificate_verification(false);
  8285. #else
  8286. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8287. Client cli(s.c_str());
  8288. #endif
  8289. cli.set_compress(true);
  8290. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8292. EXPECT_EQ(StatusCode::OK_200, res->status);
  8293. EXPECT_EQ(LARGE_DATA, res->body);
  8294. // The compressed size should be less than a 10th of the original. May vary
  8295. // depending on the zlib library.
  8296. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8297. static_cast<uint64_t>(10 * 1024 * 1024));
  8298. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8299. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8300. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8301. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8302. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8303. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8304. #endif
  8305. }
  8306. TEST_F(ServerTest, PutContentWithDeflate) {
  8307. cli_.set_compress(false);
  8308. Headers headers;
  8309. headers.emplace("Content-Encoding", "deflate");
  8310. // PUT in deflate format:
  8311. auto res = cli_.Put("/put", headers,
  8312. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(StatusCode::OK_200, res->status);
  8315. EXPECT_EQ("PUT", res->body);
  8316. }
  8317. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8318. Headers headers;
  8319. headers.emplace("Accept-Encoding", "gzip, deflate");
  8320. auto res = cli_.Get("/streamed-chunked", headers);
  8321. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8322. EXPECT_EQ(StatusCode::OK_200, res->status);
  8323. EXPECT_EQ(std::string("123456789"), res->body);
  8324. }
  8325. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8326. Headers headers;
  8327. headers.emplace("Accept-Encoding", "gzip, deflate");
  8328. auto res = cli_.Get("/streamed-chunked2", headers);
  8329. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8330. EXPECT_EQ(StatusCode::OK_200, res->status);
  8331. EXPECT_EQ(std::string("123456789"), res->body);
  8332. }
  8333. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8334. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8336. EXPECT_EQ(StatusCode::OK_200, res->status);
  8337. }
  8338. TEST(GzipDecompressor, ChunkedDecompression) {
  8339. std::string data;
  8340. for (size_t i = 0; i < 32 * 1024; ++i) {
  8341. data.push_back(static_cast<char>('a' + i % 26));
  8342. }
  8343. std::string compressed_data;
  8344. {
  8345. httplib::detail::gzip_compressor compressor;
  8346. bool result = compressor.compress(
  8347. data.data(), data.size(),
  8348. /*last=*/true,
  8349. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8350. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8351. compressed_data_size);
  8352. return true;
  8353. });
  8354. ASSERT_TRUE(result);
  8355. }
  8356. std::string decompressed_data;
  8357. {
  8358. httplib::detail::gzip_decompressor decompressor;
  8359. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8360. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8361. size_t chunk_size = 130;
  8362. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8363. chunk_begin += chunk_size) {
  8364. size_t current_chunk_size =
  8365. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8366. bool result = decompressor.decompress(
  8367. compressed_data.data() + chunk_begin, current_chunk_size,
  8368. [&](const char *decompressed_data_chunk,
  8369. size_t decompressed_data_chunk_size) {
  8370. decompressed_data.insert(decompressed_data.size(),
  8371. decompressed_data_chunk,
  8372. decompressed_data_chunk_size);
  8373. return true;
  8374. });
  8375. ASSERT_TRUE(result);
  8376. }
  8377. }
  8378. ASSERT_EQ(data, decompressed_data);
  8379. }
  8380. TEST(GzipDecompressor, DeflateDecompression) {
  8381. std::string original_text = "Raw deflate without gzip";
  8382. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8383. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8384. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8385. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8386. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8387. std::string decompressed_data;
  8388. {
  8389. httplib::detail::gzip_decompressor decompressor;
  8390. bool result = decompressor.decompress(
  8391. compressed_data.data(), compressed_data.size(),
  8392. [&](const char *decompressed_data_chunk,
  8393. size_t decompressed_data_chunk_size) {
  8394. decompressed_data.insert(decompressed_data.size(),
  8395. decompressed_data_chunk,
  8396. decompressed_data_chunk_size);
  8397. return true;
  8398. });
  8399. ASSERT_TRUE(result);
  8400. }
  8401. ASSERT_EQ(original_text, decompressed_data);
  8402. }
  8403. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8404. std::string original_text = "Raw deflate without gzip";
  8405. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8406. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8407. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8408. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8409. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8410. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8411. std::string decompressed_data;
  8412. {
  8413. httplib::detail::gzip_decompressor decompressor;
  8414. bool result = decompressor.decompress(
  8415. compressed_data.data(), compressed_data.size(),
  8416. [&](const char *decompressed_data_chunk,
  8417. size_t decompressed_data_chunk_size) {
  8418. decompressed_data.insert(decompressed_data.size(),
  8419. decompressed_data_chunk,
  8420. decompressed_data_chunk_size);
  8421. return true;
  8422. });
  8423. ASSERT_TRUE(result);
  8424. }
  8425. ASSERT_EQ(original_text, decompressed_data);
  8426. }
  8427. #endif
  8428. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8429. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8430. Headers headers;
  8431. headers.emplace("Accept-Encoding", "br");
  8432. auto res = cli_.Get("/streamed-chunked", headers);
  8433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8434. EXPECT_EQ(StatusCode::OK_200, res->status);
  8435. EXPECT_EQ(std::string("123456789"), res->body);
  8436. }
  8437. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8438. Headers headers;
  8439. headers.emplace("Accept-Encoding", "br");
  8440. auto res = cli_.Get("/streamed-chunked2", headers);
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ(StatusCode::OK_200, res->status);
  8443. EXPECT_EQ(std::string("123456789"), res->body);
  8444. }
  8445. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8446. cli_.set_compress(true);
  8447. auto res = cli_.Put(
  8448. "/put", 3,
  8449. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8450. sink.os << "PUT";
  8451. return true;
  8452. },
  8453. "text/plain");
  8454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8455. EXPECT_EQ(StatusCode::OK_200, res->status);
  8456. EXPECT_EQ("PUT", res->body);
  8457. }
  8458. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8459. cli_.set_compress(true);
  8460. auto res = cli_.Put(
  8461. "/put",
  8462. [](size_t /*offset*/, DataSink &sink) {
  8463. sink.os << "PUT";
  8464. sink.done();
  8465. return true;
  8466. },
  8467. "text/plain");
  8468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8469. EXPECT_EQ(StatusCode::OK_200, res->status);
  8470. EXPECT_EQ("PUT", res->body);
  8471. }
  8472. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8473. cli_.set_compress(true);
  8474. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ(StatusCode::OK_200, res->status);
  8477. EXPECT_EQ(LARGE_DATA, res->body);
  8478. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8479. }
  8480. #endif
  8481. TEST_F(ServerTest, Patch) {
  8482. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8484. EXPECT_EQ(StatusCode::OK_200, res->status);
  8485. EXPECT_EQ("PATCH", res->body);
  8486. }
  8487. TEST_F(ServerTest, Delete) {
  8488. auto res = cli_.Delete("/delete");
  8489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8490. EXPECT_EQ(StatusCode::OK_200, res->status);
  8491. EXPECT_EQ("DELETE", res->body);
  8492. }
  8493. TEST_F(ServerTest, DeleteContentReceiver) {
  8494. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8496. EXPECT_EQ(StatusCode::OK_200, res->status);
  8497. EXPECT_EQ("content", res->body);
  8498. }
  8499. TEST_F(ServerTest, Options) {
  8500. auto res = cli_.Options("*");
  8501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8502. EXPECT_EQ(StatusCode::OK_200, res->status);
  8503. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8504. EXPECT_TRUE(res->body.empty());
  8505. }
  8506. TEST_F(ServerTest, URL) {
  8507. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8509. EXPECT_EQ(StatusCode::OK_200, res->status);
  8510. }
  8511. TEST_F(ServerTest, ArrayParam) {
  8512. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8514. EXPECT_EQ(StatusCode::OK_200, res->status);
  8515. }
  8516. TEST_F(ServerTest, ArrayParamValues) {
  8517. auto res =
  8518. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8520. EXPECT_EQ(StatusCode::OK_200, res->status);
  8521. }
  8522. TEST_F(ServerTest, NoMultipleHeaders) {
  8523. Headers headers = {{"Content-Length", "5"}};
  8524. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8525. "text/plain");
  8526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8527. EXPECT_EQ(StatusCode::OK_200, res->status);
  8528. }
  8529. TEST_F(ServerTest, PostContentReceiver) {
  8530. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8532. ASSERT_EQ(StatusCode::OK_200, res->status);
  8533. ASSERT_EQ("content", res->body);
  8534. }
  8535. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8536. UploadFormDataItems items = {
  8537. {"text1", "text default", "", ""},
  8538. {"text2", "aωb", "", ""},
  8539. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8540. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8541. {"file3", "", "", "application/octet-stream"},
  8542. };
  8543. auto res = cli_.Post("/content_receiver", items);
  8544. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8545. EXPECT_EQ(StatusCode::OK_200, res->status);
  8546. }
  8547. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8548. UploadFormDataItems items = {
  8549. {"text1", "text default", "", ""},
  8550. {"text2", "aωb", "", ""},
  8551. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8552. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8553. {"file3", "", "", "application/octet-stream"},
  8554. };
  8555. auto boundary = std::string("+++++");
  8556. std::string body;
  8557. for (const auto &item : items) {
  8558. body += "--" + boundary + "\r\n";
  8559. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8560. if (!item.filename.empty()) {
  8561. body += "; filename=\"" + item.filename + "\"";
  8562. }
  8563. body += "\r\n";
  8564. if (!item.content_type.empty()) {
  8565. body += "Content-Type: " + item.content_type + "\r\n";
  8566. }
  8567. body += "\r\n";
  8568. body += item.content + "\r\n";
  8569. }
  8570. body += "--" + boundary + "--\r\n";
  8571. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8572. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8574. EXPECT_EQ(StatusCode::OK_200, res->status);
  8575. }
  8576. TEST(MultipartFormDataTest, FieldEscaping) {
  8577. Server svr;
  8578. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8579. const ContentReader &content_reader) {
  8580. ASSERT_TRUE(req.is_multipart_form_data());
  8581. std::vector<FormData> received;
  8582. content_reader(
  8583. [&](const FormData &file) {
  8584. received.push_back(file);
  8585. return true;
  8586. },
  8587. [&](const char *data, size_t data_length) {
  8588. received.back().content.append(data, data_length);
  8589. return true;
  8590. });
  8591. // '"', CR and LF in names and filenames are escaped following the
  8592. // WHATWG HTML standard, so each part still parses as a single part
  8593. // with no injected headers. Content types get CR/LF escaped too,
  8594. // while '"' (legal there, e.g. quoted charset) is preserved.
  8595. ASSERT_EQ(4U, received.size());
  8596. EXPECT_EQ("na%22me", received[0].name);
  8597. EXPECT_EQ("quoted name", received[0].content);
  8598. EXPECT_EQ("file", received[1].name);
  8599. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8600. received[1].filename);
  8601. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8602. EXPECT_EQ("injected", received[1].content);
  8603. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8604. EXPECT_EQ("my%22file.txt", received[2].filename);
  8605. EXPECT_EQ("cr lf name", received[2].content);
  8606. EXPECT_EQ("typed", received[3].name);
  8607. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8608. received[3].content_type);
  8609. EXPECT_EQ("typed content", received[3].content);
  8610. });
  8611. auto port = svr.bind_to_any_port("localhost");
  8612. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8613. auto se = detail::scope_exit([&] {
  8614. svr.stop();
  8615. t.join();
  8616. ASSERT_FALSE(svr.is_running());
  8617. });
  8618. svr.wait_until_ready();
  8619. Client cli("localhost", port);
  8620. UploadFormDataItems items = {
  8621. {"na\"me", "quoted name", "", ""},
  8622. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8623. "application/octet-stream"},
  8624. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8625. {"typed", "typed content", "",
  8626. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8627. };
  8628. auto res = cli.Post("/post", items);
  8629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8630. EXPECT_EQ(StatusCode::OK_200, res->status);
  8631. }
  8632. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8633. const UploadFormDataItems items = {
  8634. {"name1", "Content 1", "", ""},
  8635. {"name2", "Content 2", "file2.txt", "text/plain"},
  8636. };
  8637. Server svr;
  8638. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8639. const ContentReader &content_reader) {
  8640. ASSERT_TRUE(req.is_multipart_form_data());
  8641. std::vector<FormData> received;
  8642. content_reader(
  8643. [&](const FormData &file) {
  8644. received.push_back(file);
  8645. return true;
  8646. },
  8647. [&](const char *data, size_t data_length) {
  8648. received.back().content.append(data, data_length);
  8649. return true;
  8650. });
  8651. ASSERT_EQ(2U, received.size());
  8652. EXPECT_EQ("name1", received[0].name);
  8653. EXPECT_EQ("Content 1", received[0].content);
  8654. EXPECT_EQ("name2", received[1].name);
  8655. EXPECT_EQ("Content 2", received[1].content);
  8656. EXPECT_EQ("file2.txt", received[1].filename);
  8657. EXPECT_EQ("text/plain", received[1].content_type);
  8658. });
  8659. auto port = svr.bind_to_any_port("localhost");
  8660. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8661. auto se = detail::scope_exit([&] {
  8662. svr.stop();
  8663. t.join();
  8664. ASSERT_FALSE(svr.is_running());
  8665. });
  8666. svr.wait_until_ready();
  8667. Client cli("localhost", port);
  8668. // Whole-body serialization with a generated boundary
  8669. {
  8670. MultipartFormDataWriter writer;
  8671. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8672. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8673. writer.content_type());
  8674. auto body = writer.serialize(items);
  8675. EXPECT_EQ(body.size(), writer.content_length(items));
  8676. auto res = cli.Post("/post", body, writer.content_type());
  8677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8678. EXPECT_EQ(StatusCode::OK_200, res->status);
  8679. }
  8680. // Per-part framing with a custom boundary via a content provider
  8681. {
  8682. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8683. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8684. MultipartFormDataWriter writer("custom-boundary_123");
  8685. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8686. std::string body;
  8687. for (const auto &item : items) {
  8688. body += writer.item_begin(item);
  8689. body += item.content;
  8690. body += MultipartFormDataWriter::item_end();
  8691. }
  8692. body += writer.finish();
  8693. EXPECT_EQ(body.size(), writer.content_length(items));
  8694. auto res = cli.Post(
  8695. "/post", body.size(),
  8696. [&](size_t offset, size_t length, DataSink &sink) {
  8697. sink.write(body.data() + offset, length);
  8698. return true;
  8699. },
  8700. writer.content_type());
  8701. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8702. EXPECT_EQ(StatusCode::OK_200, res->status);
  8703. }
  8704. }
  8705. TEST_F(ServerTest, PostContentReceiverGzip) {
  8706. cli_.set_compress(true);
  8707. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8709. ASSERT_EQ(StatusCode::OK_200, res->status);
  8710. ASSERT_EQ("content", res->body);
  8711. }
  8712. TEST_F(ServerTest, PutContentReceiver) {
  8713. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8715. ASSERT_EQ(StatusCode::OK_200, res->status);
  8716. ASSERT_EQ("content", res->body);
  8717. }
  8718. TEST_F(ServerTest, PatchContentReceiver) {
  8719. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8720. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8721. ASSERT_EQ(StatusCode::OK_200, res->status);
  8722. ASSERT_EQ("content", res->body);
  8723. }
  8724. template <typename ClientType>
  8725. void TestWithHeadersAndContentReceiver(
  8726. ClientType &cli,
  8727. std::function<Result(ClientType &, const std::string &, const Headers &,
  8728. const std::string &, const std::string &,
  8729. ContentReceiver, DownloadProgress)>
  8730. request_func) {
  8731. Headers headers;
  8732. headers.emplace("X-Custom-Header", "test-value");
  8733. std::string received_body;
  8734. auto res = request_func(
  8735. cli, "/content_receiver", headers, "content", "application/json",
  8736. [&](const char *data, size_t data_length) {
  8737. received_body.append(data, data_length);
  8738. return true;
  8739. },
  8740. nullptr);
  8741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8742. EXPECT_EQ(StatusCode::OK_200, res->status);
  8743. EXPECT_EQ("content", received_body);
  8744. }
  8745. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8746. #ifdef CPPHTTPLIB_SSL_ENABLED
  8747. using ClientT = SSLClient;
  8748. #else
  8749. using ClientT = Client;
  8750. #endif
  8751. TestWithHeadersAndContentReceiver<ClientT>(
  8752. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8753. const std::string &body, const std::string &content_type,
  8754. ContentReceiver receiver, DownloadProgress progress) {
  8755. return cli.Post(path, headers, body, content_type, receiver, progress);
  8756. });
  8757. }
  8758. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8759. #ifdef CPPHTTPLIB_SSL_ENABLED
  8760. using ClientT = SSLClient;
  8761. #else
  8762. using ClientT = Client;
  8763. #endif
  8764. TestWithHeadersAndContentReceiver<ClientT>(
  8765. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8766. const std::string &body, const std::string &content_type,
  8767. ContentReceiver receiver, DownloadProgress progress) {
  8768. return cli.Put(path, headers, body, content_type, receiver, progress);
  8769. });
  8770. }
  8771. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8772. #ifdef CPPHTTPLIB_SSL_ENABLED
  8773. using ClientT = SSLClient;
  8774. #else
  8775. using ClientT = Client;
  8776. #endif
  8777. TestWithHeadersAndContentReceiver<ClientT>(
  8778. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8779. const std::string &body, const std::string &content_type,
  8780. ContentReceiver receiver, DownloadProgress progress) {
  8781. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8782. });
  8783. }
  8784. template <typename ClientType>
  8785. void TestWithHeadersAndContentReceiverWithProgress(
  8786. ClientType &cli,
  8787. std::function<Result(ClientType &, const std::string &, const Headers &,
  8788. const std::string &, const std::string &,
  8789. ContentReceiver, DownloadProgress)>
  8790. request_func) {
  8791. Headers headers;
  8792. headers.emplace("X-Test-Header", "progress-test");
  8793. std::string received_body;
  8794. auto progress_called = false;
  8795. auto res = request_func(
  8796. cli, "/content_receiver", headers, "content", "text/plain",
  8797. [&](const char *data, size_t data_length) {
  8798. received_body.append(data, data_length);
  8799. return true;
  8800. },
  8801. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8802. progress_called = true;
  8803. return true;
  8804. });
  8805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8806. EXPECT_EQ(StatusCode::OK_200, res->status);
  8807. EXPECT_EQ("content", received_body);
  8808. EXPECT_TRUE(progress_called);
  8809. }
  8810. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8811. #ifdef CPPHTTPLIB_SSL_ENABLED
  8812. using ClientT = SSLClient;
  8813. #else
  8814. using ClientT = Client;
  8815. #endif
  8816. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8817. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8818. const std::string &body, const std::string &content_type,
  8819. ContentReceiver receiver, DownloadProgress progress) {
  8820. return cli.Post(path, headers, body, content_type, receiver, progress);
  8821. });
  8822. }
  8823. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8824. #ifdef CPPHTTPLIB_SSL_ENABLED
  8825. using ClientT = SSLClient;
  8826. #else
  8827. using ClientT = Client;
  8828. #endif
  8829. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8830. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8831. const std::string &body, const std::string &content_type,
  8832. ContentReceiver receiver, DownloadProgress progress) {
  8833. return cli.Put(path, headers, body, content_type, receiver, progress);
  8834. });
  8835. }
  8836. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8837. #ifdef CPPHTTPLIB_SSL_ENABLED
  8838. using ClientT = SSLClient;
  8839. #else
  8840. using ClientT = Client;
  8841. #endif
  8842. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8843. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8844. const std::string &body, const std::string &content_type,
  8845. ContentReceiver receiver, DownloadProgress progress) {
  8846. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8847. });
  8848. }
  8849. template <typename ClientType>
  8850. void TestWithHeadersAndContentReceiverError(
  8851. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8852. const Headers &, const std::string &,
  8853. const std::string &, ContentReceiver)>
  8854. request_func) {
  8855. Headers headers;
  8856. headers.emplace("X-Error-Test", "true");
  8857. std::string received_body;
  8858. auto receiver_failed = false;
  8859. auto res =
  8860. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8861. [&](const char *data, size_t data_length) {
  8862. received_body.append(data, data_length);
  8863. receiver_failed = true;
  8864. return false;
  8865. });
  8866. ASSERT_FALSE(res);
  8867. EXPECT_TRUE(receiver_failed);
  8868. }
  8869. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8870. #ifdef CPPHTTPLIB_SSL_ENABLED
  8871. using ClientT = SSLClient;
  8872. #else
  8873. using ClientT = Client;
  8874. #endif
  8875. TestWithHeadersAndContentReceiverError<ClientT>(
  8876. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8877. const std::string &body, const std::string &content_type,
  8878. ContentReceiver receiver) {
  8879. return cli.Post(path, headers, body, content_type, receiver);
  8880. });
  8881. }
  8882. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8883. #ifdef CPPHTTPLIB_SSL_ENABLED
  8884. using ClientT = SSLClient;
  8885. #else
  8886. using ClientT = Client;
  8887. #endif
  8888. TestWithHeadersAndContentReceiverError<ClientT>(
  8889. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8890. const std::string &body, const std::string &content_type,
  8891. ContentReceiver receiver) {
  8892. return cli.Put(path, headers, body, content_type, receiver);
  8893. });
  8894. }
  8895. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8896. #ifdef CPPHTTPLIB_SSL_ENABLED
  8897. using ClientT = SSLClient;
  8898. #else
  8899. using ClientT = Client;
  8900. #endif
  8901. TestWithHeadersAndContentReceiverError<ClientT>(
  8902. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8903. const std::string &body, const std::string &content_type,
  8904. ContentReceiver receiver) {
  8905. return cli.Patch(path, headers, body, content_type, receiver);
  8906. });
  8907. }
  8908. TEST_F(ServerTest, PostQueryStringAndBody) {
  8909. auto res =
  8910. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8912. ASSERT_EQ(StatusCode::OK_200, res->status);
  8913. }
  8914. TEST_F(ServerTest, HTTP2Magic) {
  8915. Request req;
  8916. req.method = "PRI";
  8917. req.path = "*";
  8918. req.body = "SM";
  8919. auto res = std::make_shared<Response>();
  8920. auto error = Error::Success;
  8921. auto ret = cli_.send(req, *res, error);
  8922. ASSERT_TRUE(ret);
  8923. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8924. }
  8925. TEST_F(ServerTest, KeepAlive) {
  8926. auto res = cli_.Get("/hi");
  8927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8928. EXPECT_EQ(StatusCode::OK_200, res->status);
  8929. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8930. EXPECT_EQ("Hello World!", res->body);
  8931. res = cli_.Get("/hi");
  8932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8933. EXPECT_EQ(StatusCode::OK_200, res->status);
  8934. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8935. EXPECT_EQ("Hello World!", res->body);
  8936. res = cli_.Get("/hi");
  8937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8938. EXPECT_EQ(StatusCode::OK_200, res->status);
  8939. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8940. EXPECT_EQ("Hello World!", res->body);
  8941. res = cli_.Get("/not-exist");
  8942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8943. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8944. res = cli_.Post("/empty", "", "text/plain");
  8945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8946. EXPECT_EQ(StatusCode::OK_200, res->status);
  8947. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8948. EXPECT_EQ("empty", res->body);
  8949. EXPECT_EQ("close", res->get_header_value("Connection"));
  8950. res = cli_.Post(
  8951. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8952. "text/plain");
  8953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8954. EXPECT_EQ(StatusCode::OK_200, res->status);
  8955. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8956. EXPECT_EQ("empty", res->body);
  8957. cli_.set_keep_alive(false);
  8958. res = cli_.Get("/last-request");
  8959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8960. EXPECT_EQ(StatusCode::OK_200, res->status);
  8961. EXPECT_EQ("close", res->get_header_value("Connection"));
  8962. }
  8963. TEST_F(ServerTest, TooManyRedirect) {
  8964. cli_.set_follow_location(true);
  8965. auto res = cli_.Get("/redirect/0");
  8966. ASSERT_TRUE(!res);
  8967. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8968. }
  8969. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8970. Request req;
  8971. req.method = "FOOBAR";
  8972. req.path = "/hi";
  8973. cli_.set_keep_alive(true);
  8974. auto res = cli_.send(req);
  8975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8976. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8977. EXPECT_EQ("close", res->get_header_value("Connection"));
  8978. EXPECT_FALSE(cli_.is_socket_open());
  8979. }
  8980. TEST_F(ServerTest, CustomRouteReadsBody) {
  8981. const std::string xml =
  8982. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8983. Request req;
  8984. req.method = "PROPFIND";
  8985. req.path = "/dav/dir";
  8986. req.set_header("Depth", "1");
  8987. req.body = xml;
  8988. auto res = cli_.send(req);
  8989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8990. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8991. EXPECT_EQ(xml, res->body);
  8992. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8993. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8994. }
  8995. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8996. Request req;
  8997. req.method = "PROPFIND";
  8998. req.path = "/dav/42";
  8999. auto res = cli_.send(req);
  9000. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9001. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9002. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9003. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9004. }
  9005. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9006. Request req;
  9007. req.method = "PROPFIND";
  9008. req.path = "/dav-re/123";
  9009. auto res = cli_.send(req);
  9010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9011. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9012. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9013. }
  9014. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9015. Request req;
  9016. req.method = "MKCOL";
  9017. req.path = "/dav-mkcol";
  9018. auto res = cli_.send(req);
  9019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9020. EXPECT_EQ(StatusCode::Created_201, res->status);
  9021. }
  9022. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9023. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9024. Request req;
  9025. req.method = "REPORT";
  9026. req.path = "/dav-report";
  9027. req.body = xml;
  9028. auto res = cli_.send(req);
  9029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9030. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9031. EXPECT_EQ(xml, res->body);
  9032. }
  9033. // A content reader route must fire even when the request carries no body,
  9034. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9035. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9036. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9037. Request req;
  9038. req.method = "REPORT";
  9039. req.path = "/dav-report";
  9040. auto res = cli_.send(req);
  9041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9042. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9043. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9044. }
  9045. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9046. Request req;
  9047. req.method = "PROPFIND";
  9048. req.path = "/not-dav";
  9049. auto res = cli_.send(req);
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9052. }
  9053. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9054. Request req;
  9055. req.method = "UNLOCK";
  9056. req.path = "/dav/dir";
  9057. cli_.set_keep_alive(true);
  9058. auto res = cli_.send(req);
  9059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9060. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9061. EXPECT_EQ("close", res->get_header_value("Connection"));
  9062. EXPECT_FALSE(cli_.is_socket_open());
  9063. }
  9064. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9065. // The mount point serves this path, but only for GET and HEAD.
  9066. auto get_res = cli_.Get("/dir/index.html");
  9067. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9068. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9069. Request req;
  9070. req.method = "PROPFIND";
  9071. req.path = "/dir/index.html";
  9072. auto res = cli_.send(req);
  9073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9074. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9075. }
  9076. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9077. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9078. cli_.set_keep_alive(true);
  9079. for (auto i = 0; i < 2; i++) {
  9080. Request req;
  9081. req.method = "PROPFIND";
  9082. req.path = "/dav/dir";
  9083. req.body = xml;
  9084. auto res = cli_.send(req);
  9085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9086. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9087. EXPECT_EQ(xml, res->body);
  9088. EXPECT_TRUE(cli_.is_socket_open());
  9089. }
  9090. // A built-in method must still be served on the same connection.
  9091. cli_.set_keep_alive(false);
  9092. auto res = cli_.Get("/hi");
  9093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9094. EXPECT_EQ(StatusCode::OK_200, res->status);
  9095. EXPECT_EQ("close", res->get_header_value("Connection"));
  9096. }
  9097. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9098. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9099. Request req;
  9100. req.method = "PROPFIND";
  9101. req.path = "/dav/dir";
  9102. req.set_header("Expect", "100-continue");
  9103. req.body = xml;
  9104. auto res = cli_.send(req);
  9105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9106. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9107. EXPECT_EQ(xml, res->body);
  9108. }
  9109. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9110. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9111. TEST_F(ServerTest, Gzip) {
  9112. Headers headers;
  9113. headers.emplace("Accept-Encoding", "gzip, deflate");
  9114. auto res = cli_.Get("/compress", headers);
  9115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9116. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9117. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9118. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9119. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9120. "7890123456789012345678901234567890",
  9121. res->body);
  9122. EXPECT_EQ(StatusCode::OK_200, res->status);
  9123. }
  9124. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9125. Headers headers;
  9126. headers.emplace("Accept-Encoding", "gzip, deflate");
  9127. auto res = cli_.Get("/compress-with-charset", headers);
  9128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9129. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9130. EXPECT_EQ("application/json; charset=utf-8",
  9131. res->get_header_value("Content-Type"));
  9132. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9133. "7890123456789012345678901234567890",
  9134. res->body);
  9135. EXPECT_EQ(StatusCode::OK_200, res->status);
  9136. }
  9137. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9138. Headers headers;
  9139. headers.emplace("Accept-Encoding", "");
  9140. auto res = cli_.Get("/compress", headers);
  9141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9142. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9143. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9144. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9145. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9146. "7890123456789012345678901234567890",
  9147. res->body);
  9148. EXPECT_EQ(StatusCode::OK_200, res->status);
  9149. }
  9150. TEST_F(ServerTest, GzipWithContentReceiver) {
  9151. Headers headers;
  9152. headers.emplace("Accept-Encoding", "gzip, deflate");
  9153. std::string body;
  9154. auto res =
  9155. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9156. EXPECT_EQ(100U, data_length);
  9157. body.append(data, data_length);
  9158. return true;
  9159. });
  9160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9161. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9162. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9163. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9164. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9165. "7890123456789012345678901234567890",
  9166. body);
  9167. EXPECT_EQ(StatusCode::OK_200, res->status);
  9168. }
  9169. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9170. Headers headers;
  9171. headers.emplace("Accept-Encoding", "gzip, deflate");
  9172. cli_.set_decompress(false);
  9173. auto res = cli_.Get("/compress", headers);
  9174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9175. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9176. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9177. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9178. EXPECT_EQ(33U, res->body.size());
  9179. EXPECT_EQ(StatusCode::OK_200, res->status);
  9180. }
  9181. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9182. Headers headers;
  9183. headers.emplace("Accept-Encoding", "");
  9184. std::string body;
  9185. auto res =
  9186. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9187. EXPECT_EQ(100U, data_length);
  9188. body.append(data, data_length);
  9189. return true;
  9190. });
  9191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9192. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9193. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9194. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9195. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9196. "7890123456789012345678901234567890",
  9197. body);
  9198. EXPECT_EQ(StatusCode::OK_200, res->status);
  9199. }
  9200. TEST_F(ServerTest, NoGzip) {
  9201. Headers headers;
  9202. headers.emplace("Accept-Encoding", "gzip, deflate");
  9203. auto res = cli_.Get("/nocompress", headers);
  9204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9205. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9206. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9207. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9208. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9209. "7890123456789012345678901234567890",
  9210. res->body);
  9211. EXPECT_EQ(StatusCode::OK_200, res->status);
  9212. }
  9213. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9214. Headers headers;
  9215. headers.emplace("Accept-Encoding", "gzip, deflate");
  9216. std::string body;
  9217. auto res = cli_.Get("/nocompress", headers,
  9218. [&](const char *data, size_t data_length) {
  9219. EXPECT_EQ(100U, data_length);
  9220. body.append(data, data_length);
  9221. return true;
  9222. });
  9223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9224. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9225. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9226. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9227. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9228. "7890123456789012345678901234567890",
  9229. body);
  9230. EXPECT_EQ(StatusCode::OK_200, res->status);
  9231. }
  9232. TEST_F(ServerTest, MultipartFormDataGzip) {
  9233. UploadFormDataItems items = {
  9234. {"key1", "test", "", ""},
  9235. {"key2", "--abcdefg123", "", ""},
  9236. };
  9237. cli_.set_compress(true);
  9238. auto res = cli_.Post("/compress-multipart", items);
  9239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9240. EXPECT_EQ(StatusCode::OK_200, res->status);
  9241. }
  9242. #endif
  9243. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9244. // Static file compression is opt-in, so these run their own server rather than
  9245. // flipping it on for the shared ServerTest fixture, which would silently
  9246. // rewrite what every other static file test is asserting.
  9247. class StaticFileCompressionTest : public ::testing::Test {
  9248. protected:
  9249. void TearDown() override {
  9250. if (t_.joinable()) {
  9251. svr_.stop();
  9252. t_.join();
  9253. }
  9254. }
  9255. int start(const std::function<void(Server &)> &configure = nullptr) {
  9256. // Serves the same tree as a directory of build-time compressed assets
  9257. // would be served: the mount point names the coding the files are already
  9258. // stored in. Registered before "/" so it is the one that matches.
  9259. svr_.set_mount_point("/pre-encoded", "./www",
  9260. {{"Content-Encoding", "gzip"}});
  9261. svr_.set_mount_point("/", "./www");
  9262. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9263. res.set_file_content("./www/dir/index.html", "text/html");
  9264. });
  9265. svr_.Get("/pre-encoded-file-content",
  9266. [](const Request & /*req*/, Response &res) {
  9267. res.set_header("Content-Encoding", "gzip");
  9268. res.set_file_content("./www/dir/index.html", "text/html");
  9269. });
  9270. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9271. res.set_content_provider(
  9272. 6, "text/plain",
  9273. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9274. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9275. return true;
  9276. });
  9277. });
  9278. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9279. res.set_content_provider(
  9280. 1000, "text/plain",
  9281. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9282. if (offset < 100) {
  9283. std::string data(100, 'A');
  9284. sink.write(data.data(), data.size());
  9285. return true;
  9286. }
  9287. std::this_thread::sleep_for(std::chrono::seconds(2));
  9288. std::string data(900, 'B');
  9289. sink.write(data.data(), data.size());
  9290. return true;
  9291. });
  9292. });
  9293. if (configure) { configure(svr_); }
  9294. auto port = svr_.bind_to_any_port(HOST);
  9295. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9296. svr_.wait_until_ready();
  9297. return port;
  9298. }
  9299. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9300. // Every file under ./www except 1MB.txt is smaller than the default
  9301. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9302. // it out of the way.
  9303. static void enable_without_floor(Server &svr) {
  9304. svr.set_static_file_compression(true);
  9305. svr.set_static_file_compression_min_length(0);
  9306. }
  9307. Server svr_;
  9308. std::thread t_;
  9309. };
  9310. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9311. auto port = start();
  9312. Client cli(HOST, port);
  9313. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9315. EXPECT_EQ(StatusCode::OK_200, res->status);
  9316. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9317. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9318. EXPECT_EQ(1048576U, res->body.size());
  9319. }
  9320. TEST_F(StaticFileCompressionTest, MountPoint) {
  9321. auto port = start(enable);
  9322. Client cli(HOST, port);
  9323. cli.set_decompress(false);
  9324. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9326. EXPECT_EQ(StatusCode::OK_200, res->status);
  9327. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9328. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9329. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9330. // The response stays self-delimiting: a length, not a chunked body.
  9331. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9332. EXPECT_EQ(std::to_string(res->body.size()),
  9333. res->get_header_value("Content-Length"));
  9334. EXPECT_LT(res->body.size(), 1048576U);
  9335. EXPECT_FALSE(res->body.empty());
  9336. }
  9337. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9338. auto port = start(enable);
  9339. Client cli(HOST, port);
  9340. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9342. EXPECT_EQ(StatusCode::OK_200, res->status);
  9343. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9344. EXPECT_EQ(1048576U, res->body.size());
  9345. }
  9346. TEST_F(StaticFileCompressionTest, FileContent) {
  9347. auto port = start(enable_without_floor);
  9348. Client cli(HOST, port);
  9349. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9351. EXPECT_EQ(StatusCode::OK_200, res->status);
  9352. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9353. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9354. EXPECT_EQ(104U, res->body.size());
  9355. }
  9356. // A handler that serves an already-encoded file names the coding itself. The
  9357. // file-backed path decided its coding from Accept-Encoding and the content
  9358. // type alone, so it compressed the stored bytes a second time and appended a
  9359. // second Content-Encoding field line.
  9360. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9361. auto port = start(enable_without_floor);
  9362. Client cli(HOST, port);
  9363. cli.set_decompress(false);
  9364. auto res = cli.Get("/pre-encoded-file-content",
  9365. Headers{{"Accept-Encoding", "gzip"}});
  9366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9367. EXPECT_EQ(StatusCode::OK_200, res->status);
  9368. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9369. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9370. // Vary belongs to a coding the server chose, and it chose none here.
  9371. EXPECT_FALSE(res->has_header("Vary"));
  9372. // The file travels exactly as it is stored on disk.
  9373. EXPECT_EQ(104U, res->body.size());
  9374. }
  9375. // The 1MB file clears the default floor, so this one runs the configuration a
  9376. // deployment would actually have.
  9377. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9378. auto port = start(enable);
  9379. Client cli(HOST, port);
  9380. cli.set_decompress(false);
  9381. auto res =
  9382. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9383. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9384. EXPECT_EQ(StatusCode::OK_200, res->status);
  9385. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9386. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9387. EXPECT_FALSE(res->has_header("Vary"));
  9388. EXPECT_EQ(1048576U, res->body.size());
  9389. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9390. }
  9391. TEST_F(StaticFileCompressionTest, Head) {
  9392. auto port = start(enable);
  9393. Client cli(HOST, port);
  9394. cli.set_decompress(false);
  9395. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9396. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9397. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9399. EXPECT_EQ(StatusCode::OK_200, res->status);
  9400. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9401. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9402. // HEAD still reports the size a GET would return.
  9403. EXPECT_EQ(get->get_header_value("Content-Length"),
  9404. res->get_header_value("Content-Length"));
  9405. EXPECT_TRUE(res->body.empty());
  9406. }
  9407. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9408. auto port = start(enable);
  9409. Client cli(HOST, port);
  9410. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9411. {"Accept-Encoding", "gzip"}});
  9412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9413. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9414. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9415. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9416. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9417. EXPECT_EQ("cd", res->body);
  9418. }
  9419. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9420. auto port = start(enable);
  9421. Client cli(HOST, port);
  9422. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9424. EXPECT_EQ(StatusCode::OK_200, res->status);
  9425. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9426. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9427. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9428. }
  9429. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9430. auto port = start(enable);
  9431. Client cli(HOST, port);
  9432. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9434. EXPECT_EQ(StatusCode::OK_200, res->status);
  9435. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9436. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9437. EXPECT_TRUE(res->body.empty());
  9438. }
  9439. TEST_F(StaticFileCompressionTest, MinLength) {
  9440. auto port = start(enable);
  9441. Client cli(HOST, port);
  9442. // 104 bytes, well under the default floor. Compressing it would add the
  9443. // gzip header and trailer to a body that already fits in one packet.
  9444. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9445. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9446. EXPECT_EQ(StatusCode::OK_200, res->status);
  9447. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9448. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9449. }
  9450. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9451. auto port = start([](Server &svr) {
  9452. svr.set_static_file_compression(true);
  9453. svr.set_static_file_compression_min_length(1);
  9454. });
  9455. Client cli(HOST, port);
  9456. cli.set_decompress(false);
  9457. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9459. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9460. // A 9-byte file comes back larger than it went in, because gzip's header and
  9461. // trailer outweigh anything deflate can save. That is the end of the range
  9462. // the floor exists to keep out.
  9463. EXPECT_GT(res->body.size(), 9U);
  9464. }
  9465. TEST_F(StaticFileCompressionTest, MaxLength) {
  9466. auto port = start([](Server &svr) {
  9467. svr.set_static_file_compression(true);
  9468. svr.set_static_file_compression_min_length(0);
  9469. svr.set_static_file_compression_max_length(1024);
  9470. });
  9471. Client cli(HOST, port);
  9472. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9473. // defines `small` as a macro on Windows.
  9474. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9475. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9476. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9477. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9478. // Under it: compressed.
  9479. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9480. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9481. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9482. }
  9483. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9484. auto port = start(enable_without_floor);
  9485. Client cli(HOST, port);
  9486. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9487. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9488. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9489. auto identity_etag = identity->get_header_value("ETag");
  9490. ASSERT_FALSE(identity_etag.empty());
  9491. auto gzipped =
  9492. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9493. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9494. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9495. auto gzip_etag = gzipped->get_header_value("ETag");
  9496. ASSERT_FALSE(gzip_etag.empty());
  9497. // Two representations, two validators.
  9498. EXPECT_NE(identity_etag, gzip_etag);
  9499. // Each one revalidates against the request that would produce it...
  9500. auto fresh =
  9501. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9502. {"If-None-Match", gzip_etag}});
  9503. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9504. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9505. auto fresh_identity =
  9506. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9507. {"If-None-Match", identity_etag}});
  9508. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9509. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9510. // ...and not against the other representation.
  9511. auto crossed =
  9512. cli.Get("/dir/index.html",
  9513. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9514. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9515. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9516. }
  9517. // The opt-in covers responses the server reads off disk itself. A caller's own
  9518. // known-length provider keeps its Content-Length and, more importantly, keeps
  9519. // delivering incrementally: routing it through a compressor would hold every
  9520. // write back until zlib's window filled.
  9521. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9522. auto port = start(enable);
  9523. Client cli(HOST, port);
  9524. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9525. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9526. EXPECT_EQ(StatusCode::OK_200, res->status);
  9527. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9528. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9529. EXPECT_EQ("aaabbb", res->body);
  9530. }
  9531. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9532. auto port = start(enable);
  9533. Client cli(HOST, port);
  9534. cli.set_read_timeout(1, 0);
  9535. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9536. Headers{{"Accept-Encoding", "gzip"}});
  9537. ASSERT_TRUE(handle.is_valid());
  9538. // The provider writes 100 bytes and then stalls for longer than the read
  9539. // timeout. Those first bytes have to arrive anyway: run the response through
  9540. // a compressor and zlib holds them until its window fills, so the read would
  9541. // come back empty instead.
  9542. char buf[256];
  9543. auto n = handle.read(buf, sizeof(buf));
  9544. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9545. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9546. }
  9547. #endif
  9548. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9549. TEST_F(ServerTest, Brotli) {
  9550. Headers headers;
  9551. headers.emplace("Accept-Encoding", "br");
  9552. auto res = cli_.Get("/compress", headers);
  9553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9554. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9555. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9556. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9557. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9558. "7890123456789012345678901234567890",
  9559. res->body);
  9560. EXPECT_EQ(StatusCode::OK_200, res->status);
  9561. }
  9562. #endif
  9563. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9564. TEST_F(ServerTest, Zstd) {
  9565. Headers headers;
  9566. headers.emplace("Accept-Encoding", "zstd");
  9567. auto res = cli_.Get("/compress", headers);
  9568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9569. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9570. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9571. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9572. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9573. "7890123456789012345678901234567890",
  9574. res->body);
  9575. EXPECT_EQ(StatusCode::OK_200, res->status);
  9576. }
  9577. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9578. Headers headers;
  9579. headers.emplace("Accept-Encoding", "");
  9580. auto res = cli_.Get("/compress", headers);
  9581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9582. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9583. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9584. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9585. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9586. "7890123456789012345678901234567890",
  9587. res->body);
  9588. EXPECT_EQ(StatusCode::OK_200, res->status);
  9589. }
  9590. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9591. Headers headers;
  9592. headers.emplace("Accept-Encoding", "zstd");
  9593. std::string body;
  9594. auto res =
  9595. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9596. EXPECT_EQ(100U, data_length);
  9597. body.append(data, data_length);
  9598. return true;
  9599. });
  9600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9601. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9602. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9603. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9604. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9605. "7890123456789012345678901234567890",
  9606. body);
  9607. EXPECT_EQ(StatusCode::OK_200, res->status);
  9608. }
  9609. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9610. Headers headers;
  9611. headers.emplace("Accept-Encoding", "zstd");
  9612. cli_.set_decompress(false);
  9613. auto res = cli_.Get("/compress", headers);
  9614. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9615. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9616. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9617. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9619. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9620. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9621. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9622. EXPECT_EQ(StatusCode::OK_200, res->status);
  9623. ASSERT_EQ(26U, res->body.size());
  9624. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9625. 0);
  9626. }
  9627. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9628. Headers headers;
  9629. headers.emplace("Accept-Encoding", "");
  9630. std::string body;
  9631. auto res =
  9632. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9633. EXPECT_EQ(100U, data_length);
  9634. body.append(data, data_length);
  9635. return true;
  9636. });
  9637. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9638. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9639. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9640. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9641. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9642. "7890123456789012345678901234567890",
  9643. body);
  9644. EXPECT_EQ(StatusCode::OK_200, res->status);
  9645. }
  9646. TEST_F(ServerTest, NoZstd) {
  9647. Headers headers;
  9648. headers.emplace("Accept-Encoding", "zstd");
  9649. auto res = cli_.Get("/nocompress", headers);
  9650. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9651. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9652. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9653. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9654. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9655. "7890123456789012345678901234567890",
  9656. res->body);
  9657. EXPECT_EQ(StatusCode::OK_200, res->status);
  9658. }
  9659. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9660. Headers headers;
  9661. headers.emplace("Accept-Encoding", "zstd");
  9662. std::string body;
  9663. auto res = cli_.Get("/nocompress", headers,
  9664. [&](const char *data, size_t data_length) {
  9665. EXPECT_EQ(100U, data_length);
  9666. body.append(data, data_length);
  9667. return true;
  9668. });
  9669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9670. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9671. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9672. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9673. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9674. "7890123456789012345678901234567890",
  9675. body);
  9676. EXPECT_EQ(StatusCode::OK_200, res->status);
  9677. }
  9678. // TODO: How to enable zstd ??
  9679. TEST_F(ServerTest, MultipartFormDataZstd) {
  9680. UploadFormDataItems items = {
  9681. {"key1", "test", "", ""},
  9682. {"key2", "--abcdefg123", "", ""},
  9683. };
  9684. Headers headers;
  9685. headers.emplace("Accept-Encoding", "zstd");
  9686. cli_.set_compress(true);
  9687. auto res = cli_.Post("/compress-multipart", headers, items);
  9688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9689. EXPECT_EQ(StatusCode::OK_200, res->status);
  9690. }
  9691. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9692. Headers headers;
  9693. headers.emplace("Accept-Encoding", "zstd");
  9694. cli_.set_compress(true);
  9695. auto res = cli_.Put(
  9696. "/put", headers, 3,
  9697. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9698. sink.os << "PUT";
  9699. return true;
  9700. },
  9701. "text/plain");
  9702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9703. EXPECT_EQ(StatusCode::OK_200, res->status);
  9704. EXPECT_EQ("PUT", res->body);
  9705. }
  9706. // Pre-compression logging tests
  9707. TEST_F(ServerTest, PreCompressionLogging) {
  9708. // Test data for compression (matches the actual /compress endpoint content)
  9709. const std::string test_content =
  9710. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9711. "3456789012345678901234567890";
  9712. // Variables to capture logging data
  9713. std::string pre_compression_body;
  9714. std::string pre_compression_content_type;
  9715. std::string pre_compression_content_encoding;
  9716. std::string post_compression_body;
  9717. std::string post_compression_content_type;
  9718. std::string post_compression_content_encoding;
  9719. // Set up pre-compression logger
  9720. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9721. const Response &res) {
  9722. pre_compression_body = res.body;
  9723. pre_compression_content_type = res.get_header_value("Content-Type");
  9724. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9725. });
  9726. // Set up post-compression logger
  9727. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9728. post_compression_body = res.body;
  9729. post_compression_content_type = res.get_header_value("Content-Type");
  9730. post_compression_content_encoding =
  9731. res.get_header_value("Content-Encoding");
  9732. });
  9733. // Test with gzip compression
  9734. Headers headers;
  9735. headers.emplace("Accept-Encoding", "gzip");
  9736. auto res = cli_.Get("/compress", headers);
  9737. // Verify response was compressed
  9738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9739. EXPECT_EQ(StatusCode::OK_200, res->status);
  9740. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9741. // Verify pre-compression logger captured uncompressed content
  9742. EXPECT_EQ(test_content, pre_compression_body);
  9743. EXPECT_EQ("text/plain", pre_compression_content_type);
  9744. EXPECT_TRUE(pre_compression_content_encoding
  9745. .empty()); // No encoding header before compression
  9746. // Verify post-compression logger captured compressed content
  9747. EXPECT_NE(test_content,
  9748. post_compression_body); // Should be different after compression
  9749. EXPECT_EQ("text/plain", post_compression_content_type);
  9750. EXPECT_EQ("gzip", post_compression_content_encoding);
  9751. // Verify compressed content is smaller
  9752. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9753. }
  9754. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9755. const std::string test_content =
  9756. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9757. "3456789012345678901234567890";
  9758. std::string pre_compression_body;
  9759. std::string post_compression_body;
  9760. svr_.set_pre_compression_logger(
  9761. [&](const Request & /*req*/, const Response &res) {
  9762. pre_compression_body = res.body;
  9763. });
  9764. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9765. post_compression_body = res.body;
  9766. });
  9767. Headers headers;
  9768. headers.emplace("Accept-Encoding", "br");
  9769. auto res = cli_.Get("/compress", headers);
  9770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9771. EXPECT_EQ(StatusCode::OK_200, res->status);
  9772. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9773. // Verify pre-compression content is uncompressed
  9774. EXPECT_EQ(test_content, pre_compression_body);
  9775. // Verify post-compression content is compressed
  9776. EXPECT_NE(test_content, post_compression_body);
  9777. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9778. }
  9779. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9780. const std::string test_content =
  9781. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9782. "3456789012345678901234567890";
  9783. std::string pre_compression_body;
  9784. std::string post_compression_body;
  9785. svr_.set_pre_compression_logger(
  9786. [&](const Request & /*req*/, const Response &res) {
  9787. pre_compression_body = res.body;
  9788. });
  9789. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9790. post_compression_body = res.body;
  9791. });
  9792. // Request without compression (use /nocompress endpoint)
  9793. Headers headers;
  9794. auto res = cli_.Get("/nocompress", headers);
  9795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9796. EXPECT_EQ(StatusCode::OK_200, res->status);
  9797. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9798. // Pre-compression logger should not be called when no compression is applied
  9799. EXPECT_TRUE(
  9800. pre_compression_body.empty()); // Pre-compression logger not called
  9801. EXPECT_EQ(
  9802. test_content,
  9803. post_compression_body); // Post-compression logger captures final content
  9804. }
  9805. TEST_F(ServerTest, LoggerSeesContentLength) {
  9806. size_t logged_content_length = 0;
  9807. std::string logged_content_length_header;
  9808. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9809. logged_content_length = res.content_length_;
  9810. logged_content_length_header = res.get_header_value("Content-Length");
  9811. });
  9812. auto res = cli_.Get("/nocompress");
  9813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9814. EXPECT_EQ(StatusCode::OK_200, res->status);
  9815. EXPECT_EQ(res->body.size(), logged_content_length);
  9816. EXPECT_EQ(std::to_string(logged_content_length),
  9817. logged_content_length_header);
  9818. }
  9819. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9820. const std::string test_content =
  9821. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9822. "3456789012345678901234567890";
  9823. std::string pre_compression_body;
  9824. bool pre_logger_called = false;
  9825. // Set only pre-compression logger
  9826. svr_.set_pre_compression_logger(
  9827. [&](const Request & /*req*/, const Response &res) {
  9828. pre_compression_body = res.body;
  9829. pre_logger_called = true;
  9830. });
  9831. Headers headers;
  9832. headers.emplace("Accept-Encoding", "gzip");
  9833. auto res = cli_.Get("/compress", headers);
  9834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9835. EXPECT_EQ(StatusCode::OK_200, res->status);
  9836. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9837. // Verify pre-compression logger was called
  9838. EXPECT_TRUE(pre_logger_called);
  9839. EXPECT_EQ(test_content, pre_compression_body);
  9840. }
  9841. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9842. {
  9843. // Test with Expect: 100-continue header - success case
  9844. // Server returns 100 Continue, client sends body, server returns 200 OK
  9845. Request req;
  9846. req.method = "POST";
  9847. req.path = "/post-large";
  9848. req.set_header("Expect", "100-continue");
  9849. req.body = LARGE_DATA;
  9850. Response res;
  9851. auto error = Error::Success;
  9852. cli_.set_keep_alive(true);
  9853. auto ret = cli_.send(req, res, error);
  9854. EXPECT_TRUE(ret);
  9855. EXPECT_EQ(StatusCode::OK_200, res.status);
  9856. EXPECT_EQ(LARGE_DATA, res.body);
  9857. }
  9858. {
  9859. // Test with Expect: 100-continue header - error case
  9860. // Client should not send the body when server returns an error
  9861. Request req;
  9862. req.method = "POST";
  9863. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9864. req.set_header("Expect", "100-continue");
  9865. req.body = LARGE_DATA;
  9866. Response res;
  9867. auto error = Error::Success;
  9868. auto start = std::chrono::high_resolution_clock::now();
  9869. cli_.set_keep_alive(true);
  9870. auto ret = cli_.send(req, res, error);
  9871. auto end = std::chrono::high_resolution_clock::now();
  9872. auto elapsed =
  9873. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9874. .count();
  9875. // With Expect: 100-continue, request completes successfully but with error
  9876. EXPECT_TRUE(ret);
  9877. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9878. EXPECT_EQ("close", res.get_header_value("Connection"));
  9879. EXPECT_FALSE(cli_.is_socket_open());
  9880. EXPECT_LE(elapsed, 2000);
  9881. }
  9882. {
  9883. // Send an extra GET request to ensure error recovery without hanging
  9884. Request req;
  9885. req.method = "GET";
  9886. req.path = "/hi";
  9887. auto start = std::chrono::high_resolution_clock::now();
  9888. auto res = cli_.send(req);
  9889. auto end = std::chrono::high_resolution_clock::now();
  9890. auto elapsed =
  9891. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9892. .count();
  9893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9894. EXPECT_EQ(StatusCode::OK_200, res->status);
  9895. EXPECT_EQ("Hello World!", res->body);
  9896. EXPECT_LE(elapsed, 500);
  9897. }
  9898. }
  9899. TEST(ZstdDecompressor, ChunkedDecompression) {
  9900. std::string data;
  9901. for (size_t i = 0; i < 32 * 1024; ++i) {
  9902. data.push_back(static_cast<char>('a' + i % 26));
  9903. }
  9904. std::string compressed_data;
  9905. {
  9906. httplib::detail::zstd_compressor compressor;
  9907. bool result = compressor.compress(
  9908. data.data(), data.size(),
  9909. /*last=*/true,
  9910. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9911. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9912. compressed_data_size);
  9913. return true;
  9914. });
  9915. ASSERT_TRUE(result);
  9916. }
  9917. std::string decompressed_data;
  9918. {
  9919. httplib::detail::zstd_decompressor decompressor;
  9920. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9921. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9922. size_t chunk_size = 130;
  9923. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9924. chunk_begin += chunk_size) {
  9925. size_t current_chunk_size =
  9926. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9927. bool result = decompressor.decompress(
  9928. compressed_data.data() + chunk_begin, current_chunk_size,
  9929. [&](const char *decompressed_data_chunk,
  9930. size_t decompressed_data_chunk_size) {
  9931. decompressed_data.insert(decompressed_data.size(),
  9932. decompressed_data_chunk,
  9933. decompressed_data_chunk_size);
  9934. return true;
  9935. });
  9936. ASSERT_TRUE(result);
  9937. }
  9938. }
  9939. ASSERT_EQ(data, decompressed_data);
  9940. }
  9941. TEST(ZstdDecompressor, Decompress) {
  9942. std::string original_text = "Compressed with ZSTD";
  9943. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9944. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9945. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9946. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9947. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9948. std::string decompressed_data;
  9949. {
  9950. httplib::detail::zstd_decompressor decompressor;
  9951. bool result = decompressor.decompress(
  9952. compressed_data.data(), compressed_data.size(),
  9953. [&](const char *decompressed_data_chunk,
  9954. size_t decompressed_data_chunk_size) {
  9955. decompressed_data.insert(decompressed_data.size(),
  9956. decompressed_data_chunk,
  9957. decompressed_data_chunk_size);
  9958. return true;
  9959. });
  9960. ASSERT_TRUE(result);
  9961. }
  9962. ASSERT_EQ(original_text, decompressed_data);
  9963. }
  9964. #endif
  9965. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9966. // separate chunks so that the server sees each part in its own read(). Used to
  9967. // place a read boundary at a specific offset of a request body.
  9968. static bool send_request_in_parts(time_t read_timeout_sec,
  9969. const std::vector<std::string> &parts,
  9970. std::string *resp = nullptr,
  9971. int port = PORT) {
  9972. auto error = Error::Success;
  9973. auto client_sock = detail::create_client_socket(
  9974. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9975. /*connection_timeout_sec=*/5, 0,
  9976. /*read_timeout_sec=*/5, 0,
  9977. /*write_timeout_sec=*/5, 0, std::string(), error);
  9978. if (client_sock == INVALID_SOCKET) { return false; }
  9979. auto ret = detail::process_client_socket(
  9980. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9981. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9982. for (size_t i = 0; i < parts.size(); i++) {
  9983. const auto &part = parts[i];
  9984. if (part.size() !=
  9985. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9986. return false;
  9987. }
  9988. if (i + 1 < parts.size()) {
  9989. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9990. }
  9991. }
  9992. char buf[512];
  9993. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9994. while (line_reader.getline()) {
  9995. if (resp) { *resp += line_reader.ptr(); }
  9996. }
  9997. return true;
  9998. });
  9999. detail::close_socket(client_sock);
  10000. return ret;
  10001. }
  10002. // Sends a raw request to a server listening at HOST:PORT.
  10003. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10004. std::string *resp = nullptr, int port = PORT) {
  10005. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10006. }
  10007. #ifdef CPPHTTPLIB_SSL_ENABLED
  10008. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10009. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10010. ASSERT_TRUE(svr.is_valid());
  10011. svr.set_read_timeout(1, 0);
  10012. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10013. auto se = detail::scope_exit([&] {
  10014. svr.stop();
  10015. t.join();
  10016. ASSERT_FALSE(svr.is_running());
  10017. });
  10018. svr.wait_until_ready();
  10019. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10020. // keeps each wait well within the read timeout. The server gives up a
  10021. // second in, so the bytes sent after that fail.
  10022. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10023. parts.resize(26, std::string(1, '\0'));
  10024. EXPECT_FALSE(send_request_in_parts(5, parts));
  10025. }
  10026. #endif
  10027. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10028. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10029. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10030. const std::vector<std::string> &parts,
  10031. std::string *resp = nullptr,
  10032. int port = PORT) {
  10033. auto error = Error::Success;
  10034. auto sock = detail::create_client_socket(
  10035. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10036. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10037. /*write_timeout_sec=*/5, 0, std::string(), error);
  10038. if (sock == INVALID_SOCKET) { return false; }
  10039. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10040. auto ctx = SSL_CTX_new(TLS_client_method());
  10041. auto ssl = SSL_new(ctx);
  10042. auto ssl_se = detail::scope_exit([&] {
  10043. SSL_free(ssl);
  10044. SSL_CTX_free(ctx);
  10045. });
  10046. SSL_set_fd(ssl, static_cast<int>(sock));
  10047. if (SSL_connect(ssl) != 1) { return false; }
  10048. for (size_t i = 0; i < parts.size(); i++) {
  10049. const auto &part = parts[i];
  10050. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10051. static_cast<int>(part.size())) {
  10052. return false;
  10053. }
  10054. if (i + 1 < parts.size()) {
  10055. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10056. }
  10057. }
  10058. char buf[512];
  10059. int n;
  10060. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10061. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10062. }
  10063. return true;
  10064. }
  10065. #endif
  10066. // The request line, then a header value a byte at a time.
  10067. static std::vector<std::string> slow_request_head_parts() {
  10068. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10069. parts.resize(26, "a");
  10070. parts.emplace_back("\r\n\r\n");
  10071. return parts;
  10072. }
  10073. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10074. // within the one-second read timeout. The server gives up a second in, before
  10075. // the head is complete.
  10076. static void
  10077. expect_slow_request_head_dropped(Server &svr,
  10078. const std::function<std::string()> &send) {
  10079. std::atomic<bool> handled(false);
  10080. svr.Get("/", [&](const Request &, Response &res) {
  10081. handled = true;
  10082. res.set_content("ok", "text/plain");
  10083. });
  10084. svr.set_read_timeout(1, 0);
  10085. thread t = thread([&]() { ASSERT_TRUE(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. auto resp = send();
  10093. EXPECT_FALSE(handled);
  10094. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10095. }
  10096. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10097. Server svr;
  10098. expect_slow_request_head_dropped(svr, [] {
  10099. std::string resp;
  10100. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10101. return resp;
  10102. });
  10103. }
  10104. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10105. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10107. ASSERT_TRUE(svr.is_valid());
  10108. expect_slow_request_head_dropped(svr, [] {
  10109. std::string resp;
  10110. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10111. return resp;
  10112. });
  10113. }
  10114. #endif
  10115. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10116. Server svr;
  10117. std::string header_value;
  10118. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10119. header_value = req.get_header_value("foo");
  10120. res.set_content("ok", "text/plain");
  10121. });
  10122. thread t = thread([&] { svr.listen(HOST, PORT); });
  10123. auto se = detail::scope_exit([&] {
  10124. svr.stop();
  10125. t.join();
  10126. ASSERT_FALSE(svr.is_running());
  10127. });
  10128. svr.wait_until_ready();
  10129. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10130. // like characters are not treated the same - use vertical tab and escape.
  10131. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10132. "foo: \t \v bar \x1B\t \r\n"
  10133. "Connection: close\r\n"
  10134. "\r\n";
  10135. std::string res;
  10136. ASSERT_TRUE(send_request(5, req, &res));
  10137. EXPECT_EQ(header_value, "");
  10138. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10139. }
  10140. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10141. Server svr;
  10142. std::string received;
  10143. svr.Get("/order", [&](const Request &req, Response &res) {
  10144. received = entries_to_string(req.headers);
  10145. res.set_content("ok", "text/plain");
  10146. });
  10147. auto port = svr.bind_to_any_port(HOST);
  10148. thread t = thread([&] { svr.listen_after_bind(); });
  10149. auto se = detail::scope_exit([&] {
  10150. svr.stop();
  10151. t.join();
  10152. ASSERT_FALSE(svr.is_running());
  10153. });
  10154. svr.wait_until_ready();
  10155. const std::string req = "GET /order HTTP/1.1\r\n"
  10156. "Host: localhost\r\n"
  10157. "X-First: 1\r\n"
  10158. "X-Dup: a\r\n"
  10159. "X-Second: 2\r\n"
  10160. "X-Dup: b\r\n"
  10161. "Connection: close\r\n"
  10162. "\r\n";
  10163. std::string res;
  10164. ASSERT_TRUE(send_request(5, req, &res, port));
  10165. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10166. EXPECT_EQ(
  10167. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10168. received);
  10169. }
  10170. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10171. Server svr;
  10172. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10173. res.set_header("Set-Cookie", "first=1");
  10174. res.set_header("X-Between", "y");
  10175. res.set_header("Set-Cookie", "second=2");
  10176. res.set_content("ok", "text/plain");
  10177. });
  10178. auto port = svr.bind_to_any_port(HOST);
  10179. thread t = thread([&] { svr.listen_after_bind(); });
  10180. auto se = detail::scope_exit([&] {
  10181. svr.stop();
  10182. t.join();
  10183. ASSERT_FALSE(svr.is_running());
  10184. });
  10185. svr.wait_until_ready();
  10186. Client cli(HOST, port);
  10187. auto res = cli.Get("/cookies");
  10188. ASSERT_TRUE(res);
  10189. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10190. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10191. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10192. }
  10193. // A stream may send a byte at a time with a small extension on each chunk,
  10194. // however long it runs
  10195. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10196. Server svr;
  10197. svr.Post("/count", [](const Request &req, Response &res) {
  10198. res.set_content(std::to_string(req.body.size()), "text/plain");
  10199. });
  10200. auto port = svr.bind_to_any_port(HOST);
  10201. ASSERT_LT(0, port);
  10202. thread t = thread([&] { svr.listen_after_bind(); });
  10203. auto se = detail::scope_exit([&] {
  10204. svr.stop();
  10205. t.join();
  10206. ASSERT_FALSE(svr.is_running());
  10207. });
  10208. svr.wait_until_ready();
  10209. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10210. "\r\nTransfer-Encoding: chunked\r\n"
  10211. "Connection: close\r\n\r\n";
  10212. for (auto i = 0; i < 4096; i++) {
  10213. req += "1;a=b\r\nx\r\n";
  10214. }
  10215. req += "0\r\n\r\n";
  10216. std::string res;
  10217. ASSERT_TRUE(send_request(5, req, &res, port));
  10218. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10219. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10220. }
  10221. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10222. Server svr;
  10223. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10224. auto i = new int(0);
  10225. res.set_header("Trailer", "X-Safe, X-Reflected");
  10226. res.set_chunked_content_provider(
  10227. "text/plain",
  10228. [i](size_t /*offset*/, DataSink &sink) {
  10229. if (*i == 0) {
  10230. sink.os << "body";
  10231. } else {
  10232. Headers trailer;
  10233. // A valid trailer that must survive.
  10234. trailer.emplace("X-Safe", "safe");
  10235. // Attacker-controlled value carrying CR/LF (response splitting).
  10236. trailer.emplace("X-Reflected",
  10237. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10238. // Attacker-controlled name carrying CR/LF.
  10239. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10240. sink.done_with_trailer(trailer);
  10241. }
  10242. (*i)++;
  10243. return true;
  10244. },
  10245. [i](bool /*success*/) { delete i; });
  10246. });
  10247. thread t = thread([&] { svr.listen(HOST, PORT); });
  10248. auto se = detail::scope_exit([&] {
  10249. svr.stop();
  10250. t.join();
  10251. ASSERT_FALSE(svr.is_running());
  10252. });
  10253. svr.wait_until_ready();
  10254. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10255. "Host: " + HOST +
  10256. "\r\n"
  10257. "Connection: close\r\n"
  10258. "\r\n";
  10259. std::string res;
  10260. ASSERT_TRUE(send_request(5, req, &res));
  10261. // The injected fields must not appear anywhere in the raw response.
  10262. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10263. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10264. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10265. // Invalid trailers are dropped entirely, matching set_header().
  10266. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10267. // The valid trailer still passes through.
  10268. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10269. }
  10270. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10271. // A custom header writer gets only the fields the default one writes
  10272. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10273. std::string s;
  10274. for (const auto &h : hdrs) {
  10275. s += h.first + ": " + h.second + "\r\n";
  10276. }
  10277. s += "\r\n";
  10278. return strm.write(s.data(), s.size());
  10279. };
  10280. for (auto custom_writer : {false, true}) {
  10281. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10282. Server svr;
  10283. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10284. svr.set_post_routing_handler([](const Request &, Response &res) {
  10285. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10286. });
  10287. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10288. // res.headers is a public field an application can populate directly,
  10289. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10290. // A valid header that must survive.
  10291. res.headers.emplace("X-Safe", "safe");
  10292. // Attacker-controlled value carrying CR/LF (response splitting).
  10293. res.headers.emplace("X-Reflected",
  10294. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10295. // Attacker-controlled name carrying CR/LF.
  10296. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10297. res.set_content("body", "text/plain");
  10298. });
  10299. thread t = thread([&] { svr.listen(HOST, PORT); });
  10300. auto se = detail::scope_exit([&] {
  10301. svr.stop();
  10302. t.join();
  10303. ASSERT_FALSE(svr.is_running());
  10304. });
  10305. svr.wait_until_ready();
  10306. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10307. "Host: " + HOST +
  10308. "\r\n"
  10309. "Connection: close\r\n"
  10310. "\r\n";
  10311. std::string res;
  10312. ASSERT_TRUE(send_request(5, req, &res));
  10313. // The injected fields must not appear anywhere in the raw response.
  10314. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10315. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10316. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10317. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10318. // Invalid headers are dropped entirely, matching set_header().
  10319. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10320. // The valid header still passes through.
  10321. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10322. }
  10323. }
  10324. // Forward declaration: in split builds split.py strips `inline` and moves the
  10325. // definition into httplib.cc, so detail::write_request_line is not visible from
  10326. // the public httplib.h. Re-declaring it here lets the tests link against the
  10327. // symbol in both header-only and split builds.
  10328. namespace httplib {
  10329. namespace detail {
  10330. ssize_t write_request_line(Stream &strm, const std::string &method,
  10331. const std::string &path);
  10332. } // namespace detail
  10333. } // namespace httplib
  10334. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10335. // A well-formed target is written verbatim.
  10336. {
  10337. detail::BufferStream strm;
  10338. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10339. EXPECT_GT(n, 0);
  10340. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10341. }
  10342. // A target carrying CR/LF, SP or other control octets must be rejected
  10343. // before anything reaches the wire, otherwise it splits the request line and
  10344. // injects a header or a whole request.
  10345. const std::string evil_targets[] = {
  10346. "/a\r\nInjected: pwned",
  10347. "/a\rInjected",
  10348. "/a\nInjected",
  10349. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10350. "/a b",
  10351. "/a\tb",
  10352. "/a\x7f",
  10353. };
  10354. for (const auto &evil : evil_targets) {
  10355. detail::BufferStream strm;
  10356. auto n = detail::write_request_line(strm, "GET", evil);
  10357. EXPECT_LT(n, 0);
  10358. EXPECT_TRUE(strm.get_buffer().empty());
  10359. }
  10360. }
  10361. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10362. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10363. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10364. // target reaches write_request. The client must fail cleanly with
  10365. // Error::Write instead of putting a request-line-less, header-injecting
  10366. // request on the wire.
  10367. Server svr;
  10368. svr.Get("/a", [](const Request &, Response &res) {
  10369. res.set_content("ok", "text/plain");
  10370. });
  10371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10372. auto se = detail::scope_exit([&] {
  10373. svr.stop();
  10374. thread.join();
  10375. ASSERT_FALSE(svr.is_running());
  10376. });
  10377. svr.wait_until_ready();
  10378. {
  10379. Client cli(HOST, PORT);
  10380. cli.set_path_encode(false);
  10381. // The request is rejected before anything is written, so the connection
  10382. // stays silent and the subsequent response read would otherwise block for
  10383. // the full default read timeout. Shorten it -- the assertion is on the
  10384. // error, not the timeout.
  10385. cli.set_read_timeout(1, 0);
  10386. auto res = cli.Get("/a\r\nInjected: pwned");
  10387. EXPECT_FALSE(res);
  10388. EXPECT_EQ(Error::Write, res.error());
  10389. }
  10390. }
  10391. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10392. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10393. // including extension methods.
  10394. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10395. for (const auto &method : good_methods) {
  10396. detail::BufferStream strm;
  10397. auto n = detail::write_request_line(strm, method, "/");
  10398. EXPECT_GT(n, 0);
  10399. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10400. }
  10401. // A method carrying CR/LF would split the request line and smuggle a whole
  10402. // request ahead of the real one. A space or an empty method corrupts the
  10403. // request line. All must be rejected before anything reaches the wire.
  10404. const std::string evil_methods[] = {
  10405. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10406. "GET\r\nInjected: pwned",
  10407. "GET\r",
  10408. "GET\n",
  10409. "GE T",
  10410. "",
  10411. };
  10412. for (const auto &evil : evil_methods) {
  10413. detail::BufferStream strm;
  10414. auto n = detail::write_request_line(strm, evil, "/");
  10415. EXPECT_LT(n, 0);
  10416. EXPECT_TRUE(strm.get_buffer().empty());
  10417. }
  10418. }
  10419. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10420. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10421. // through Client::send must fail with Error::Write and no request, neither
  10422. // the smuggled one nor the real one, may reach the server.
  10423. Server svr;
  10424. std::atomic<int> request_count(0);
  10425. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10426. request_count++;
  10427. res.status = StatusCode::OK_200;
  10428. return Server::HandlerResponse::Handled;
  10429. });
  10430. auto port = svr.bind_to_any_port(HOST);
  10431. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10432. auto se = detail::scope_exit([&] {
  10433. svr.stop();
  10434. thread.join();
  10435. ASSERT_FALSE(svr.is_running());
  10436. });
  10437. svr.wait_until_ready();
  10438. {
  10439. Client cli(HOST, port);
  10440. const std::string evil_methods[] = {
  10441. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10442. "GE T",
  10443. "",
  10444. };
  10445. for (const auto &evil : evil_methods) {
  10446. Request req;
  10447. req.method = evil;
  10448. req.path = "/";
  10449. auto res = cli.send(req);
  10450. EXPECT_FALSE(res);
  10451. EXPECT_EQ(Error::Write, res.error());
  10452. }
  10453. auto handle =
  10454. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10455. EXPECT_FALSE(handle.is_valid());
  10456. EXPECT_EQ(Error::Write, handle.error);
  10457. // A valid request on the same client still goes through.
  10458. auto res = cli.Get("/");
  10459. ASSERT_TRUE(res);
  10460. EXPECT_EQ(StatusCode::OK_200, res->status);
  10461. }
  10462. EXPECT_EQ(1, request_count.load());
  10463. }
  10464. // Sends a raw request and verifies that there isn't a crash or exception.
  10465. static void test_raw_request(const std::string &req,
  10466. std::string *out = nullptr) {
  10467. Server svr;
  10468. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10469. res.set_content("ok", "text/plain");
  10470. });
  10471. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10472. res.set_content("ok", "text/plain");
  10473. });
  10474. svr.Get("/header_field_value_check",
  10475. [&](const Request & /*req*/, Response &res) {
  10476. res.set_content("ok", "text/plain");
  10477. });
  10478. svr.CustomRoute("PROPFIND", "/dav",
  10479. [&](const Request & /*req*/, Response &res) {
  10480. res.status = StatusCode::MultiStatus_207;
  10481. });
  10482. // Server read timeout must be longer than the client read timeout for the
  10483. // bug to reproduce, probably to force the server to process a request
  10484. // without a trailing blank line.
  10485. const time_t client_read_timeout_sec = 1;
  10486. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10487. bool listen_thread_ok = false;
  10488. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10489. auto se = detail::scope_exit([&] {
  10490. svr.stop();
  10491. t.join();
  10492. ASSERT_FALSE(svr.is_running());
  10493. EXPECT_TRUE(listen_thread_ok);
  10494. });
  10495. svr.wait_until_ready();
  10496. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10497. }
  10498. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10499. // A certain header line causes an exception if the header property is parsed
  10500. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10501. test_raw_request(
  10502. "GET /hi HTTP/1.1\r\n"
  10503. " : "
  10504. " "
  10505. " ");
  10506. }
  10507. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10508. // A certain header line causes an exception if the header property *name* is
  10509. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10510. // greedy matcher and requires backtracking when there are a lot of ":"
  10511. // characters.
  10512. // This occurs with libc++ but not libstdc++.
  10513. test_raw_request(
  10514. "GET /hi HTTP/1.1\r\n"
  10515. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10516. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10517. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10518. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10519. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10520. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10521. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10522. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10523. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10524. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10525. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10526. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10527. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10528. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10529. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10530. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10531. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10532. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10533. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10534. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10535. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10536. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10537. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10538. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10539. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10540. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10541. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10542. "&&&%%%");
  10543. }
  10544. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10545. // Make sure this doesn't crash the server.
  10546. // In a previous version of the header line regex, the "\r" rendered the line
  10547. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10548. // a new position where the leading white space ended and the field value
  10549. // began.
  10550. // The crash occurs with libc++ but not libstdc++.
  10551. test_raw_request("GET /hi HTTP/1.1\r\n"
  10552. "a:" +
  10553. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10554. "\r\n"
  10555. "\r\n");
  10556. }
  10557. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10558. const char *rejected[] = {
  10559. // RFC 9112 §3: one SP between the parts, and nothing else
  10560. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10561. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10562. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10563. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10564. // A request-target has no fragment
  10565. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10566. // An HTTP/1.1 request needs a Host
  10567. "GET /hi HTTP/1.1\r\n\r\n",
  10568. };
  10569. for (auto request : rejected) {
  10570. std::string out;
  10571. test_raw_request(request, &out);
  10572. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10573. }
  10574. std::string out;
  10575. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10576. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10577. }
  10578. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10579. // RFC 9112 §6.1
  10580. const char *requests[] = {
  10581. "PUT /put_hi HTTP/1.1\r\n"
  10582. "Host: localhost\r\n"
  10583. "Content-Length: 0\r\n"
  10584. "Transfer-Encoding: chunked\r\n"
  10585. "\r\n"
  10586. "0\r\n\r\n",
  10587. "PUT /put_hi HTTP/1.0\r\n"
  10588. "Connection: keep-alive\r\n"
  10589. "Transfer-Encoding: chunked\r\n"
  10590. "\r\n"
  10591. "0\r\n\r\n",
  10592. };
  10593. for (auto request : requests) {
  10594. std::string out;
  10595. test_raw_request(request, &out);
  10596. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10597. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10598. }
  10599. }
  10600. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10601. std::string out;
  10602. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10603. "Content-Type: text/plain\r\n"
  10604. "Transfer-Encoding: chunked\r\n"
  10605. "\r\n"
  10606. "nothex\r\n",
  10607. &out);
  10608. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10609. }
  10610. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10611. std::string out;
  10612. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10613. "Content-Type: text/plain\r\n"
  10614. "Transfer-Encoding: chunked\r\n"
  10615. "\r\n"
  10616. "3\r\n"
  10617. "xyz\r\n"
  10618. "NaN\r\n",
  10619. &out);
  10620. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10621. }
  10622. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10623. std::string out;
  10624. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10625. "Content-Type: text/plain\r\n"
  10626. "Transfer-Encoding: chunked\r\n"
  10627. "\r\n"
  10628. // Length is too large for 64 bits.
  10629. "1ffffffffffffffff\r\n"
  10630. "xyz\r\n",
  10631. &out);
  10632. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10633. }
  10634. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10635. test_raw_request("GET /hi HTTP/1.1\r\n"
  10636. "Content-Type: text/plain\r\n\r");
  10637. }
  10638. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10639. std::string out;
  10640. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10641. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10642. }
  10643. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10644. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10645. std::string out;
  10646. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10647. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10648. }
  10649. }
  10650. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10651. std::string out;
  10652. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10653. "Host: localhost\r\n"
  10654. "Connection: close\r\n\r\n",
  10655. &out);
  10656. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10657. }
  10658. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10659. Server svr;
  10660. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10661. EXPECT_TRUE(!req.remote_addr.empty());
  10662. });
  10663. thread t = thread([&] { svr.listen(HOST, PORT); });
  10664. auto se = detail::scope_exit([&] {
  10665. svr.stop();
  10666. t.join();
  10667. ASSERT_FALSE(svr.is_running());
  10668. });
  10669. svr.wait_until_ready();
  10670. // Send an invalid request line to trigger Bad Request
  10671. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10672. std::string out;
  10673. ASSERT_TRUE(send_request(5, bad_req, &out));
  10674. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10675. }
  10676. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10677. // answered right away rather than blocking on a read that waits for EOF.
  10678. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10679. std::string out;
  10680. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10681. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10682. }
  10683. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10684. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10685. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10686. for (const auto *method : methods) {
  10687. Server svr;
  10688. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10689. EXPECT_FALSE(svr.is_valid()) << method;
  10690. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10691. }
  10692. }
  10693. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10694. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10695. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10696. for (const auto *method : methods) {
  10697. Server svr;
  10698. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10699. EXPECT_FALSE(svr.is_valid()) << method;
  10700. }
  10701. }
  10702. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10703. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10704. "COPY", "MOVE", "LOCK",
  10705. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10706. Server svr;
  10707. for (const auto *method : methods) {
  10708. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10709. }
  10710. EXPECT_TRUE(svr.is_valid());
  10711. }
  10712. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10713. Server svr;
  10714. svr.CustomRoute("POST", "/x",
  10715. [](const Request &, Response &, const ContentReader &) {});
  10716. EXPECT_FALSE(svr.is_valid());
  10717. }
  10718. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10719. Server svr;
  10720. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10721. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10722. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10723. EXPECT_FALSE(svr.is_valid());
  10724. }
  10725. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10726. Server svr;
  10727. auto captured = Error::Success;
  10728. svr.set_error_logger(
  10729. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10730. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10731. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10732. }
  10733. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10734. std::string out;
  10735. std::string request(
  10736. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10737. test_raw_request(request, &out);
  10738. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10739. }
  10740. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10741. std::string out;
  10742. std::string request(
  10743. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10744. test_raw_request(request, &out);
  10745. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10746. }
  10747. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10748. std::string out;
  10749. std::string request(
  10750. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10751. test_raw_request(request, &out);
  10752. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10753. }
  10754. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10755. std::string out;
  10756. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10757. "Host: localhost\r\n"
  10758. "Test: \r\n\r\n",
  10759. &out);
  10760. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10761. }
  10762. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10763. Server svr;
  10764. std::string x_custom;
  10765. std::string cookie;
  10766. std::string xff;
  10767. std::string x_unicode;
  10768. std::string x_iis;
  10769. svr.Get("/check", [&](const Request &req, Response &res) {
  10770. x_custom = req.get_header_value("X-Custom");
  10771. cookie = req.get_header_value("Cookie");
  10772. xff = req.get_header_value("X-Forwarded-For");
  10773. x_unicode = req.get_header_value("X-Unicode");
  10774. x_iis = req.get_header_value("X-IIS");
  10775. res.set_content("ok", "text/plain");
  10776. });
  10777. thread t = thread([&] { svr.listen(HOST, PORT); });
  10778. auto se = detail::scope_exit([&] {
  10779. svr.stop();
  10780. t.join();
  10781. ASSERT_FALSE(svr.is_running());
  10782. });
  10783. svr.wait_until_ready();
  10784. const std::string req = "GET /check HTTP/1.1\r\n"
  10785. "Host: localhost\r\n"
  10786. "X-Custom: a%0D%0AInjected: b\r\n"
  10787. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10788. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10789. "X-Unicode: %E3%81%82\r\n"
  10790. "X-IIS: %u00E9\r\n"
  10791. "Connection: close\r\n"
  10792. "\r\n";
  10793. std::string res;
  10794. ASSERT_TRUE(send_request(5, req, &res));
  10795. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10796. // Every value must be returned verbatim (wire form), with no decoding.
  10797. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10798. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10799. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10800. EXPECT_EQ("%E3%81%82", x_unicode);
  10801. EXPECT_EQ("%u00E9", x_iis);
  10802. }
  10803. // Applications that previously relied on automatic percent-decoding can
  10804. // reproduce the old behavior by explicitly calling decode_path_component()
  10805. // or, for RFC 3986 conformance, decode_uri_component().
  10806. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10807. Server svr;
  10808. std::string decoded;
  10809. svr.Get("/check", [&](const Request &req, Response &res) {
  10810. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10811. res.set_content("ok", "text/plain");
  10812. });
  10813. thread t = thread([&] { svr.listen(HOST, PORT); });
  10814. auto se = detail::scope_exit([&] {
  10815. svr.stop();
  10816. t.join();
  10817. ASSERT_FALSE(svr.is_running());
  10818. });
  10819. svr.wait_until_ready();
  10820. const std::string req = "GET /check HTTP/1.1\r\n"
  10821. "Host: localhost\r\n"
  10822. "X-Custom: hello%20world\r\n"
  10823. "Connection: close\r\n"
  10824. "\r\n";
  10825. std::string res;
  10826. ASSERT_TRUE(send_request(5, req, &res));
  10827. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10828. EXPECT_EQ("hello world", decoded);
  10829. }
  10830. // Regression test for #2033. Browsers send Referer values that include
  10831. // percent-encoded characters such as %0A inside the URL. Decoding the
  10832. // header value would either trip the post-decode CR/LF/NUL guard (the
  10833. // original bug, returning 400) or, after that guard was relaxed, silently
  10834. // store a literal LF — both unacceptable. The wire form must round-trip.
  10835. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10836. Server svr;
  10837. std::string referer;
  10838. svr.Get("/check", [&](const Request &req, Response &res) {
  10839. referer = req.get_header_value("Referer");
  10840. res.set_content("ok", "text/plain");
  10841. });
  10842. thread t = thread([&] { svr.listen(HOST, PORT); });
  10843. auto se = detail::scope_exit([&] {
  10844. svr.stop();
  10845. t.join();
  10846. ASSERT_FALSE(svr.is_running());
  10847. });
  10848. svr.wait_until_ready();
  10849. const std::string req = "GET /check HTTP/1.1\r\n"
  10850. "Host: localhost\r\n"
  10851. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10852. "Connection: close\r\n"
  10853. "\r\n";
  10854. std::string res;
  10855. ASSERT_TRUE(send_request(5, req, &res));
  10856. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10857. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10858. }
  10859. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10860. Server svr;
  10861. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10862. res.set_header("Cache-Control", "no-cache");
  10863. res.set_chunked_content_provider(
  10864. "text/event-stream", [](size_t offset, DataSink &sink) {
  10865. std::string s = "data:";
  10866. s += std::to_string(offset);
  10867. s += "\n\n";
  10868. auto ret = sink.write(s.data(), s.size());
  10869. EXPECT_TRUE(ret);
  10870. std::this_thread::sleep_for(std::chrono::seconds(1));
  10871. return true;
  10872. });
  10873. });
  10874. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10875. svr.wait_until_ready();
  10876. Client client(HOST, PORT);
  10877. const Headers headers = {{"Accept", "text/event-stream"}};
  10878. auto get_thread = std::thread([&client, &headers]() {
  10879. auto res = client.Get(
  10880. "/events", headers,
  10881. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10882. });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. get_thread.join();
  10886. listen_thread.join();
  10887. ASSERT_FALSE(svr.is_running());
  10888. });
  10889. // Give GET time to get a few messages.
  10890. std::this_thread::sleep_for(std::chrono::seconds(2));
  10891. }
  10892. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10893. httplib::Server svr;
  10894. svr.Post("/hi",
  10895. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10896. res.status = StatusCode::OK_200;
  10897. });
  10898. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10899. svr.wait_until_ready();
  10900. Client cli(HOST, PORT);
  10901. auto res = cli.Post("/hi", "data", "text/plain");
  10902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10903. EXPECT_EQ(StatusCode::OK_200, res->status);
  10904. svr.stop();
  10905. thread.join();
  10906. ASSERT_FALSE(svr.is_running());
  10907. res = cli.Post("/hi", "data", "text/plain");
  10908. ASSERT_FALSE(res);
  10909. }
  10910. TEST(ServerStopTest, ListenFailure) {
  10911. Server svr;
  10912. auto t = thread([&]() {
  10913. auto ret = svr.listen("????", PORT);
  10914. EXPECT_FALSE(ret);
  10915. });
  10916. svr.wait_until_ready();
  10917. svr.stop();
  10918. t.join();
  10919. }
  10920. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10921. TEST(ServerStopTest, Decommision) {
  10922. Server svr;
  10923. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10924. for (int i = 0; i < 4; i++) {
  10925. auto is_even = !(i % 2);
  10926. std::thread t{[&] {
  10927. try {
  10928. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10929. if (is_even) {
  10930. throw std::runtime_error("Some thing that happens to go wrong.");
  10931. }
  10932. svr.listen(HOST, PORT);
  10933. } catch (...) { svr.decommission(); }
  10934. }};
  10935. svr.wait_until_ready();
  10936. // Server is up
  10937. {
  10938. Client cli(HOST, PORT);
  10939. auto res = cli.Get("/hi");
  10940. if (is_even) {
  10941. EXPECT_FALSE(res);
  10942. } else {
  10943. EXPECT_TRUE(res);
  10944. EXPECT_EQ("hi...", res->body);
  10945. }
  10946. }
  10947. svr.stop();
  10948. t.join();
  10949. // Server is down...
  10950. {
  10951. Client cli(HOST, PORT);
  10952. auto res = cli.Get("/hi");
  10953. EXPECT_FALSE(res);
  10954. }
  10955. }
  10956. }
  10957. #endif
  10958. // Helper function for string body upload progress tests
  10959. template <typename SetupHandler, typename ClientCall>
  10960. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10961. ClientCall &&client_call,
  10962. const string &body) {
  10963. Server svr;
  10964. setup_handler(svr);
  10965. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10966. auto se = detail::scope_exit([&] {
  10967. svr.stop();
  10968. t.join();
  10969. });
  10970. svr.wait_until_ready();
  10971. Client cli(HOST, PORT);
  10972. vector<uint64_t> progress_values;
  10973. bool progress_called = false;
  10974. auto res =
  10975. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10976. progress_values.push_back(current);
  10977. progress_called = true;
  10978. return true;
  10979. });
  10980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10981. EXPECT_EQ(200, res->status);
  10982. EXPECT_TRUE(progress_called);
  10983. }
  10984. TEST(UploadProgressTest, PostStringBodyBasic) {
  10985. TestStringBodyUploadProgress(
  10986. [](Server &svr) {
  10987. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10988. res.set_content("received", "text/plain");
  10989. });
  10990. },
  10991. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10992. return cli.Post("/test", body, "text/plain", progress_callback);
  10993. },
  10994. "test data for upload progress");
  10995. }
  10996. TEST(UploadProgressTest, PutStringBodyBasic) {
  10997. TestStringBodyUploadProgress(
  10998. [](Server &svr) {
  10999. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  11000. res.set_content("put received", "text/plain");
  11001. });
  11002. },
  11003. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11004. return cli.Put("/test", body, "text/plain", progress_callback);
  11005. },
  11006. "put test data for upload progress");
  11007. }
  11008. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11009. TestStringBodyUploadProgress(
  11010. [](Server &svr) {
  11011. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11012. res.set_content("patch received", "text/plain");
  11013. });
  11014. },
  11015. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11016. return cli.Patch("/test", body, "text/plain", progress_callback);
  11017. },
  11018. "patch test data for upload progress");
  11019. }
  11020. // Helper function for content provider upload progress tests
  11021. template <typename SetupHandler, typename ClientCall>
  11022. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11023. ClientCall &&client_call) {
  11024. Server svr;
  11025. setup_handler(svr);
  11026. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11027. auto se = detail::scope_exit([&] {
  11028. svr.stop();
  11029. t.join();
  11030. });
  11031. svr.wait_until_ready();
  11032. Client cli(HOST, PORT);
  11033. vector<uint64_t> progress_values;
  11034. auto res =
  11035. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11036. progress_values.push_back(current);
  11037. return true;
  11038. });
  11039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11040. EXPECT_EQ(200, res->status);
  11041. EXPECT_FALSE(progress_values.empty());
  11042. }
  11043. TEST(UploadProgressTest, PostContentProviderProgress) {
  11044. TestContentProviderUploadProgress(
  11045. [](Server &svr) {
  11046. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11047. res.set_content("provider received", "text/plain");
  11048. });
  11049. },
  11050. [](Client &cli, UploadProgress progress_callback) {
  11051. return cli.Post(
  11052. "/test", 9,
  11053. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11054. sink.os << "test data";
  11055. return true;
  11056. },
  11057. "text/plain", progress_callback);
  11058. });
  11059. }
  11060. // Helper function for multipart upload progress tests
  11061. template <typename SetupHandler, typename ClientCall>
  11062. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11063. ClientCall &&client_call,
  11064. const string &endpoint) {
  11065. Server svr;
  11066. setup_handler(svr);
  11067. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11068. auto se = detail::scope_exit([&] {
  11069. svr.stop();
  11070. t.join();
  11071. });
  11072. svr.wait_until_ready();
  11073. Client cli(HOST, PORT);
  11074. vector<uint64_t> progress_values;
  11075. UploadFormDataItems items = {
  11076. {"field1", "value1", "", ""},
  11077. {"field2", "longer value for progress tracking test", "", ""},
  11078. {"file1", "file content data for upload progress", "test.txt",
  11079. "text/plain"}};
  11080. auto res = client_call(cli, endpoint, items,
  11081. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11082. progress_values.push_back(current);
  11083. return true;
  11084. });
  11085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11086. EXPECT_EQ(200, res->status);
  11087. EXPECT_FALSE(progress_values.empty());
  11088. }
  11089. TEST(UploadProgressTest, PostMultipartProgress) {
  11090. TestMultipartUploadProgress(
  11091. [](Server &svr) {
  11092. svr.Post("/multipart", [](const Request &req, Response &res) {
  11093. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11094. res.set_content("multipart received", "text/plain");
  11095. });
  11096. },
  11097. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11098. UploadProgress progress_callback) {
  11099. return cli.Post(endpoint, items, progress_callback);
  11100. },
  11101. "/multipart");
  11102. }
  11103. // Helper function for basic download progress tests
  11104. template <typename SetupHandler, typename ClientCall>
  11105. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11106. ClientCall &&client_call, const string &endpoint,
  11107. size_t expected_content_size) {
  11108. Server svr;
  11109. setup_handler(svr);
  11110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11111. auto se = detail::scope_exit([&] {
  11112. svr.stop();
  11113. t.join();
  11114. });
  11115. svr.wait_until_ready();
  11116. Client cli(HOST, PORT);
  11117. vector<uint64_t> progress_values;
  11118. auto res = client_call(cli, endpoint,
  11119. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11120. progress_values.push_back(current);
  11121. return true;
  11122. });
  11123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11124. EXPECT_EQ(200, res->status);
  11125. EXPECT_FALSE(progress_values.empty());
  11126. EXPECT_EQ(expected_content_size, res->body.size());
  11127. }
  11128. TEST(DownloadProgressTest, GetBasic) {
  11129. TestBasicDownloadProgress(
  11130. [](Server &svr) {
  11131. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11132. string content(1000, 'D');
  11133. res.set_content(content, "text/plain");
  11134. });
  11135. },
  11136. [](Client &cli, const string &endpoint,
  11137. DownloadProgress progress_callback) {
  11138. return cli.Get(endpoint, progress_callback);
  11139. },
  11140. "/download", 1000u);
  11141. }
  11142. // Helper function for content receiver download progress tests
  11143. template <typename SetupHandler, typename ClientCall>
  11144. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11145. ClientCall &&client_call,
  11146. const string &endpoint,
  11147. size_t expected_content_size) {
  11148. Server svr;
  11149. setup_handler(svr);
  11150. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11151. auto se = detail::scope_exit([&] {
  11152. svr.stop();
  11153. t.join();
  11154. });
  11155. svr.wait_until_ready();
  11156. Client cli(HOST, PORT);
  11157. vector<uint64_t> progress_values;
  11158. string received_body;
  11159. auto res = client_call(
  11160. cli, endpoint,
  11161. [&](const char *data, size_t data_length) -> bool {
  11162. received_body.append(data, data_length);
  11163. return true;
  11164. },
  11165. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11166. progress_values.push_back(current);
  11167. return true;
  11168. });
  11169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11170. EXPECT_EQ(200, res->status);
  11171. EXPECT_FALSE(progress_values.empty());
  11172. EXPECT_EQ(expected_content_size, received_body.size());
  11173. EXPECT_TRUE(res->body.empty());
  11174. }
  11175. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11176. TestContentReceiverDownloadProgress(
  11177. [](Server &svr) {
  11178. svr.Get("/download-receiver",
  11179. [](const Request & /*req*/, Response &res) {
  11180. string content(2000, 'R');
  11181. res.set_content(content, "text/plain");
  11182. });
  11183. },
  11184. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11185. DownloadProgress progress_callback) {
  11186. return cli.Get(endpoint, content_receiver, progress_callback);
  11187. },
  11188. "/download-receiver", 2000u);
  11189. }
  11190. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11191. // A provider reaching a pass with nothing to hand over - an empty buffer
  11192. // popped off a queue, say - must not be taken to mean the body is finished.
  11193. // It used to end the loop with the terminating chunk unwritten while the
  11194. // server still considered the response complete, so the peer waited for an
  11195. // end that never arrived.
  11196. Server svr;
  11197. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11198. auto step = std::make_shared<int>(0);
  11199. res.set_chunked_content_provider("text/plain",
  11200. [step](size_t /*offset*/, DataSink &sink) {
  11201. switch ((*step)++) {
  11202. case 0: sink.write("", 0); break;
  11203. case 1: sink.write("hello", 5); break;
  11204. default: sink.done(); break;
  11205. }
  11206. return true;
  11207. });
  11208. });
  11209. auto port = svr.bind_to_any_port(HOST);
  11210. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11211. auto listen_se = detail::scope_exit([&] {
  11212. svr.stop();
  11213. listen_thread.join();
  11214. ASSERT_FALSE(svr.is_running());
  11215. });
  11216. svr.wait_until_ready();
  11217. Client cli(HOST, port);
  11218. // Without the fix the body is never terminated, so bound the wait rather
  11219. // than letting the test hang on the default read timeout.
  11220. cli.set_read_timeout(5, 0);
  11221. auto res = cli.Get("/stream");
  11222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11223. EXPECT_EQ(StatusCode::OK_200, res->status);
  11224. EXPECT_EQ("hello", res->body);
  11225. }
  11226. TEST(StreamingTest, NoContentLengthStreaming) {
  11227. Server svr;
  11228. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11229. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11230. if (offset < 6) {
  11231. sink.os << (offset < 3 ? "a" : "b");
  11232. } else {
  11233. sink.done();
  11234. }
  11235. return true;
  11236. });
  11237. });
  11238. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11239. auto listen_se = detail::scope_exit([&] {
  11240. svr.stop();
  11241. listen_thread.join();
  11242. ASSERT_FALSE(svr.is_running());
  11243. });
  11244. svr.wait_until_ready();
  11245. Client client(HOST, PORT);
  11246. auto get_thread = std::thread([&client]() {
  11247. std::string s;
  11248. auto res =
  11249. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11250. s += std::string(data, len);
  11251. return true;
  11252. });
  11253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11254. EXPECT_EQ(StatusCode::OK_200, res->status);
  11255. EXPECT_EQ("aaabbb", s);
  11256. });
  11257. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11258. // Give GET time to get a few messages.
  11259. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11260. }
  11261. TEST(MountTest, Unmount) {
  11262. Server svr;
  11263. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11264. auto se = detail::scope_exit([&] {
  11265. svr.stop();
  11266. listen_thread.join();
  11267. ASSERT_FALSE(svr.is_running());
  11268. });
  11269. svr.wait_until_ready();
  11270. Client cli("localhost", PORT);
  11271. svr.set_mount_point("/mount2", "./www2");
  11272. auto res = cli.Get("/");
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11275. res = cli.Get("/mount2/dir/test.html");
  11276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11277. EXPECT_EQ(StatusCode::OK_200, res->status);
  11278. svr.set_mount_point("/", "./www");
  11279. res = cli.Get("/dir/");
  11280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11281. EXPECT_EQ(StatusCode::OK_200, res->status);
  11282. svr.remove_mount_point("/");
  11283. res = cli.Get("/dir/");
  11284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11285. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11286. svr.remove_mount_point("/mount2");
  11287. res = cli.Get("/mount2/dir/test.html");
  11288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11289. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11290. }
  11291. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11292. Server svr;
  11293. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11294. svr.Get("/api/hello", [](const Request &, Response &res) {
  11295. res.set_content("api", "text/plain");
  11296. });
  11297. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. listen_thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli(HOST, PORT);
  11305. auto res = cli.Get("/dir/test.html");
  11306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11307. EXPECT_EQ(StatusCode::OK_200, res->status);
  11308. res = cli.Get("/api/hello");
  11309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11310. EXPECT_EQ(StatusCode::OK_200, res->status);
  11311. EXPECT_EQ("api", res->body);
  11312. }
  11313. TEST(MountTest, PathSegmentBoundary) {
  11314. Server svr;
  11315. svr.set_mount_point("/mount2", "./www2");
  11316. svr.set_mount_point("/", "./www");
  11317. auto port = svr.bind_to_any_port(HOST);
  11318. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11319. auto se = detail::scope_exit([&] {
  11320. svr.stop();
  11321. listen_thread.join();
  11322. ASSERT_FALSE(svr.is_running());
  11323. });
  11324. svr.wait_until_ready();
  11325. Client cli(HOST, port);
  11326. auto res = cli.Get("/mount2/dir/test.html");
  11327. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11328. EXPECT_EQ(StatusCode::OK_200, res->status);
  11329. // "/mount2" must not match part-way through a path segment.
  11330. res = cli.Get("/mount2dir/test.html");
  11331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11332. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11333. // A mount point ending in '/' keeps matching every path below it.
  11334. res = cli.Get("/dir/test.html");
  11335. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11336. EXPECT_EQ(StatusCode::OK_200, res->status);
  11337. }
  11338. TEST(MountTest, Redicect) {
  11339. Server svr;
  11340. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11341. auto se = detail::scope_exit([&] {
  11342. svr.stop();
  11343. listen_thread.join();
  11344. ASSERT_FALSE(svr.is_running());
  11345. });
  11346. svr.set_mount_point("/", "./www");
  11347. svr.wait_until_ready();
  11348. Client cli("localhost", PORT);
  11349. auto res = cli.Get("/dir/");
  11350. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11351. EXPECT_EQ(StatusCode::OK_200, res->status);
  11352. res = cli.Get("/dir");
  11353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11354. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11355. res = cli.Get("/file");
  11356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11357. EXPECT_EQ(StatusCode::OK_200, res->status);
  11358. res = cli.Get("/file/");
  11359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11360. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11361. cli.set_follow_location(true);
  11362. res = cli.Get("/dir");
  11363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11364. EXPECT_EQ(StatusCode::OK_200, res->status);
  11365. }
  11366. TEST(MountTest, MultibytesPathName) {
  11367. Server svr;
  11368. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11369. auto se = detail::scope_exit([&] {
  11370. svr.stop();
  11371. listen_thread.join();
  11372. ASSERT_FALSE(svr.is_running());
  11373. });
  11374. svr.set_mount_point("/", "./www");
  11375. svr.wait_until_ready();
  11376. Client cli("localhost", PORT);
  11377. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11379. EXPECT_EQ(StatusCode::OK_200, res->status);
  11380. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11381. }
  11382. // A mount point serves no path with an empty segment or one ending in '.' or
  11383. // a space, so a guard in the pre-routing handler sees the path of every file
  11384. // that is served
  11385. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11386. Server svr;
  11387. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11388. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11389. if (req.path == "/dir/test.html") {
  11390. res.status = StatusCode::Unauthorized_401;
  11391. return Server::HandlerResponse::Handled;
  11392. }
  11393. return Server::HandlerResponse::Unhandled;
  11394. });
  11395. auto port = svr.bind_to_any_port(HOST);
  11396. ASSERT_LT(0, port);
  11397. thread t = thread([&] { svr.listen_after_bind(); });
  11398. auto se = detail::scope_exit([&] {
  11399. svr.stop();
  11400. t.join();
  11401. ASSERT_FALSE(svr.is_running());
  11402. });
  11403. svr.wait_until_ready();
  11404. Client cli(HOST, port);
  11405. for (auto path :
  11406. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11407. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11408. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11409. "/dir/test.html%3A%3A$DATA"}) {
  11410. SCOPED_TRACE(path);
  11411. auto res = cli.Get(path);
  11412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11413. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11414. }
  11415. }
  11416. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11417. Server svr;
  11418. svr.set_mount_point("/", "./www");
  11419. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11420. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11421. auto port = svr.bind_to_any_port(HOST);
  11422. ASSERT_GT(port, 0);
  11423. thread t = thread([&] { svr.listen_after_bind(); });
  11424. auto se = detail::scope_exit([&] {
  11425. svr.stop();
  11426. t.join();
  11427. ASSERT_FALSE(svr.is_running());
  11428. });
  11429. svr.wait_until_ready();
  11430. Client cli(HOST, port);
  11431. auto res = cli.Get("/dir/test.abcde");
  11432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11433. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11434. res = cli.Get("/dir/test.html");
  11435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11436. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11437. }
  11438. #ifdef _WIN32
  11439. // Issue #2435: mmap::open() must succeed even when another handle holds
  11440. // the file open for writing (e.g. an active log file).
  11441. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11442. const char *path = "mmap_concurrent_writer_test.txt";
  11443. const char *content = "hello";
  11444. {
  11445. std::ofstream f(path, std::ios::binary);
  11446. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11447. }
  11448. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11449. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11450. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11451. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11452. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11453. detail::mmap m(path);
  11454. ASSERT_TRUE(m.is_open());
  11455. EXPECT_EQ(strlen(content), m.size());
  11456. char buf[8];
  11457. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11458. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11459. }
  11460. #endif
  11461. #ifndef _WIN32
  11462. // A directory or a device has no size to serve.
  11463. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11464. const char *path = "./mmap_not_regular_test_dir";
  11465. ASSERT_EQ(0, ::mkdir(path, 0755));
  11466. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11467. for (auto p : {path, "/dev/null"}) {
  11468. detail::mmap m(p);
  11469. EXPECT_FALSE(m.is_open()) << p;
  11470. EXPECT_EQ(0U, m.size()) << p;
  11471. }
  11472. Server svr;
  11473. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11474. res.set_file_content("/dev/null");
  11475. });
  11476. auto port = svr.bind_to_any_port(HOST);
  11477. thread t = thread([&] { svr.listen_after_bind(); });
  11478. auto se = detail::scope_exit([&] {
  11479. svr.stop();
  11480. t.join();
  11481. });
  11482. svr.wait_until_ready();
  11483. auto res = Client(HOST, port).Get("/null");
  11484. ASSERT_TRUE(res);
  11485. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11486. }
  11487. #endif
  11488. #ifdef __linux__
  11489. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11490. TEST(MmapTest, FileIsNotMapped) {
  11491. const char *path = "mmap_not_mapped_test.txt";
  11492. {
  11493. std::ofstream f(path, std::ios::binary);
  11494. f << "hello";
  11495. }
  11496. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11497. detail::mmap m(path);
  11498. ASSERT_TRUE(m.is_open());
  11499. std::ifstream maps("/proc/self/maps");
  11500. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11501. std::istreambuf_iterator<char>());
  11502. EXPECT_EQ(std::string::npos, mappings.find(path));
  11503. }
  11504. #endif
  11505. TEST(KeepAliveTest, ReadTimeout) {
  11506. Server svr;
  11507. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11508. std::this_thread::sleep_for(std::chrono::seconds(2));
  11509. res.set_content("a", "text/plain");
  11510. });
  11511. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11512. res.set_content("b", "text/plain");
  11513. });
  11514. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11515. auto se = detail::scope_exit([&] {
  11516. svr.stop();
  11517. listen_thread.join();
  11518. ASSERT_FALSE(svr.is_running());
  11519. });
  11520. svr.wait_until_ready();
  11521. Client cli("localhost", PORT);
  11522. cli.set_keep_alive(true);
  11523. cli.set_read_timeout(std::chrono::seconds(1));
  11524. auto resa = cli.Get("/a");
  11525. ASSERT_FALSE(resa);
  11526. EXPECT_EQ(Error::Read, resa.error());
  11527. auto resb = cli.Get("/b");
  11528. ASSERT_TRUE(resb);
  11529. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11530. EXPECT_EQ("b", resb->body);
  11531. }
  11532. TEST(KeepAliveTest, MaxCount) {
  11533. size_t keep_alive_max_count = 3;
  11534. Server svr;
  11535. svr.set_keep_alive_max_count(keep_alive_max_count);
  11536. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11537. res.set_content("Hello World!", "text/plain");
  11538. });
  11539. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11540. auto se = detail::scope_exit([&] {
  11541. svr.stop();
  11542. listen_thread.join();
  11543. ASSERT_FALSE(svr.is_running());
  11544. });
  11545. svr.wait_until_ready();
  11546. Client cli(HOST, PORT);
  11547. cli.set_keep_alive(true);
  11548. for (size_t i = 0; i < 5; i++) {
  11549. auto result = cli.Get("/hi");
  11550. ASSERT_TRUE(result);
  11551. EXPECT_EQ(StatusCode::OK_200, result->status);
  11552. if (i == keep_alive_max_count - 1) {
  11553. EXPECT_EQ("close", result->get_header_value("Connection"));
  11554. } else {
  11555. EXPECT_FALSE(result->has_header("Connection"));
  11556. }
  11557. }
  11558. }
  11559. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11560. // can pull the next one into the server's buffer. The server must serve it
  11561. // without waiting for the socket to become readable again. The keep-alive
  11562. // timeout outlasts the client's read timeout, so a request left waiting for it
  11563. // shows up as a missing response.
  11564. static void serve_pipelining_routes(Server &svr,
  11565. const std::function<void(int)> &client) {
  11566. svr.set_keep_alive_timeout(5);
  11567. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11568. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11569. });
  11570. svr.Post("/echo", [](const Request &req, Response &res) {
  11571. res.set_content("echo " + req.body, "text/plain");
  11572. });
  11573. auto port = svr.bind_to_any_port(HOST);
  11574. thread t = thread([&] { svr.listen_after_bind(); });
  11575. auto se = detail::scope_exit([&] {
  11576. svr.stop();
  11577. t.join();
  11578. });
  11579. svr.wait_until_ready();
  11580. client(port);
  11581. }
  11582. static std::string
  11583. send_pipelined_requests(const std::vector<std::string> &parts) {
  11584. Server svr;
  11585. std::string res;
  11586. serve_pipelining_routes(svr, [&](int port) {
  11587. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11588. });
  11589. return res;
  11590. }
  11591. static void expect_in_order(const std::string &res,
  11592. const std::vector<std::string> &bodies) {
  11593. size_t pos = 0;
  11594. for (const auto &body : bodies) {
  11595. pos = res.find(body, pos);
  11596. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11597. pos += body.size();
  11598. }
  11599. }
  11600. TEST(KeepAliveTest, PipelinedRequests) {
  11601. auto res = send_pipelined_requests(
  11602. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11603. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11604. "Content-Length: 4\r\n\r\nbody"
  11605. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11606. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11607. }
  11608. // The second request starts in the server's buffer and ends on the socket.
  11609. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11610. auto res =
  11611. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11612. "GET /hi/2 HTTP/1.1\r\nHo",
  11613. "st: localhost\r\nConnection: close\r\n\r\n"});
  11614. expect_in_order(res, {"hi 1", "hi 2"});
  11615. }
  11616. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11617. // CRLF after a body does not turn into a 400 for the next request.
  11618. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11619. auto res = send_pipelined_requests(
  11620. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11621. "Content-Length: 4\r\n\r\nbody\r\n"
  11622. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11623. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11624. expect_in_order(res, {"echo body", "hi 2"});
  11625. }
  11626. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11627. // must not be served as the next request.
  11628. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11629. auto res = send_pipelined_requests(
  11630. {"INVALID REQUEST LINE\r\n\r\n"
  11631. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11632. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11633. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11634. }
  11635. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11636. // Over TLS, the next request is held by the TLS library as already decrypted
  11637. // data rather than on the socket.
  11638. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11639. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11640. std::string res;
  11641. serve_pipelining_routes(svr, [&](int port) {
  11642. // One part, so all three requests arrive in one TLS record
  11643. EXPECT_TRUE(send_ssl_request_in_parts(
  11644. 2,
  11645. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11646. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11647. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11648. &res, port));
  11649. });
  11650. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11651. }
  11652. #endif
  11653. TEST(KeepAliveTest, Issue1041) {
  11654. Server svr;
  11655. svr.set_keep_alive_timeout(3);
  11656. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11657. res.set_content("Hello World!", "text/plain");
  11658. });
  11659. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11660. auto se = detail::scope_exit([&] {
  11661. svr.stop();
  11662. listen_thread.join();
  11663. ASSERT_FALSE(svr.is_running());
  11664. });
  11665. svr.wait_until_ready();
  11666. Client cli(HOST, PORT);
  11667. cli.set_keep_alive(true);
  11668. auto result = cli.Get("/hi");
  11669. ASSERT_TRUE(result);
  11670. EXPECT_EQ(StatusCode::OK_200, result->status);
  11671. std::this_thread::sleep_for(std::chrono::seconds(5));
  11672. result = cli.Get("/hi");
  11673. ASSERT_TRUE(result);
  11674. EXPECT_EQ(StatusCode::OK_200, result->status);
  11675. }
  11676. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11677. Server svr;
  11678. svr.set_keep_alive_max_count(0);
  11679. std::set<int> remote_ports;
  11680. svr.Get("/hi", [&](const Request &req, Response &res) {
  11681. remote_ports.insert(req.remote_port);
  11682. res.set_content("hi", "text/plain");
  11683. });
  11684. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11685. auto se = detail::scope_exit([&] {
  11686. svr.stop();
  11687. listen_thread.join();
  11688. ASSERT_FALSE(svr.is_running());
  11689. });
  11690. svr.wait_until_ready();
  11691. Client cli(HOST, PORT);
  11692. cli.set_keep_alive(true);
  11693. for (int i = 0; i < 3; i++) {
  11694. auto res = cli.Get("/hi");
  11695. ASSERT_TRUE(res);
  11696. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11697. }
  11698. // All three over one connection
  11699. EXPECT_EQ(1u, remote_ports.size());
  11700. }
  11701. // Forward declaration (see the base64_encode note).
  11702. namespace httplib {
  11703. namespace detail {
  11704. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11705. } // namespace detail
  11706. } // namespace httplib
  11707. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11708. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11709. #ifndef _WIN32
  11710. signal(SIGPIPE, SIG_IGN);
  11711. #endif
  11712. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11713. ASSERT_NE(INVALID_SOCKET, srv);
  11714. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11715. default_socket_options(srv);
  11716. sockaddr_in addr{};
  11717. addr.sin_family = AF_INET;
  11718. addr.sin_port = 0;
  11719. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11720. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11721. ASSERT_EQ(0, ::listen(srv, 2));
  11722. socklen_t addr_len = sizeof(addr);
  11723. ASSERT_EQ(0,
  11724. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11725. auto port = ntohs(addr.sin_port);
  11726. struct Peer {
  11727. socket_t sock = INVALID_SOCKET;
  11728. #ifdef CPPHTTPLIB_SSL_ENABLED
  11729. tls::session_t session = nullptr;
  11730. #endif
  11731. };
  11732. #ifdef CPPHTTPLIB_SSL_ENABLED
  11733. tls::ctx_t ctx = nullptr;
  11734. if (use_tls) {
  11735. ctx = tls::create_server_context();
  11736. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11737. nullptr);
  11738. }
  11739. auto ctx_se = detail::scope_exit([&] {
  11740. if (ctx) { tls::free_context(ctx); }
  11741. });
  11742. #endif
  11743. auto close_peer = [](Peer &peer) {
  11744. #ifdef CPPHTTPLIB_SSL_ENABLED
  11745. if (peer.session) { tls::free_session(peer.session); }
  11746. #endif
  11747. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11748. };
  11749. auto accept_peer = [&]() {
  11750. Peer peer;
  11751. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11752. peer.sock = ::accept(srv, nullptr, nullptr);
  11753. if (peer.sock == INVALID_SOCKET) { return peer; }
  11754. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11755. #ifdef CPPHTTPLIB_SSL_ENABLED
  11756. if (use_tls) {
  11757. peer.session = tls::create_session(ctx, peer.sock);
  11758. tls::TlsError err;
  11759. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11760. nullptr)) {
  11761. close_peer(peer);
  11762. return Peer();
  11763. }
  11764. }
  11765. #endif
  11766. return peer;
  11767. };
  11768. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11769. #ifdef CPPHTTPLIB_SSL_ENABLED
  11770. tls::TlsError err;
  11771. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11772. #endif
  11773. return detail::read_socket(peer.sock, buf, len, 0);
  11774. };
  11775. auto read_head = [&](const Peer &peer) {
  11776. std::string head;
  11777. char buf[1024];
  11778. while (head.find("\r\n\r\n") == std::string::npos) {
  11779. auto n = read_some(peer, buf, sizeof(buf));
  11780. if (n <= 0) { break; }
  11781. head.append(buf, static_cast<size_t>(n));
  11782. }
  11783. };
  11784. auto send_text = [](const Peer &peer, const std::string &text) {
  11785. #ifdef CPPHTTPLIB_SSL_ENABLED
  11786. tls::TlsError err;
  11787. if (peer.session) {
  11788. tls::write(peer.session, text.data(), text.size(), err);
  11789. return;
  11790. }
  11791. #endif
  11792. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11793. };
  11794. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11795. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11796. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11797. // Sent once the first response is read, so that it lands on an idle socket
  11798. std::promise<void> first_response_read;
  11799. auto first_response_read_future = first_response_read.get_future();
  11800. auto server_thread = std::thread([&] {
  11801. auto peer1 = accept_peer();
  11802. if (peer1.sock == INVALID_SOCKET) { return; }
  11803. read_head(peer1);
  11804. if (same_write) {
  11805. send_text(peer1, first + stray);
  11806. } else {
  11807. send_text(peer1, first);
  11808. first_response_read_future.wait_for(std::chrono::seconds(5));
  11809. send_text(peer1, stray);
  11810. }
  11811. // peer1 stays open, so only the unread data can tell the client
  11812. auto peer2 = accept_peer();
  11813. if (peer2.sock != INVALID_SOCKET) {
  11814. read_head(peer2);
  11815. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11816. "Connection: close\r\n\r\nsecond");
  11817. close_peer(peer2);
  11818. }
  11819. close_peer(peer1);
  11820. });
  11821. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11822. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11823. std::to_string(port));
  11824. #ifdef CPPHTTPLIB_SSL_ENABLED
  11825. cli.enable_server_certificate_verification(false);
  11826. #endif
  11827. cli.set_keep_alive(true);
  11828. cli.set_read_timeout(5, 0);
  11829. auto res = cli.Get("/1");
  11830. first_response_read.set_value();
  11831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11832. EXPECT_EQ("first", res->body);
  11833. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11834. res = cli.Get("/2");
  11835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11836. EXPECT_EQ(StatusCode::OK_200, res->status);
  11837. EXPECT_EQ("second", res->body);
  11838. }
  11839. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11840. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11841. }
  11842. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11843. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11844. }
  11845. #ifdef CPPHTTPLIB_SSL_ENABLED
  11846. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11847. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11848. }
  11849. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11850. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11851. }
  11852. #endif
  11853. TEST(KeepAliveTest, Issue1959) {
  11854. Server svr;
  11855. svr.set_keep_alive_timeout(5);
  11856. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11857. res.set_content("a", "text/plain");
  11858. });
  11859. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11860. auto se = detail::scope_exit([&] {
  11861. if (!svr.is_running()) return;
  11862. svr.stop();
  11863. listen_thread.join();
  11864. ASSERT_FALSE(svr.is_running());
  11865. });
  11866. svr.wait_until_ready();
  11867. Client cli("localhost", PORT);
  11868. cli.set_keep_alive(true);
  11869. using namespace std::chrono;
  11870. auto start = steady_clock::now();
  11871. cli.Get("/a");
  11872. svr.stop();
  11873. listen_thread.join();
  11874. auto end = steady_clock::now();
  11875. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11876. EXPECT_LT(elapsed, 5000);
  11877. }
  11878. #ifdef CPPHTTPLIB_SSL_ENABLED
  11879. TEST(KeepAliveTest, SSLClientReconnection) {
  11880. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11881. ASSERT_TRUE(svr.is_valid());
  11882. svr.set_keep_alive_timeout(1);
  11883. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11884. res.set_content("Hello World!", "text/plain");
  11885. });
  11886. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11887. auto se = detail::scope_exit([&] {
  11888. svr.stop();
  11889. listen_thread.join();
  11890. ASSERT_FALSE(svr.is_running());
  11891. });
  11892. svr.wait_until_ready();
  11893. SSLClient cli(HOST, PORT);
  11894. cli.enable_server_certificate_verification(false);
  11895. cli.set_keep_alive(true);
  11896. auto result = cli.Get("/hi");
  11897. ASSERT_TRUE(result);
  11898. EXPECT_EQ(StatusCode::OK_200, result->status);
  11899. result = cli.Get("/hi");
  11900. ASSERT_TRUE(result);
  11901. EXPECT_EQ(StatusCode::OK_200, result->status);
  11902. std::this_thread::sleep_for(std::chrono::seconds(2));
  11903. // Recoonect
  11904. result = cli.Get("/hi");
  11905. ASSERT_TRUE(result);
  11906. EXPECT_EQ(StatusCode::OK_200, result->status);
  11907. result = cli.Get("/hi");
  11908. ASSERT_TRUE(result);
  11909. EXPECT_EQ(StatusCode::OK_200, result->status);
  11910. }
  11911. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11912. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11913. ASSERT_TRUE(svr.is_valid());
  11914. svr.set_keep_alive_timeout(1);
  11915. std::string content = "reconnect";
  11916. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11917. res.set_content("Hello World!", "text/plain");
  11918. });
  11919. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  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. SSLClient cli(HOST, PORT);
  11927. cli.enable_server_certificate_verification(false);
  11928. cli.set_keep_alive(true);
  11929. auto result = cli.Post(
  11930. "/hi", content.size(),
  11931. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11932. sink.write(content.c_str(), content.size());
  11933. return true;
  11934. },
  11935. "text/plain");
  11936. ASSERT_TRUE(result);
  11937. EXPECT_EQ(200, result->status);
  11938. std::this_thread::sleep_for(std::chrono::seconds(2));
  11939. // Recoonect
  11940. result = cli.Post(
  11941. "/hi", content.size(),
  11942. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11943. sink.write(content.c_str(), content.size());
  11944. return true;
  11945. },
  11946. "text/plain");
  11947. ASSERT_TRUE(result);
  11948. EXPECT_EQ(200, result->status);
  11949. result = cli.Post(
  11950. "/hi", content.size(),
  11951. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11952. sink.write(content.c_str(), content.size());
  11953. return true;
  11954. },
  11955. "text/plain");
  11956. ASSERT_TRUE(result);
  11957. EXPECT_EQ(200, result->status);
  11958. }
  11959. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11960. using namespace httplib::tls;
  11961. {
  11962. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11963. ASSERT_TRUE(svr.is_valid());
  11964. svr.Get("/sni", [&](const Request &req, Response &res) {
  11965. std::string expected = req.sni();
  11966. EXPECT_EQ(expected, req.get_param_value("expected"));
  11967. res.set_content("ok", "text/plain");
  11968. });
  11969. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11970. auto se = detail::scope_exit([&] {
  11971. svr.stop();
  11972. listen_thread.join();
  11973. ASSERT_FALSE(svr.is_running());
  11974. });
  11975. svr.wait_until_ready();
  11976. {
  11977. SSLClient cli("localhost", PORT);
  11978. cli.enable_server_certificate_verification(false);
  11979. auto res = cli.Get("/sni?expected=localhost");
  11980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11981. }
  11982. {
  11983. SSLClient cli("::1", PORT);
  11984. cli.enable_server_certificate_verification(false);
  11985. auto res = cli.Get("/sni?expected=");
  11986. // NOTE: This may fail if the server is listening on IPv4 only
  11987. // (e.g., when localhost resolves to 127.0.0.1 only)
  11988. if (res) {
  11989. EXPECT_EQ(StatusCode::OK_200, res->status);
  11990. } else {
  11991. EXPECT_EQ(Error::Connection, res.error());
  11992. }
  11993. }
  11994. }
  11995. }
  11996. // The SNI of a failed handshake does not reach the next connection that the
  11997. // same worker thread serves
  11998. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11999. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12000. ASSERT_TRUE(svr.is_valid());
  12001. svr.new_task_queue = [] { return new ThreadPool(1); };
  12002. svr.Get("/sni", [](const Request &req, Response &res) {
  12003. res.set_content(req.sni(), "text/plain");
  12004. });
  12005. auto port = svr.bind_to_any_port("127.0.0.1");
  12006. ASSERT_LT(0, port);
  12007. thread t = thread([&] { svr.listen_after_bind(); });
  12008. auto se = detail::scope_exit([&] {
  12009. svr.stop();
  12010. t.join();
  12011. ASSERT_FALSE(svr.is_running());
  12012. });
  12013. svr.wait_until_ready();
  12014. {
  12015. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12016. SSLClient cli("localhost", port);
  12017. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12018. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12019. auto res = cli.Get("/sni");
  12020. ASSERT_FALSE(res);
  12021. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12022. }
  12023. // An IP host sends no SNI (RFC 6066)
  12024. SSLClient cli("127.0.0.1", port);
  12025. cli.enable_server_certificate_verification(false);
  12026. auto res = cli.Get("/sni");
  12027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12028. EXPECT_EQ("", res->body);
  12029. }
  12030. #endif
  12031. TEST(ClientProblemDetectionTest, ContentProvider) {
  12032. Server svr;
  12033. size_t content_length = 1024 * 1024;
  12034. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12035. res.set_content_provider(
  12036. content_length, "text/plain",
  12037. [&](size_t offset, size_t length, DataSink &sink) {
  12038. auto out_len = std::min(length, static_cast<size_t>(1024));
  12039. std::string out(out_len, '@');
  12040. sink.write(out.data(), out_len);
  12041. return offset < 4096;
  12042. },
  12043. [](bool success) { ASSERT_FALSE(success); });
  12044. });
  12045. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12046. res.set_content_provider(
  12047. 0, "text/plain",
  12048. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12049. EXPECT_TRUE(false);
  12050. return true;
  12051. },
  12052. [](bool success) { ASSERT_FALSE(success); });
  12053. });
  12054. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12055. auto se = detail::scope_exit([&] {
  12056. svr.stop();
  12057. listen_thread.join();
  12058. ASSERT_FALSE(svr.is_running());
  12059. });
  12060. svr.wait_until_ready();
  12061. Client cli("localhost", PORT);
  12062. {
  12063. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12064. size_t /*data_length*/) { return false; });
  12065. ASSERT_FALSE(res);
  12066. }
  12067. {
  12068. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12069. size_t /*data_length*/) { return false; });
  12070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12071. }
  12072. }
  12073. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12074. // A provider that reports success without writing anything and without
  12075. // calling done() used to be handed the same offset and length again on every
  12076. // pass, so it spun for as long as the peer stayed connected.
  12077. Server svr;
  12078. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12079. res.set_content("ok", "text/plain");
  12080. });
  12081. auto port = svr.bind_to_any_port(HOST);
  12082. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12083. auto se = detail::scope_exit([&] {
  12084. svr.stop();
  12085. listen_thread.join();
  12086. ASSERT_FALSE(svr.is_running());
  12087. });
  12088. svr.wait_until_ready();
  12089. std::atomic<int> call_count{0};
  12090. Client cli(HOST, port);
  12091. auto res = cli.Post(
  12092. "/", 1024,
  12093. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12094. // Give up after enough passes to show the spin, so that losing the
  12095. // check below fails this test instead of hanging it.
  12096. return ++call_count < 100;
  12097. },
  12098. "text/plain");
  12099. ASSERT_FALSE(res);
  12100. EXPECT_EQ(Error::Write, res.error());
  12101. EXPECT_EQ(1, call_count.load());
  12102. }
  12103. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12104. // A writer only has to assign `write`. The other three used to be left as
  12105. // empty std::functions, so a provider calling one threw
  12106. // std::bad_function_call out of the thread running it and took the whole
  12107. // process down.
  12108. DataSink sink;
  12109. std::string written;
  12110. sink.write = [&](const char *data, size_t data_len) {
  12111. written.append(data, data_len);
  12112. return true;
  12113. };
  12114. EXPECT_TRUE(sink.is_writable());
  12115. sink.done();
  12116. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12117. EXPECT_TRUE(written.empty());
  12118. }
  12119. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12120. // A sink that cannot carry trailers still has to finish.
  12121. DataSink sink;
  12122. auto done_count = 0;
  12123. sink.done = [&]() { done_count++; };
  12124. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12125. EXPECT_EQ(1, done_count);
  12126. }
  12127. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12128. Server svr;
  12129. const std::string body(4096, 'x');
  12130. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12131. res.set_content_provider(body.size(), "text/plain",
  12132. [&](size_t offset, size_t length, DataSink &sink) {
  12133. sink.write(body.data() + offset, length);
  12134. sink.done();
  12135. return true;
  12136. });
  12137. });
  12138. auto port = svr.bind_to_any_port(HOST);
  12139. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12140. auto se = detail::scope_exit([&] {
  12141. svr.stop();
  12142. listen_thread.join();
  12143. ASSERT_FALSE(svr.is_running());
  12144. });
  12145. svr.wait_until_ready();
  12146. Client cli(HOST, port);
  12147. auto res = cli.Get("/");
  12148. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12149. EXPECT_EQ(StatusCode::OK_200, res->status);
  12150. EXPECT_EQ(body, res->body);
  12151. }
  12152. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12153. Server svr;
  12154. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12155. res.set_content_provider(
  12156. 1024, "text/plain",
  12157. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12158. sink.write("hello", 5);
  12159. sink.done(); // short of the 1024 bytes the response promised
  12160. return true;
  12161. });
  12162. });
  12163. auto port = svr.bind_to_any_port(HOST);
  12164. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12165. auto se = detail::scope_exit([&] {
  12166. svr.stop();
  12167. listen_thread.join();
  12168. ASSERT_FALSE(svr.is_running());
  12169. });
  12170. svr.wait_until_ready();
  12171. Client cli(HOST, port);
  12172. cli.set_read_timeout(5, 0);
  12173. // The response is short of its Content-Length, so the client cannot read a
  12174. // complete body. What matters is that this returns at all: a no-op done()
  12175. // would leave the writer looping over a provider that never makes progress.
  12176. auto res = cli.Get("/");
  12177. EXPECT_FALSE(res);
  12178. }
  12179. // Read as the next response by a peer that sees it after a framed body.
  12180. static const std::string smuggled_response =
  12181. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12182. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12183. Server svr;
  12184. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12185. res.set_content_provider(
  12186. 5, "text/plain",
  12187. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12188. auto data = "AAAAA" + smuggled_response;
  12189. sink.write(data.data(), data.size());
  12190. return true;
  12191. });
  12192. });
  12193. thread t = thread([&] { svr.listen(HOST, PORT); });
  12194. auto se = detail::scope_exit([&] {
  12195. svr.stop();
  12196. t.join();
  12197. ASSERT_FALSE(svr.is_running());
  12198. });
  12199. svr.wait_until_ready();
  12200. std::string resp;
  12201. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12202. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12203. resp.clear();
  12204. ASSERT_TRUE(send_request(
  12205. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12206. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12207. }
  12208. TEST(NoContentTest, BodyIsNotSent) {
  12209. Server svr;
  12210. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12211. res.status = StatusCode::NoContent_204;
  12212. res.set_content(smuggled_response, "text/plain");
  12213. });
  12214. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12215. res.status = StatusCode::NotModified_304;
  12216. res.set_chunked_content_provider(
  12217. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12218. sink.write(smuggled_response.data(), smuggled_response.size());
  12219. sink.done();
  12220. return true;
  12221. });
  12222. });
  12223. thread t = thread([&] { svr.listen(HOST, PORT); });
  12224. auto se = detail::scope_exit([&] {
  12225. svr.stop();
  12226. t.join();
  12227. ASSERT_FALSE(svr.is_running());
  12228. });
  12229. svr.wait_until_ready();
  12230. for (auto path : {"/204", "/304"}) {
  12231. std::string resp;
  12232. ASSERT_TRUE(send_request(
  12233. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12234. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12235. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12236. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12237. }
  12238. }
  12239. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12240. Server svr;
  12241. std::atomic<bool> smuggled(false);
  12242. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12243. res.set_content("ok", "text/plain");
  12244. });
  12245. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12246. smuggled = true;
  12247. });
  12248. auto port = svr.bind_to_any_port(HOST);
  12249. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12250. auto se = detail::scope_exit([&] {
  12251. svr.stop();
  12252. listen_thread.join();
  12253. ASSERT_FALSE(svr.is_running());
  12254. });
  12255. svr.wait_until_ready();
  12256. // What follows the body would be read as the next request.
  12257. Client cli(HOST, port);
  12258. auto res = cli.Post(
  12259. "/", 5,
  12260. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12261. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12262. sink.write(data.data(), data.size());
  12263. return true;
  12264. },
  12265. "text/plain");
  12266. ASSERT_FALSE(res);
  12267. EXPECT_EQ(Error::Write, res.error());
  12268. EXPECT_FALSE(smuggled);
  12269. }
  12270. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12271. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12272. // The compressed path builds the whole body before connecting, so this
  12273. // fails client-side and never reaches a server.
  12274. Client cli(HOST, PORT);
  12275. cli.set_compress(true);
  12276. auto res = cli.Post(
  12277. "/", 1024,
  12278. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12279. sink.write("hello", 5);
  12280. sink.done(); // short of the 1024 bytes the request announced
  12281. return true;
  12282. },
  12283. "text/plain");
  12284. ASSERT_FALSE(res);
  12285. EXPECT_EQ(Error::Write, res.error());
  12286. }
  12287. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12288. Server svr;
  12289. std::string received;
  12290. size_t content_length_count = 0;
  12291. bool has_transfer_encoding = true;
  12292. svr.Post("/echo", [&](const Request &req, Response &res) {
  12293. received = req.body;
  12294. content_length_count = req.get_header_value_count("Content-Length");
  12295. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12296. res.set_content("ok", "text/plain");
  12297. });
  12298. svr.Get("/next", [](const Request &, Response &res) {
  12299. res.set_content("next", "text/plain");
  12300. });
  12301. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12302. auto se = detail::scope_exit([&] {
  12303. svr.stop();
  12304. listen_thread.join();
  12305. ASSERT_FALSE(svr.is_running());
  12306. });
  12307. svr.wait_until_ready();
  12308. Client cli(HOST, PORT);
  12309. cli.set_keep_alive(true);
  12310. cli.set_compress(true);
  12311. const std::string body = "hello world";
  12312. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12313. auto res = cli.Post("/echo", headers, body, "text/plain");
  12314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12315. EXPECT_EQ(StatusCode::OK_200, res->status);
  12316. EXPECT_EQ(body, received);
  12317. EXPECT_EQ(1u, content_length_count);
  12318. EXPECT_FALSE(has_transfer_encoding);
  12319. // The rest of a truncated body would be read as this request
  12320. auto res2 = cli.Get("/next");
  12321. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12322. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12323. EXPECT_EQ("next", res2->body);
  12324. }
  12325. #endif
  12326. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12327. Server svr;
  12328. std::string received;
  12329. size_t content_length_count = 1;
  12330. bool has_transfer_encoding = false;
  12331. svr.Post("/echo", [&](const Request &req, Response &res) {
  12332. received = req.body;
  12333. content_length_count = req.get_header_value_count("Content-Length");
  12334. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12335. res.set_content("ok", "text/plain");
  12336. });
  12337. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12338. auto se = detail::scope_exit([&] {
  12339. svr.stop();
  12340. listen_thread.join();
  12341. ASSERT_FALSE(svr.is_running());
  12342. });
  12343. svr.wait_until_ready();
  12344. Client cli(HOST, PORT);
  12345. cli.set_keep_alive(true);
  12346. const std::string body = "hello world";
  12347. Headers headers = {{"Content-Length", "5"}};
  12348. auto res = cli.Post(
  12349. "/echo", headers,
  12350. [&](size_t /*offset*/, DataSink &sink) {
  12351. sink.write(body.data(), body.size());
  12352. sink.done();
  12353. return true;
  12354. },
  12355. "text/plain");
  12356. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12357. EXPECT_EQ(StatusCode::OK_200, res->status);
  12358. EXPECT_EQ(body, received);
  12359. EXPECT_EQ(0u, content_length_count);
  12360. EXPECT_TRUE(has_transfer_encoding);
  12361. }
  12362. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12363. Server svr;
  12364. svr.set_error_handler([](Request const &, Response &res) -> void {
  12365. res.set_chunked_content_provider(
  12366. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12367. sink.os << "hello";
  12368. sink.os << "world";
  12369. sink.done();
  12370. return true;
  12371. });
  12372. });
  12373. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12374. auto se = detail::scope_exit([&] {
  12375. svr.stop();
  12376. listen_thread.join();
  12377. ASSERT_FALSE(svr.is_running());
  12378. });
  12379. svr.wait_until_ready();
  12380. Client cli("localhost", PORT);
  12381. auto res = cli.Get("/");
  12382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12383. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12384. EXPECT_EQ("helloworld", res->body);
  12385. }
  12386. // A body set after a content provider must replace it, not be sent through it.
  12387. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12388. Server svr;
  12389. svr.set_mount_point("/", "./www");
  12390. svr.set_file_request_handler([](const Request &req, Response &res) {
  12391. if (req.path == "/dir/test.html") {
  12392. res.status = StatusCode::Forbidden_403;
  12393. res.set_content(std::string(5000, 'D'), "text/plain");
  12394. } else if (req.path == "/file") {
  12395. res.status = StatusCode::Forbidden_403;
  12396. res.body = "Denied";
  12397. }
  12398. });
  12399. auto port = svr.bind_to_any_port(HOST);
  12400. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12401. auto se = detail::scope_exit([&] {
  12402. svr.stop();
  12403. t.join();
  12404. ASSERT_FALSE(svr.is_running());
  12405. });
  12406. svr.wait_until_ready();
  12407. Client cli(HOST, port);
  12408. {
  12409. auto res = cli.Get("/dir/test.html");
  12410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12411. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12412. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12413. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12414. }
  12415. {
  12416. auto res = cli.Get("/file");
  12417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12418. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12419. EXPECT_EQ("Denied", res->body);
  12420. }
  12421. {
  12422. auto res = cli.Get("/dir/index.html");
  12423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12424. EXPECT_EQ(StatusCode::OK_200, res->status);
  12425. EXPECT_EQ(0U, res->body.find("<html>"));
  12426. }
  12427. }
  12428. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12429. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12430. Server svr;
  12431. std::vector<bool> released;
  12432. std::mutex released_mutex;
  12433. auto releaser = [&](bool success) {
  12434. std::lock_guard<std::mutex> guard(released_mutex);
  12435. released.push_back(success);
  12436. };
  12437. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12438. return sink.write(&"hello"[offset], length);
  12439. };
  12440. svr.Get("/sized", [&](const Request &, Response &res) {
  12441. res.status = StatusCode::NotFound_404;
  12442. res.set_content_provider(5, "text/plain", provider, releaser);
  12443. });
  12444. svr.Get("/chunked", [&](const Request &, Response &res) {
  12445. res.status = StatusCode::ServiceUnavailable_503;
  12446. res.set_chunked_content_provider(
  12447. "text/plain",
  12448. [](size_t, DataSink &sink) {
  12449. sink.os << "chunk";
  12450. sink.done();
  12451. return true;
  12452. },
  12453. releaser);
  12454. });
  12455. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12456. res.set_content_provider(5, "text/plain", provider, releaser);
  12457. throw std::runtime_error("after the provider");
  12458. });
  12459. svr.set_error_handler([](const Request &req, Response &res) {
  12460. // Leave the exception handler's content to it.
  12461. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12462. res.set_content(std::string(1000, 'E'), "text/html");
  12463. return Server::HandlerResponse::Handled;
  12464. });
  12465. svr.set_exception_handler(
  12466. [](const Request &, Response &res, std::exception_ptr) {
  12467. res.status = StatusCode::InternalServerError_500;
  12468. res.set_content(std::string(1000, 'X'), "text/html");
  12469. });
  12470. auto port = svr.bind_to_any_port(HOST);
  12471. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12472. auto se = detail::scope_exit([&] {
  12473. svr.stop();
  12474. t.join();
  12475. ASSERT_FALSE(svr.is_running());
  12476. });
  12477. svr.wait_until_ready();
  12478. Client cli(HOST, port);
  12479. {
  12480. auto res = cli.Get("/sized");
  12481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12483. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12484. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12485. }
  12486. {
  12487. auto res = cli.Get("/chunked");
  12488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12489. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12490. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12491. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12492. }
  12493. {
  12494. auto res = cli.Get("/throw");
  12495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12496. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12497. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12498. }
  12499. std::lock_guard<std::mutex> guard(released_mutex);
  12500. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12501. }
  12502. #endif
  12503. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12504. Server svr;
  12505. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12506. return sink.write(&"abc"[offset], length);
  12507. };
  12508. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12509. res.set_file_content("./www/dir/test.html");
  12510. res.set_content("body", "text/plain");
  12511. });
  12512. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12513. res.set_content(std::string(100, 'B'), "text/plain");
  12514. res.set_file_content("./www/dir/test.html");
  12515. });
  12516. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12517. res.set_content(std::string(100, 'B'), "text/plain");
  12518. res.set_content_provider(3, "text/x-provider", abc);
  12519. });
  12520. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12521. res.set_content_provider(3, "text/x-provider", abc);
  12522. res.set_content(std::string(100, 'B'), "text/plain");
  12523. });
  12524. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12525. res.set_content_provider(3, "text/x-provider", abc);
  12526. res.set_file_content("./www/dir/test.html", "text/x-file");
  12527. });
  12528. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12529. res.set_file_content("./www/dir/test.html");
  12530. res.set_header("Content-Type", "text/x-handler");
  12531. });
  12532. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12533. res.set_content_provider(3, "text/plain", abc);
  12534. res.body = "direct";
  12535. });
  12536. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12537. res.set_file_content("./www/dir/test.html");
  12538. res.body = "direct";
  12539. });
  12540. auto port = svr.bind_to_any_port(HOST);
  12541. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12542. auto se = detail::scope_exit([&] {
  12543. svr.stop();
  12544. t.join();
  12545. ASSERT_FALSE(svr.is_running());
  12546. });
  12547. svr.wait_until_ready();
  12548. Client cli(HOST, port);
  12549. auto expect_body = [&](const char *path, const std::string &body,
  12550. const std::string &type) {
  12551. // Uncompressed, so Content-Length can be compared with the body.
  12552. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12553. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12554. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12555. EXPECT_EQ(body, res->body) << path;
  12556. EXPECT_EQ(std::to_string(body.size()),
  12557. res->get_header_value("Content-Length"))
  12558. << path;
  12559. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12560. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12561. };
  12562. expect_body("/file-then-body", "body", "text/plain");
  12563. expect_body("/body-then-file", "test.html", "text/html");
  12564. expect_body("/body-then-provider", "abc", "text/x-provider");
  12565. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12566. expect_body("/provider-then-file", "test.html", "text/x-file");
  12567. expect_body("/file-then-header", "test.html", "text/x-handler");
  12568. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12569. expect_body("/file-then-direct-body", "direct", "text/plain");
  12570. // Ranges are checked against the body, not the dropped provider.
  12571. {
  12572. auto res = cli.Get("/provider-then-direct-body",
  12573. Headers{{make_range_header({{1, 2}})}});
  12574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12575. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12576. EXPECT_EQ("ir", res->body);
  12577. }
  12578. {
  12579. auto res = cli.Get("/file-then-direct-body",
  12580. Headers{{make_range_header({{7, 8}})}});
  12581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12582. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12583. }
  12584. }
  12585. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12586. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12587. const char *path = "./truncated_while_served.txt";
  12588. const size_t size = 32 * 1024 * 1024;
  12589. {
  12590. std::ofstream f(path, std::ios::binary);
  12591. f << std::string(size, 'x');
  12592. }
  12593. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12594. // Over TLS, where the bytes are encrypted in this process rather than
  12595. // copied by send().
  12596. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12597. svr.Get("/file", [&](const Request &, Response &res) {
  12598. res.set_file_content(path, "text/plain");
  12599. });
  12600. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12601. auto se = detail::scope_exit([&] {
  12602. svr.stop();
  12603. thread.join();
  12604. ASSERT_FALSE(svr.is_running());
  12605. });
  12606. svr.wait_until_ready();
  12607. // The file shrinks once the first bytes are in, as a rewrite in place
  12608. // would, and reading the mapping past its new end used to raise SIGBUS.
  12609. SSLClient cli(HOST, PORT);
  12610. cli.enable_server_certificate_verification(false);
  12611. size_t received = 0;
  12612. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12613. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12614. received += len;
  12615. return true;
  12616. });
  12617. EXPECT_FALSE(res);
  12618. EXPECT_LT(received, size);
  12619. }
  12620. #endif
  12621. // Forward declaration (see the base64_encode note).
  12622. namespace httplib {
  12623. namespace detail {
  12624. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12625. const std::string &content_type,
  12626. EncodingType encoding);
  12627. } // namespace detail
  12628. } // namespace httplib
  12629. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12630. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12631. ASSERT_TRUE(mm->is_open());
  12632. Response res;
  12633. detail::set_file_content_provider(res, mm, "text/html",
  12634. detail::EncodingType::None);
  12635. std::string out;
  12636. DataSink sink;
  12637. sink.write = [&](const char *d, size_t l) {
  12638. out.append(d, l);
  12639. return true;
  12640. };
  12641. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12642. EXPECT_EQ("test.html", out);
  12643. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12644. EXPECT_EQ("test.html", out);
  12645. }
  12646. TEST(LongPollingTest, ClientCloseDetection) {
  12647. Server svr;
  12648. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12649. res.set_chunked_content_provider(
  12650. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12651. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12652. sink.os << "hello";
  12653. auto count = 10;
  12654. while (count > 0 && sink.is_writable()) {
  12655. this_thread::sleep_for(chrono::milliseconds(10));
  12656. count--;
  12657. }
  12658. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12659. return true;
  12660. });
  12661. });
  12662. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12663. auto se = detail::scope_exit([&] {
  12664. svr.stop();
  12665. listen_thread.join();
  12666. ASSERT_FALSE(svr.is_running());
  12667. });
  12668. svr.wait_until_ready();
  12669. Client cli("localhost", PORT);
  12670. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12671. EXPECT_EQ("hello", string(data, data_length));
  12672. return false; // close the socket immediately.
  12673. });
  12674. ASSERT_FALSE(res);
  12675. }
  12676. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12677. Server svr;
  12678. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12679. res.set_chunked_content_provider(
  12680. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12681. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12682. sink.os << "hello";
  12683. EXPECT_TRUE(sink.os.good());
  12684. // Wait for the client to close the connection
  12685. auto count = 10;
  12686. while (count > 0 && sink.is_writable()) {
  12687. this_thread::sleep_for(chrono::milliseconds(10));
  12688. count--;
  12689. }
  12690. // After client disconnect, write repeatedly until the socket
  12691. // write actually fails (small writes may be absorbed by the
  12692. // kernel buffer)
  12693. std::string chunk(1024, 'x');
  12694. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12695. sink.os << chunk;
  12696. }
  12697. EXPECT_TRUE(sink.os.fail());
  12698. return true;
  12699. });
  12700. });
  12701. auto port = svr.bind_to_any_port("localhost");
  12702. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12703. auto se = detail::scope_exit([&] {
  12704. svr.stop();
  12705. listen_thread.join();
  12706. ASSERT_FALSE(svr.is_running());
  12707. });
  12708. svr.wait_until_ready();
  12709. Client cli("localhost", port);
  12710. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12711. EXPECT_EQ("hello", string(data, data_length));
  12712. return false; // close the socket immediately.
  12713. });
  12714. ASSERT_FALSE(res);
  12715. }
  12716. TEST(GetWithParametersTest, GetWithParameters) {
  12717. Server svr;
  12718. svr.Get("/", [&](const Request &req, Response &) {
  12719. EXPECT_EQ("world", req.get_param_value("hello"));
  12720. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12721. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12722. });
  12723. svr.Get("/params", [&](const Request &req, Response &) {
  12724. EXPECT_EQ("world", req.get_param_value("hello"));
  12725. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12726. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12727. });
  12728. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12729. EXPECT_EQ("resource-id", req.matches[1]);
  12730. EXPECT_EQ("foo", req.get_param_value("param1"));
  12731. EXPECT_EQ("bar", req.get_param_value("param2"));
  12732. });
  12733. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12734. EXPECT_EQ("user-id", req.path_params.at("id"));
  12735. EXPECT_EQ("foo", req.get_param_value("param1"));
  12736. EXPECT_EQ("bar", req.get_param_value("param2"));
  12737. });
  12738. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12739. auto se = detail::scope_exit([&] {
  12740. svr.stop();
  12741. listen_thread.join();
  12742. ASSERT_FALSE(svr.is_running());
  12743. });
  12744. svr.wait_until_ready();
  12745. {
  12746. Client cli(HOST, PORT);
  12747. Params params;
  12748. params.emplace("hello", "world");
  12749. params.emplace("hello2", "world2");
  12750. params.emplace("hello3", "world3");
  12751. auto res = cli.Get("/", params, Headers{});
  12752. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12753. EXPECT_EQ(StatusCode::OK_200, res->status);
  12754. }
  12755. {
  12756. Client cli(HOST, PORT);
  12757. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12759. EXPECT_EQ(StatusCode::OK_200, res->status);
  12760. }
  12761. {
  12762. Client cli(HOST, PORT);
  12763. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12765. EXPECT_EQ(StatusCode::OK_200, res->status);
  12766. }
  12767. {
  12768. Client cli(HOST, PORT);
  12769. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12771. EXPECT_EQ(StatusCode::OK_200, res->status);
  12772. }
  12773. }
  12774. TEST(GetWithParametersTest, GetWithParameters2) {
  12775. Server svr;
  12776. svr.Get("/", [&](const Request &req, Response &res) {
  12777. auto text = req.get_param_value("hello");
  12778. res.set_content(text, "text/plain");
  12779. });
  12780. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12781. auto se = detail::scope_exit([&] {
  12782. svr.stop();
  12783. listen_thread.join();
  12784. ASSERT_FALSE(svr.is_running());
  12785. });
  12786. svr.wait_until_ready();
  12787. Client cli("localhost", PORT);
  12788. Params params;
  12789. params.emplace("hello", "world");
  12790. std::string body;
  12791. auto res = cli.Get("/", params, Headers{},
  12792. [&](const char *data, size_t data_length) {
  12793. body.append(data, data_length);
  12794. return true;
  12795. });
  12796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12797. EXPECT_EQ(StatusCode::OK_200, res->status);
  12798. EXPECT_EQ("world", body);
  12799. }
  12800. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12801. Server svr;
  12802. svr.Get("/search", [&](const Request &req, Response &res) {
  12803. auto q = req.get_param_value("q");
  12804. res.set_content(q, "text/plain");
  12805. });
  12806. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12807. auto se = detail::scope_exit([&] {
  12808. svr.stop();
  12809. listen_thread.join();
  12810. ASSERT_FALSE(svr.is_running());
  12811. });
  12812. svr.wait_until_ready();
  12813. Client cli("localhost", PORT);
  12814. // Verify that Get(path, params) works without requiring Headers argument
  12815. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12817. EXPECT_EQ(StatusCode::OK_200, res->status);
  12818. EXPECT_EQ("cpp-httplib", res->body);
  12819. }
  12820. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12821. auto host = "httpbingo.org";
  12822. auto path = std::string{"/range/32"};
  12823. #ifdef CPPHTTPLIB_SSL_ENABLED
  12824. SSLClient cli(host);
  12825. #else
  12826. Client cli(host);
  12827. #endif
  12828. cli.set_default_headers({make_range_header({{1, 10}})});
  12829. cli.set_connection_timeout(5);
  12830. {
  12831. auto res = retry_service_failures([&] { return cli.Get(path); });
  12832. SKIP_ON_SERVICE_FAILURE(res);
  12833. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12834. EXPECT_EQ("bcdefghijk", res->body);
  12835. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12836. }
  12837. {
  12838. auto res = retry_service_failures([&] { return cli.Get(path); });
  12839. SKIP_ON_SERVICE_FAILURE(res);
  12840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12841. EXPECT_EQ("bcdefghijk", res->body);
  12842. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12843. }
  12844. }
  12845. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12846. Server svr;
  12847. svr.set_default_headers({{"Hello", "World"}});
  12848. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12849. res.set_content("ok", "text/plain");
  12850. });
  12851. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12852. auto se = detail::scope_exit([&] {
  12853. svr.stop();
  12854. listen_thread.join();
  12855. ASSERT_FALSE(svr.is_running());
  12856. });
  12857. svr.wait_until_ready();
  12858. Client cli("localhost", PORT);
  12859. auto res = cli.Get("/");
  12860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12861. EXPECT_EQ(StatusCode::OK_200, res->status);
  12862. EXPECT_EQ("ok", res->body);
  12863. EXPECT_EQ("World", res->get_header_value("Hello"));
  12864. }
  12865. #ifdef CPPHTTPLIB_SSL_ENABLED
  12866. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12867. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12868. ASSERT_TRUE(svr.is_valid());
  12869. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12870. std::this_thread::sleep_for(std::chrono::seconds(2));
  12871. res.set_content("a", "text/plain");
  12872. });
  12873. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12874. res.set_content("b", "text/plain");
  12875. });
  12876. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12877. auto se = detail::scope_exit([&] {
  12878. svr.stop();
  12879. listen_thread.join();
  12880. ASSERT_FALSE(svr.is_running());
  12881. });
  12882. svr.wait_until_ready();
  12883. SSLClient cli("localhost", PORT);
  12884. cli.enable_server_certificate_verification(false);
  12885. cli.set_keep_alive(true);
  12886. cli.set_read_timeout(std::chrono::seconds(1));
  12887. auto resa = cli.Get("/a");
  12888. ASSERT_TRUE(!resa);
  12889. EXPECT_EQ(Error::Read, resa.error());
  12890. auto resb = cli.Get("/b");
  12891. ASSERT_TRUE(resb);
  12892. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12893. EXPECT_EQ("b", resb->body);
  12894. }
  12895. // Closing an idle keep-alive connection sends close_notify and returns. The
  12896. // server must not wait for the client's close_notify: an idle client never
  12897. // sends one, so the worker would be held until the read timeout expires, and
  12898. // stop() would wait for it.
  12899. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12901. ASSERT_TRUE(svr.is_valid());
  12902. svr.set_keep_alive_timeout(1);
  12903. svr.set_read_timeout(10, 0);
  12904. svr.Get("/", [](const Request &, Response &res) {
  12905. res.set_content("ok", "text/plain");
  12906. });
  12907. auto port = svr.bind_to_any_port(HOST);
  12908. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12909. auto se = detail::scope_exit([&] {
  12910. if (listen_thread.joinable()) {
  12911. svr.stop();
  12912. listen_thread.join();
  12913. }
  12914. });
  12915. svr.wait_until_ready();
  12916. SSLClient cli(HOST, port);
  12917. cli.enable_server_certificate_verification(false);
  12918. cli.set_keep_alive(true);
  12919. auto res = cli.Get("/");
  12920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12921. EXPECT_EQ(StatusCode::OK_200, res->status);
  12922. // Stay idle past the keep-alive timeout so the server closes the connection.
  12923. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12924. auto start = std::chrono::steady_clock::now();
  12925. svr.stop();
  12926. listen_thread.join();
  12927. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12928. std::chrono::steady_clock::now() - start)
  12929. .count();
  12930. EXPECT_LT(elapsed, 3000);
  12931. }
  12932. #endif
  12933. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12934. protected:
  12935. ServerTestWithAI_PASSIVE()
  12936. : cli_(HOST, PORT)
  12937. #ifdef CPPHTTPLIB_SSL_ENABLED
  12938. ,
  12939. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12940. #endif
  12941. {
  12942. #ifdef CPPHTTPLIB_SSL_ENABLED
  12943. cli_.enable_server_certificate_verification(false);
  12944. #endif
  12945. }
  12946. virtual void SetUp() {
  12947. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12948. res.set_content("Hello World!", "text/plain");
  12949. });
  12950. t_ = thread(
  12951. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12952. svr_.wait_until_ready();
  12953. }
  12954. virtual void TearDown() {
  12955. svr_.stop();
  12956. t_.join();
  12957. }
  12958. #ifdef CPPHTTPLIB_SSL_ENABLED
  12959. SSLClient cli_;
  12960. SSLServer svr_;
  12961. #else
  12962. Client cli_;
  12963. Server svr_;
  12964. #endif
  12965. thread t_;
  12966. };
  12967. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12968. auto res = cli_.Get("/hi");
  12969. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12970. EXPECT_EQ(StatusCode::OK_200, res->status);
  12971. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12972. EXPECT_EQ("Hello World!", res->body);
  12973. }
  12974. class ServerUpDownTest : public ::testing::Test {
  12975. protected:
  12976. ServerUpDownTest() : cli_(HOST, PORT) {}
  12977. virtual void SetUp() {
  12978. t_ = thread([&]() {
  12979. svr_.bind_to_any_port(HOST);
  12980. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12981. ASSERT_TRUE(svr_.listen_after_bind());
  12982. });
  12983. svr_.wait_until_ready();
  12984. }
  12985. virtual void TearDown() {
  12986. svr_.stop();
  12987. t_.join();
  12988. }
  12989. Client cli_;
  12990. Server svr_;
  12991. thread t_;
  12992. };
  12993. TEST_F(ServerUpDownTest, QuickStartStop) {
  12994. // Should not crash, especially when run with
  12995. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12996. }
  12997. class PayloadMaxLengthTest : public ::testing::Test {
  12998. protected:
  12999. PayloadMaxLengthTest()
  13000. : cli_(HOST, PORT)
  13001. #ifdef CPPHTTPLIB_SSL_ENABLED
  13002. ,
  13003. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13004. #endif
  13005. {
  13006. #ifdef CPPHTTPLIB_SSL_ENABLED
  13007. cli_.enable_server_certificate_verification(false);
  13008. #endif
  13009. }
  13010. virtual void SetUp() {
  13011. svr_.set_payload_max_length(8);
  13012. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13013. res.set_content("test", "text/plain");
  13014. });
  13015. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13016. svr_.wait_until_ready();
  13017. }
  13018. virtual void TearDown() {
  13019. svr_.stop();
  13020. t_.join();
  13021. }
  13022. #ifdef CPPHTTPLIB_SSL_ENABLED
  13023. SSLClient cli_;
  13024. SSLServer svr_;
  13025. #else
  13026. Client cli_;
  13027. Server svr_;
  13028. #endif
  13029. thread t_;
  13030. };
  13031. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13032. auto res = cli_.Post("/test", "123456789", "text/plain");
  13033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13034. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13035. res = cli_.Post("/test", "12345678", "text/plain");
  13036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13037. EXPECT_EQ(StatusCode::OK_200, res->status);
  13038. }
  13039. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13040. // Test chunked encoding with payload exceeding the 8-byte limit
  13041. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13042. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13044. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13045. }
  13046. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13047. // Test chunked encoding with payload within the 8-byte limit
  13048. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13049. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13051. EXPECT_EQ(StatusCode::OK_200, res->status);
  13052. }
  13053. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13054. // Test using send_request to send chunked data exceeding payload limit
  13055. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13056. "Host: " +
  13057. std::string(HOST) + ":" + std::to_string(PORT) +
  13058. "\r\n"
  13059. "Transfer-Encoding: chunked\r\n"
  13060. "Connection: close\r\n"
  13061. "\r\n"
  13062. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13063. "0123456789\r\n"
  13064. "0\r\n" // End chunk
  13065. "\r\n";
  13066. std::string response;
  13067. bool result = send_request(1, chunked_request, &response);
  13068. if (!result) {
  13069. // If send_request fails, it might be because the server closed the
  13070. // connection due to payload limit enforcement, which is acceptable
  13071. SUCCEED()
  13072. << "Server rejected oversized chunked request (connection closed)";
  13073. } else {
  13074. // If we got a response, check if it's an error response or connection was
  13075. // closed early Short response length indicates connection was closed due to
  13076. // payload limit
  13077. if (response.length() <= 10) {
  13078. SUCCEED() << "Server closed connection for oversized chunked request";
  13079. } else {
  13080. // Check for error status codes
  13081. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13082. response.find("Payload Too Large") != std::string::npos ||
  13083. response.find("400") != std::string::npos);
  13084. }
  13085. }
  13086. }
  13087. class LargePayloadMaxLengthTest : public ::testing::Test {
  13088. protected:
  13089. LargePayloadMaxLengthTest()
  13090. : cli_(HOST, PORT)
  13091. #ifdef CPPHTTPLIB_SSL_ENABLED
  13092. ,
  13093. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13094. #endif
  13095. {
  13096. #ifdef CPPHTTPLIB_SSL_ENABLED
  13097. cli_.enable_server_certificate_verification(false);
  13098. #endif
  13099. }
  13100. virtual void SetUp() {
  13101. // Set 10MB payload limit
  13102. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13103. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13104. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13105. res.set_content("Large payload test", "text/plain");
  13106. });
  13107. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13108. svr_.wait_until_ready();
  13109. }
  13110. virtual void TearDown() {
  13111. svr_.stop();
  13112. t_.join();
  13113. }
  13114. #ifdef CPPHTTPLIB_SSL_ENABLED
  13115. SSLClient cli_;
  13116. SSLServer svr_;
  13117. #else
  13118. Client cli_;
  13119. Server svr_;
  13120. #endif
  13121. thread t_;
  13122. };
  13123. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13124. // Test chunked encoding with payload within 10MB limit
  13125. std::string medium_payload(5 * 1024 * 1024,
  13126. 'A'); // 5MB payload, within 10MB limit
  13127. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13129. EXPECT_EQ(StatusCode::OK_200, res->status);
  13130. }
  13131. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13132. // Test chunked encoding with payload exceeding 10MB limit
  13133. std::string large_payload(12 * 1024 * 1024,
  13134. 'B'); // 12MB payload, exceeds 10MB limit
  13135. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13136. // Server may either return 413 or close the connection
  13137. if (res) {
  13138. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13139. } else {
  13140. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13141. }
  13142. }
  13143. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13144. Server svr;
  13145. svr.Get("/", [](const Request &, Response &res) {
  13146. // Claims the most the client accepts, far more than it sends, then drops
  13147. // the connection.
  13148. res.set_content_provider(std::string().max_size(), "text/plain",
  13149. [](size_t, size_t, DataSink &sink) {
  13150. sink.write("abc", 3);
  13151. return false;
  13152. });
  13153. });
  13154. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13155. auto se = detail::scope_exit([&] {
  13156. svr.stop();
  13157. thread.join();
  13158. ASSERT_FALSE(svr.is_running());
  13159. });
  13160. svr.wait_until_ready();
  13161. Client cli(HOST, PORT);
  13162. cli.set_payload_max_length(0);
  13163. EXPECT_FALSE(cli.Get("/"));
  13164. }
  13165. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13166. // Stream API does, not as a plain read failure
  13167. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13168. Server svr;
  13169. svr.Get("/big", [](const Request &, Response &res) {
  13170. res.set_content(std::string(100000, 'b'), "text/plain");
  13171. });
  13172. auto port = svr.bind_to_any_port(HOST);
  13173. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13174. auto se = detail::scope_exit([&] {
  13175. svr.stop();
  13176. thread.join();
  13177. });
  13178. svr.wait_until_ready();
  13179. Client cli(HOST, port);
  13180. cli.set_payload_max_length(1000);
  13181. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13182. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13183. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13184. [](const char *, size_t) { return true; });
  13185. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13186. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13187. // Small on the wire, over the limit once decompressed
  13188. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13189. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13190. #endif
  13191. }
  13192. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13193. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13194. // path.
  13195. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13196. Server svr;
  13197. const size_t LIMIT = 64 * 1024; // 64KB
  13198. svr.set_payload_max_length(LIMIT);
  13199. size_t total = 0;
  13200. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13201. const ContentReader &content_reader) {
  13202. content_reader([&](const char * /*data*/, size_t len) {
  13203. total += len;
  13204. return true;
  13205. });
  13206. res.status = 200;
  13207. res.set_content("stream_ok", "text/plain");
  13208. });
  13209. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13210. auto se = detail::scope_exit([&] {
  13211. svr.stop();
  13212. thread.join();
  13213. ASSERT_FALSE(svr.is_running());
  13214. });
  13215. svr.wait_until_ready();
  13216. // Prepare 256KB raw data and gzip-compress it
  13217. std::string raw(256 * 1024, 'A');
  13218. std::string gz;
  13219. {
  13220. z_stream zs{};
  13221. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13222. Z_DEFAULT_STRATEGY);
  13223. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13224. zs.avail_in = static_cast<uInt>(raw.size());
  13225. char outbuf[4096];
  13226. int ret;
  13227. do {
  13228. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13229. zs.avail_out = sizeof(outbuf);
  13230. ret = deflate(&zs, Z_FINISH);
  13231. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13232. } while (ret != Z_STREAM_END);
  13233. deflateEnd(&zs);
  13234. }
  13235. Client cli(HOST, PORT);
  13236. cli.set_connection_timeout(std::chrono::seconds(5));
  13237. Headers headers = {{"Content-Encoding", "gzip"}};
  13238. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13239. "application/octet-stream");
  13240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13241. // Server must reject oversized decompressed payloads with 413.
  13242. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13243. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13244. EXPECT_LE(total, LIMIT);
  13245. }
  13246. #endif
  13247. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13248. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13249. // the payload must be passed through untouched instead of being rejected.
  13250. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13251. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13252. Server svr;
  13253. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13254. res.set_content(body, "image/jpeg");
  13255. res.set_header("Content-Encoding", "UTF-8");
  13256. });
  13257. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13258. res.set_content(body, "image/jpeg");
  13259. res.set_header("Content-Encoding", "identity");
  13260. });
  13261. svr.Post("/echo", [](const Request &req, Response &res) {
  13262. res.set_content(req.body, "image/jpeg");
  13263. });
  13264. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13265. auto se = detail::scope_exit([&] {
  13266. svr.stop();
  13267. t.join();
  13268. ASSERT_FALSE(svr.is_running());
  13269. });
  13270. svr.wait_until_ready();
  13271. Client cli(HOST, PORT);
  13272. {
  13273. auto res = cli.Get("/image");
  13274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13275. EXPECT_EQ(StatusCode::OK_200, res->status);
  13276. EXPECT_EQ(body, res->body);
  13277. }
  13278. {
  13279. auto res = cli.Get("/identity");
  13280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13281. EXPECT_EQ(StatusCode::OK_200, res->status);
  13282. EXPECT_EQ(body, res->body);
  13283. }
  13284. {
  13285. // The same applies to a request body reaching the server.
  13286. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13287. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13289. EXPECT_EQ(StatusCode::OK_200, res->status);
  13290. EXPECT_EQ(body, res->body);
  13291. }
  13292. }
  13293. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13294. // gzip-encoded response even when the build has no zlib support.
  13295. static const char GZIPPED_HELLO_WORLD[] = {
  13296. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13297. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13298. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13299. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13300. // A content coding is a whole token, not something the field value merely
  13301. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13302. // as "fibre" look like Brotli, and turned a multi-coding value like
  13303. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13304. // it was never meant to see.
  13305. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13306. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13307. Server svr;
  13308. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13309. res.set_content(body, "image/jpeg");
  13310. res.set_header("Content-Encoding", "fibre");
  13311. });
  13312. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13313. res.set_content(body, "image/jpeg");
  13314. res.set_header("Content-Encoding", "gzip, br");
  13315. });
  13316. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13317. res.set_content(body, "image/jpeg");
  13318. res.set_header("Content-Encoding", "x-zstd-ish");
  13319. });
  13320. auto port = svr.bind_to_any_port(HOST);
  13321. thread t = thread([&]() { svr.listen_after_bind(); });
  13322. auto se = detail::scope_exit([&] {
  13323. svr.stop();
  13324. t.join();
  13325. ASSERT_FALSE(svr.is_running());
  13326. });
  13327. svr.wait_until_ready();
  13328. Client cli(HOST, port);
  13329. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13330. auto res = cli.Get(path);
  13331. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13332. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13333. // Not a coding we recognize, so the payload comes back untouched
  13334. EXPECT_EQ(body, res->body) << path;
  13335. }
  13336. }
  13337. // A content coding cpp-httplib recognizes but was not built with must be
  13338. // reported as such. Handing the still-compressed payload back to the caller
  13339. // would silently corrupt it.
  13340. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13341. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13342. Server svr;
  13343. // "image/jpeg" keeps the server from applying a content coding of its own,
  13344. // so the hand-crafted Content-Encoding below survives.
  13345. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13346. res.set_content(gzipped, "image/jpeg");
  13347. res.set_header("Content-Encoding", "gzip");
  13348. });
  13349. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13350. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13351. res.set_content(gzipped, "image/jpeg");
  13352. res.set_header("Content-Encoding", "GZIP");
  13353. });
  13354. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13355. auto se = detail::scope_exit([&] {
  13356. svr.stop();
  13357. t.join();
  13358. ASSERT_FALSE(svr.is_running());
  13359. });
  13360. svr.wait_until_ready();
  13361. Client cli(HOST, PORT);
  13362. {
  13363. auto res = cli.Get("/gzipped");
  13364. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13366. EXPECT_EQ("Hello World!", res->body);
  13367. #else
  13368. ASSERT_FALSE(res);
  13369. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13370. #endif
  13371. }
  13372. {
  13373. // open_stream() must behave the same way.
  13374. auto handle = cli.open_stream("GET", "/gzipped");
  13375. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13376. ASSERT_TRUE(handle.is_valid());
  13377. std::string received;
  13378. char buf[256];
  13379. ssize_t n;
  13380. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13381. received.append(buf, static_cast<size_t>(n));
  13382. }
  13383. EXPECT_EQ("Hello World!", received);
  13384. #else
  13385. EXPECT_FALSE(handle.is_valid());
  13386. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13387. #endif
  13388. }
  13389. {
  13390. // A differently-cased coding must not be mistaken for an unknown one, or
  13391. // the body would be handed back still compressed.
  13392. auto res = cli.Get("/gzipped-uppercase");
  13393. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13395. EXPECT_EQ("Hello World!", res->body);
  13396. #else
  13397. ASSERT_FALSE(res);
  13398. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13399. #endif
  13400. }
  13401. }
  13402. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13403. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13404. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13405. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13406. // body a second time and appending a second Content-Encoding field line, so
  13407. // clients that decode one coding per listed value handed back raw gzip bytes.
  13408. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13409. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13410. Server svr;
  13411. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13412. // keeps the server from applying a coding of its own.
  13413. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13414. res.set_content(gzipped, "text/plain");
  13415. res.set_header("Content-Encoding", "gzip");
  13416. });
  13417. auto port = svr.bind_to_any_port(HOST);
  13418. thread t = thread([&]() { svr.listen_after_bind(); });
  13419. auto se = detail::scope_exit([&] {
  13420. svr.stop();
  13421. t.join();
  13422. ASSERT_FALSE(svr.is_running());
  13423. });
  13424. svr.wait_until_ready();
  13425. Client cli(HOST, port);
  13426. Headers headers = {{"Accept-Encoding", "gzip"}};
  13427. auto res = cli.Get("/pre-gzipped", headers);
  13428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13429. EXPECT_EQ(StatusCode::OK_200, res->status);
  13430. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13431. EXPECT_EQ("Hello World!", res->body);
  13432. }
  13433. // set_compress(false) sends every handler response as it is, buffered or
  13434. // streamed
  13435. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13436. const std::string text(1000, 'a');
  13437. Server svr;
  13438. svr.set_compress(false);
  13439. svr.Get("/buffered", [&](const Request &, Response &res) {
  13440. res.set_content(text, "text/plain");
  13441. });
  13442. svr.Get("/streamed", [&](const Request &, Response &res) {
  13443. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13444. sink.write(text.data(), text.size());
  13445. sink.done();
  13446. return true;
  13447. });
  13448. });
  13449. auto port = svr.bind_to_any_port(HOST);
  13450. ASSERT_LT(0, port);
  13451. thread t = thread([&] { svr.listen_after_bind(); });
  13452. auto se = detail::scope_exit([&] {
  13453. svr.stop();
  13454. t.join();
  13455. ASSERT_FALSE(svr.is_running());
  13456. });
  13457. svr.wait_until_ready();
  13458. Client cli(HOST, port);
  13459. cli.set_decompress(false);
  13460. for (auto path : {"/buffered", "/streamed"}) {
  13461. SCOPED_TRACE(path);
  13462. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13464. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13465. EXPECT_EQ(text, res->body);
  13466. }
  13467. }
  13468. // A chunked provider settles its coding where the headers are written and
  13469. // reuses it at write time. Both ends of that have to hold: a handler's own
  13470. // Content-Encoding suppresses the coding, and a response without one is still
  13471. // compressed as it always was.
  13472. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13473. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13474. const std::string plain = "Hello World! Hello World! Hello World!";
  13475. Server svr;
  13476. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13477. res.set_header("Content-Encoding", "gzip");
  13478. res.set_chunked_content_provider(
  13479. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13480. sink.write(gzipped.data(), gzipped.size());
  13481. sink.done();
  13482. return true;
  13483. });
  13484. });
  13485. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13486. res.set_chunked_content_provider(
  13487. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13488. sink.write(plain.data(), plain.size());
  13489. sink.done();
  13490. return true;
  13491. });
  13492. });
  13493. auto port = svr.bind_to_any_port(HOST);
  13494. thread t = thread([&]() { svr.listen_after_bind(); });
  13495. auto se = detail::scope_exit([&] {
  13496. svr.stop();
  13497. t.join();
  13498. ASSERT_FALSE(svr.is_running());
  13499. });
  13500. svr.wait_until_ready();
  13501. Client cli(HOST, port);
  13502. Headers headers = {{"Accept-Encoding", "gzip"}};
  13503. {
  13504. auto res = cli.Get("/pre-gzipped", headers);
  13505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13506. EXPECT_EQ(StatusCode::OK_200, res->status);
  13507. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13508. EXPECT_EQ("Hello World!", res->body);
  13509. }
  13510. {
  13511. auto res = cli.Get("/negotiated", headers);
  13512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13513. EXPECT_EQ(StatusCode::OK_200, res->status);
  13514. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13515. EXPECT_EQ(plain, res->body);
  13516. }
  13517. }
  13518. #endif
  13519. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13520. // the same message as the comma-joined one, so both have to be read the same
  13521. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13522. // single gzip coding, and a body the sender says was encoded twice was handed
  13523. // back after one pass, still compressed but presented as decoded.
  13524. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13525. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13526. Server svr;
  13527. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13528. res.set_content(body, "image/jpeg");
  13529. res.headers.emplace("Content-Encoding", "gzip");
  13530. res.headers.emplace("Content-Encoding", "gzip");
  13531. });
  13532. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13533. res.set_content(body, "image/jpeg");
  13534. res.set_header("Content-Encoding", "gzip, gzip");
  13535. });
  13536. auto port = svr.bind_to_any_port(HOST);
  13537. thread t = thread([&]() { svr.listen_after_bind(); });
  13538. auto se = detail::scope_exit([&] {
  13539. svr.stop();
  13540. t.join();
  13541. ASSERT_FALSE(svr.is_running());
  13542. });
  13543. svr.wait_until_ready();
  13544. Client cli(HOST, port);
  13545. // Two codings is not something cpp-httplib decodes, so both representations
  13546. // take the pass-through path rather than one of them being gunzipped once.
  13547. for (const char *path : {"/split", "/joined"}) {
  13548. auto res = cli.Get(path);
  13549. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13550. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13551. EXPECT_EQ(body, res->body) << path;
  13552. }
  13553. }
  13554. // Regression test for DoS vulnerability: a malicious server sending a response
  13555. // without Content-Length header must not cause unbounded memory consumption on
  13556. // the client side. The client should stop reading after a reasonable limit,
  13557. // similar to the server-side set_payload_max_length protection.
  13558. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13559. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13560. #ifndef _WIN32
  13561. signal(SIGPIPE, SIG_IGN);
  13562. #endif
  13563. auto server_thread = std::thread([] {
  13564. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13565. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13566. default_socket_options(srv);
  13567. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13568. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13569. sockaddr_in addr{};
  13570. addr.sin_family = AF_INET;
  13571. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13572. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13573. int opt = 1;
  13574. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13575. #ifdef _WIN32
  13576. reinterpret_cast<const char *>(&opt),
  13577. #else
  13578. &opt,
  13579. #endif
  13580. sizeof(opt));
  13581. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13582. ::listen(srv, 1);
  13583. sockaddr_in cli_addr{};
  13584. socklen_t cli_len = sizeof(cli_addr);
  13585. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13586. if (cli != INVALID_SOCKET) {
  13587. char buf[4096];
  13588. ::recv(cli, buf, sizeof(buf), 0);
  13589. // Malicious response: no Content-Length, no chunked encoding
  13590. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13591. "Connection: close\r\n"
  13592. "\r\n";
  13593. ::send(cli,
  13594. #ifdef _WIN32
  13595. static_cast<const char *>(response_header.c_str()),
  13596. static_cast<int>(response_header.size()),
  13597. #else
  13598. response_header.c_str(), response_header.size(),
  13599. #endif
  13600. 0);
  13601. // Send 10MB of data
  13602. std::string chunk(64 * 1024, 'A');
  13603. size_t total_sent = 0;
  13604. while (total_sent < MALICIOUS_DATA_SIZE) {
  13605. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13606. auto sent = ::send(cli,
  13607. #ifdef _WIN32
  13608. static_cast<const char *>(chunk.c_str()),
  13609. static_cast<int>(to_send),
  13610. #else
  13611. chunk.c_str(), to_send,
  13612. #endif
  13613. 0);
  13614. if (sent <= 0) break;
  13615. total_sent += static_cast<size_t>(sent);
  13616. }
  13617. detail::close_socket(cli);
  13618. }
  13619. detail::close_socket(srv);
  13620. });
  13621. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13622. size_t total_read = 0;
  13623. {
  13624. Client cli("127.0.0.1", PORT + 2);
  13625. cli.set_read_timeout(5, 0);
  13626. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13627. auto stream = cli.open_stream("GET", "/malicious");
  13628. ASSERT_TRUE(stream.is_valid());
  13629. char buffer[64 * 1024];
  13630. ssize_t n;
  13631. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13632. total_read += static_cast<size_t>(n);
  13633. }
  13634. } // StreamHandle and Client destroyed here, closing the socket
  13635. server_thread.join();
  13636. // With set_payload_max_length, the client must stop reading before consuming
  13637. // all 10MB. The read loop should be cut off at or near the configured limit.
  13638. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13639. << "Client read " << total_read << " bytes, exceeding the configured "
  13640. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13641. }
  13642. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13643. // the entire response body without truncation.
  13644. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13645. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13646. #ifndef _WIN32
  13647. signal(SIGPIPE, SIG_IGN);
  13648. #endif
  13649. auto server_thread = std::thread([] {
  13650. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13651. default_socket_options(srv);
  13652. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13653. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13654. sockaddr_in addr{};
  13655. addr.sin_family = AF_INET;
  13656. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13657. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13658. int opt = 1;
  13659. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13660. #ifdef _WIN32
  13661. reinterpret_cast<const char *>(&opt),
  13662. #else
  13663. &opt,
  13664. #endif
  13665. sizeof(opt));
  13666. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13667. ::listen(srv, 1);
  13668. sockaddr_in cli_addr{};
  13669. socklen_t cli_len = sizeof(cli_addr);
  13670. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13671. if (cli != INVALID_SOCKET) {
  13672. char buf[4096];
  13673. ::recv(cli, buf, sizeof(buf), 0);
  13674. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13675. "Connection: close\r\n"
  13676. "\r\n";
  13677. ::send(cli,
  13678. #ifdef _WIN32
  13679. static_cast<const char *>(response_header.c_str()),
  13680. static_cast<int>(response_header.size()),
  13681. #else
  13682. response_header.c_str(), response_header.size(),
  13683. #endif
  13684. 0);
  13685. std::string chunk(64 * 1024, 'A');
  13686. size_t total_sent = 0;
  13687. while (total_sent < DATA_SIZE) {
  13688. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13689. auto sent = ::send(cli,
  13690. #ifdef _WIN32
  13691. static_cast<const char *>(chunk.c_str()),
  13692. static_cast<int>(to_send),
  13693. #else
  13694. chunk.c_str(), to_send,
  13695. #endif
  13696. 0);
  13697. if (sent <= 0) break;
  13698. total_sent += static_cast<size_t>(sent);
  13699. }
  13700. #ifdef _WIN32
  13701. ::shutdown(cli, SD_SEND);
  13702. #else
  13703. ::shutdown(cli, SHUT_WR);
  13704. #endif
  13705. // Drain until the client closes its end, ensuring all data is delivered
  13706. char drain[1024];
  13707. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13708. detail::close_socket(cli);
  13709. }
  13710. detail::close_socket(srv);
  13711. });
  13712. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13713. size_t total_read = 0;
  13714. {
  13715. Client cli("127.0.0.1", PORT + 2);
  13716. cli.set_read_timeout(5, 0);
  13717. cli.set_payload_max_length(0); // 0 means no limit
  13718. auto stream = cli.open_stream("GET", "/data");
  13719. ASSERT_TRUE(stream.is_valid());
  13720. char buffer[64 * 1024];
  13721. ssize_t n;
  13722. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13723. total_read += static_cast<size_t>(n);
  13724. }
  13725. }
  13726. server_thread.join();
  13727. EXPECT_EQ(total_read, DATA_SIZE)
  13728. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13729. << " bytes without truncation, but only read " << total_read << " bytes.";
  13730. }
  13731. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13732. // enormous Content-Length must not cause the client to pre-allocate a huge
  13733. // response body buffer. The reservation is capped at payload_max_length_, and
  13734. // the read itself fails when the body exceeds the limit.
  13735. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13736. #ifndef _WIN32
  13737. signal(SIGPIPE, SIG_IGN);
  13738. #endif
  13739. auto server_thread = std::thread([] {
  13740. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13741. default_socket_options(srv);
  13742. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13743. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13744. sockaddr_in addr{};
  13745. addr.sin_family = AF_INET;
  13746. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13747. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13748. int opt = 1;
  13749. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13750. #ifdef _WIN32
  13751. reinterpret_cast<const char *>(&opt),
  13752. #else
  13753. &opt,
  13754. #endif
  13755. sizeof(opt));
  13756. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13757. ::listen(srv, 1);
  13758. sockaddr_in cli_addr{};
  13759. socklen_t cli_len = sizeof(cli_addr);
  13760. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13761. if (cli != INVALID_SOCKET) {
  13762. char buf[4096];
  13763. ::recv(cli, buf, sizeof(buf), 0);
  13764. // Malicious response: claim a 20GB body but send only a tiny payload.
  13765. std::string response = "HTTP/1.1 200 OK\r\n"
  13766. "Content-Length: 20000000000\r\n"
  13767. "\r\n"
  13768. "abc";
  13769. ::send(cli,
  13770. #ifdef _WIN32
  13771. static_cast<const char *>(response.c_str()),
  13772. static_cast<int>(response.size()),
  13773. #else
  13774. response.c_str(), response.size(),
  13775. #endif
  13776. 0);
  13777. detail::close_socket(cli);
  13778. }
  13779. detail::close_socket(srv);
  13780. });
  13781. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13782. {
  13783. Client cli("127.0.0.1", PORT + 2);
  13784. cli.set_read_timeout(5, 0);
  13785. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13786. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13787. // (server claims more bytes than payload_max_length permits), but it must
  13788. // not exhaust memory before getting there.
  13789. auto res = cli.Get("/malicious");
  13790. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13791. }
  13792. server_thread.join();
  13793. }
  13794. // Verify that content_receiver bypasses the default payload_max_length,
  13795. // allowing streaming downloads larger than 100MB without requiring an explicit
  13796. // set_payload_max_length call.
  13797. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13798. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13799. #ifndef _WIN32
  13800. signal(SIGPIPE, SIG_IGN);
  13801. #endif
  13802. auto server_thread = std::thread([] {
  13803. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13804. default_socket_options(srv);
  13805. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13806. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13807. sockaddr_in addr{};
  13808. addr.sin_family = AF_INET;
  13809. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13810. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13811. int opt = 1;
  13812. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13813. #ifdef _WIN32
  13814. reinterpret_cast<const char *>(&opt),
  13815. #else
  13816. &opt,
  13817. #endif
  13818. sizeof(opt));
  13819. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13820. ::listen(srv, 1);
  13821. sockaddr_in cli_addr{};
  13822. socklen_t cli_len = sizeof(cli_addr);
  13823. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13824. if (cli != INVALID_SOCKET) {
  13825. char buf[4096];
  13826. ::recv(cli, buf, sizeof(buf), 0);
  13827. // Response with Content-Length larger than default 100MB limit
  13828. auto content_length = std::to_string(DATA_SIZE);
  13829. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13830. "Content-Length: " +
  13831. content_length +
  13832. "\r\n"
  13833. "Connection: close\r\n"
  13834. "\r\n";
  13835. ::send(cli,
  13836. #ifdef _WIN32
  13837. static_cast<const char *>(response_header.c_str()),
  13838. static_cast<int>(response_header.size()),
  13839. #else
  13840. response_header.c_str(), response_header.size(),
  13841. #endif
  13842. 0);
  13843. std::string chunk(64 * 1024, 'A');
  13844. size_t total_sent = 0;
  13845. while (total_sent < DATA_SIZE) {
  13846. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13847. auto sent = ::send(cli,
  13848. #ifdef _WIN32
  13849. static_cast<const char *>(chunk.c_str()),
  13850. static_cast<int>(to_send),
  13851. #else
  13852. chunk.c_str(), to_send,
  13853. #endif
  13854. 0);
  13855. if (sent <= 0) break;
  13856. total_sent += static_cast<size_t>(sent);
  13857. }
  13858. detail::close_socket(cli);
  13859. }
  13860. detail::close_socket(srv);
  13861. });
  13862. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13863. size_t total_received = 0;
  13864. {
  13865. Client cli("127.0.0.1", PORT + 2);
  13866. cli.set_read_timeout(10, 0);
  13867. // Do NOT call set_payload_max_length — use the default 100MB limit
  13868. auto res =
  13869. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13870. total_received += data_length;
  13871. return true;
  13872. });
  13873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13874. EXPECT_EQ(StatusCode::OK_200, res->status);
  13875. }
  13876. server_thread.join();
  13877. EXPECT_EQ(total_received, DATA_SIZE)
  13878. << "With content_receiver, the client should read all " << DATA_SIZE
  13879. << " bytes despite the default 100MB payload_max_length, but only read "
  13880. << total_received << " bytes.";
  13881. }
  13882. // Verify that an explicit set_payload_max_length smaller than the response is
  13883. // enforced even when a content_receiver is used.
  13884. TEST(ClientVulnerabilityTest,
  13885. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13886. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13887. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13888. #ifndef _WIN32
  13889. signal(SIGPIPE, SIG_IGN);
  13890. #endif
  13891. auto server_thread = std::thread([] {
  13892. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13893. default_socket_options(srv);
  13894. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13895. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13896. sockaddr_in addr{};
  13897. addr.sin_family = AF_INET;
  13898. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13899. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13900. int opt = 1;
  13901. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13902. #ifdef _WIN32
  13903. reinterpret_cast<const char *>(&opt),
  13904. #else
  13905. &opt,
  13906. #endif
  13907. sizeof(opt));
  13908. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13909. ::listen(srv, 1);
  13910. sockaddr_in cli_addr{};
  13911. socklen_t cli_len = sizeof(cli_addr);
  13912. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13913. if (cli != INVALID_SOCKET) {
  13914. char buf[4096];
  13915. ::recv(cli, buf, sizeof(buf), 0);
  13916. auto content_length = std::to_string(DATA_SIZE);
  13917. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13918. "Content-Length: " +
  13919. content_length +
  13920. "\r\n"
  13921. "Connection: close\r\n"
  13922. "\r\n";
  13923. ::send(cli,
  13924. #ifdef _WIN32
  13925. static_cast<const char *>(response_header.c_str()),
  13926. static_cast<int>(response_header.size()),
  13927. #else
  13928. response_header.c_str(), response_header.size(),
  13929. #endif
  13930. 0);
  13931. std::string chunk(64 * 1024, 'A');
  13932. size_t total_sent = 0;
  13933. while (total_sent < DATA_SIZE) {
  13934. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13935. auto sent = ::send(cli,
  13936. #ifdef _WIN32
  13937. static_cast<const char *>(chunk.c_str()),
  13938. static_cast<int>(to_send),
  13939. #else
  13940. chunk.c_str(), to_send,
  13941. #endif
  13942. 0);
  13943. if (sent <= 0) break;
  13944. total_sent += static_cast<size_t>(sent);
  13945. }
  13946. detail::close_socket(cli);
  13947. }
  13948. detail::close_socket(srv);
  13949. });
  13950. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13951. size_t total_received = 0;
  13952. {
  13953. Client cli("127.0.0.1", PORT + 2);
  13954. cli.set_read_timeout(10, 0);
  13955. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13956. auto res =
  13957. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13958. total_received += data_length;
  13959. return true;
  13960. });
  13961. // Should fail because 200MB exceeds the explicit 150MB limit
  13962. EXPECT_FALSE(res);
  13963. }
  13964. server_thread.join();
  13965. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13966. << "Client with content_receiver should respect the explicit "
  13967. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13968. << total_received << " bytes.";
  13969. }
  13970. // Verify that an explicit set_payload_max_length larger than the response
  13971. // allows the content_receiver to read all data successfully.
  13972. TEST(ClientVulnerabilityTest,
  13973. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13974. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13975. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13976. #ifndef _WIN32
  13977. signal(SIGPIPE, SIG_IGN);
  13978. #endif
  13979. auto server_thread = std::thread([] {
  13980. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13981. default_socket_options(srv);
  13982. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13983. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13984. sockaddr_in addr{};
  13985. addr.sin_family = AF_INET;
  13986. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13987. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13988. int opt = 1;
  13989. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13990. #ifdef _WIN32
  13991. reinterpret_cast<const char *>(&opt),
  13992. #else
  13993. &opt,
  13994. #endif
  13995. sizeof(opt));
  13996. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13997. ::listen(srv, 1);
  13998. sockaddr_in cli_addr{};
  13999. socklen_t cli_len = sizeof(cli_addr);
  14000. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14001. if (cli != INVALID_SOCKET) {
  14002. char buf[4096];
  14003. ::recv(cli, buf, sizeof(buf), 0);
  14004. auto content_length = std::to_string(DATA_SIZE);
  14005. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14006. "Content-Length: " +
  14007. content_length +
  14008. "\r\n"
  14009. "Connection: close\r\n"
  14010. "\r\n";
  14011. ::send(cli,
  14012. #ifdef _WIN32
  14013. static_cast<const char *>(response_header.c_str()),
  14014. static_cast<int>(response_header.size()),
  14015. #else
  14016. response_header.c_str(), response_header.size(),
  14017. #endif
  14018. 0);
  14019. std::string chunk(64 * 1024, 'A');
  14020. size_t total_sent = 0;
  14021. while (total_sent < DATA_SIZE) {
  14022. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14023. auto sent = ::send(cli,
  14024. #ifdef _WIN32
  14025. static_cast<const char *>(chunk.c_str()),
  14026. static_cast<int>(to_send),
  14027. #else
  14028. chunk.c_str(), to_send,
  14029. #endif
  14030. 0);
  14031. if (sent <= 0) break;
  14032. total_sent += static_cast<size_t>(sent);
  14033. }
  14034. #ifdef _WIN32
  14035. ::shutdown(cli, SD_SEND);
  14036. #else
  14037. ::shutdown(cli, SHUT_WR);
  14038. #endif
  14039. char drain[1024];
  14040. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14041. detail::close_socket(cli);
  14042. }
  14043. detail::close_socket(srv);
  14044. });
  14045. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14046. size_t total_received = 0;
  14047. {
  14048. Client cli("127.0.0.1", PORT + 2);
  14049. cli.set_read_timeout(10, 0);
  14050. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14051. auto res =
  14052. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14053. total_received += data_length;
  14054. return true;
  14055. });
  14056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14057. EXPECT_EQ(StatusCode::OK_200, res->status);
  14058. }
  14059. server_thread.join();
  14060. EXPECT_EQ(total_received, DATA_SIZE)
  14061. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14062. << " bytes (larger than " << DATA_SIZE
  14063. << " bytes response), content_receiver should read all data, but only "
  14064. "read "
  14065. << total_received << " bytes.";
  14066. }
  14067. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14068. // Regression test for "zip bomb" attack on the client side: a malicious server
  14069. // sends a small gzip-compressed response that decompresses to a huge payload.
  14070. // The client must enforce payload_max_length on the decompressed size.
  14071. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14072. constexpr size_t DECOMPRESSED_SIZE =
  14073. 10 * 1024 * 1024; // 10MB after decompression
  14074. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14075. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14076. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14077. std::string compressed;
  14078. {
  14079. httplib::detail::gzip_compressor compressor;
  14080. bool ok =
  14081. compressor.compress(uncompressed.data(), uncompressed.size(),
  14082. /*last=*/true, [&](const char *buf, size_t len) {
  14083. compressed.append(buf, len);
  14084. return true;
  14085. });
  14086. ASSERT_TRUE(ok);
  14087. }
  14088. // Sanity: compressed data should be much smaller than the decompressed size
  14089. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14090. #ifndef _WIN32
  14091. signal(SIGPIPE, SIG_IGN);
  14092. #endif
  14093. // Set up the listening socket in the main thread so the server is guaranteed
  14094. // to be ready before the client connects (eliminates race condition).
  14095. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14096. default_socket_options(srv);
  14097. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14098. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14099. sockaddr_in addr{};
  14100. addr.sin_family = AF_INET;
  14101. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14102. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14103. int opt = 1;
  14104. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14105. #ifdef _WIN32
  14106. reinterpret_cast<const char *>(&opt),
  14107. #else
  14108. &opt,
  14109. #endif
  14110. sizeof(opt));
  14111. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14112. ASSERT_EQ(0, ::listen(srv, 1));
  14113. auto server_thread = std::thread([&compressed, srv] {
  14114. sockaddr_in cli_addr{};
  14115. socklen_t cli_len = sizeof(cli_addr);
  14116. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14117. if (cli != INVALID_SOCKET) {
  14118. // Read the full HTTP request (until \r\n\r\n)
  14119. char buf[4096];
  14120. size_t total = 0;
  14121. while (total < sizeof(buf)) {
  14122. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14123. if (n <= 0) break;
  14124. total += static_cast<size_t>(n);
  14125. // Check for end of headers
  14126. if (total >= 4) {
  14127. std::string req(buf, total);
  14128. if (req.find("\r\n\r\n") != std::string::npos) break;
  14129. }
  14130. }
  14131. // Malicious response: gzip-compressed body, no Content-Length
  14132. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14133. "Content-Encoding: gzip\r\n"
  14134. "Connection: close\r\n"
  14135. "\r\n";
  14136. ::send(cli,
  14137. #ifdef _WIN32
  14138. static_cast<const char *>(response_header.c_str()),
  14139. static_cast<int>(response_header.size()),
  14140. #else
  14141. response_header.c_str(), response_header.size(),
  14142. #endif
  14143. 0);
  14144. // Send the compressed payload (small on the wire, huge when decompressed)
  14145. size_t total_sent = 0;
  14146. while (total_sent < compressed.size()) {
  14147. auto to_send = std::min(compressed.size() - total_sent,
  14148. static_cast<size_t>(64 * 1024));
  14149. auto sent =
  14150. ::send(cli,
  14151. #ifdef _WIN32
  14152. static_cast<const char *>(compressed.c_str() + total_sent),
  14153. static_cast<int>(to_send),
  14154. #else
  14155. compressed.c_str() + total_sent, to_send,
  14156. #endif
  14157. 0);
  14158. if (sent <= 0) break;
  14159. total_sent += static_cast<size_t>(sent);
  14160. }
  14161. detail::close_socket(cli);
  14162. }
  14163. });
  14164. auto se = detail::scope_exit([&] {
  14165. detail::close_socket(srv);
  14166. server_thread.join();
  14167. });
  14168. size_t total_decompressed = 0;
  14169. {
  14170. Client cli("127.0.0.1", PORT + 3);
  14171. cli.set_read_timeout(5, 0);
  14172. cli.set_decompress(true);
  14173. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14174. auto stream = cli.open_stream("GET", "/zipbomb");
  14175. ASSERT_TRUE(stream.is_valid());
  14176. char buffer[64 * 1024];
  14177. ssize_t n;
  14178. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14179. total_decompressed += static_cast<size_t>(n);
  14180. }
  14181. }
  14182. // The decompressed size must be capped by payload_max_length. Without
  14183. // protection, the client would decompress the full 10MB from a tiny
  14184. // compressed payload, enabling a zip bomb DoS attack.
  14185. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14186. << "Client decompressed " << total_decompressed
  14187. << " bytes from a gzip response. The decompressed size should be "
  14188. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14189. }
  14190. #endif
  14191. TEST(HostAndPortPropertiesTest, NoSSL) {
  14192. httplib::Client cli("www.google.com", 1234);
  14193. ASSERT_EQ("www.google.com", cli.host());
  14194. ASSERT_EQ(1234, cli.port());
  14195. }
  14196. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14197. httplib::Client cli("www.google.com:1234");
  14198. ASSERT_EQ("www.google.com", cli.host());
  14199. ASSERT_EQ(1234, cli.port());
  14200. }
  14201. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14202. // Port number that overflows int — should not crash, client becomes invalid
  14203. httplib::Client cli("http://www.google.com:99999999999999999999");
  14204. ASSERT_FALSE(cli.is_valid());
  14205. }
  14206. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14207. // Port 99999 exceeds valid range (1-65535) — should not crash
  14208. httplib::Client cli("http://www.google.com:99999");
  14209. ASSERT_FALSE(cli.is_valid());
  14210. auto res = cli.Get("/");
  14211. EXPECT_FALSE(res);
  14212. EXPECT_EQ(Error::Connection, res.error());
  14213. }
  14214. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14215. httplib::Client cli("http://user:pass@localhost:1234");
  14216. ASSERT_FALSE(cli.is_valid());
  14217. EXPECT_FALSE(cli.Get("/"));
  14218. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14219. }
  14220. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14221. httplib::Client cli("http://www.google.com:80abc");
  14222. ASSERT_FALSE(cli.is_valid());
  14223. }
  14224. #ifdef CPPHTTPLIB_SSL_ENABLED
  14225. TEST(HostAndPortPropertiesTest, SSL) {
  14226. httplib::SSLClient cli("www.google.com");
  14227. ASSERT_EQ("www.google.com", cli.host());
  14228. ASSERT_EQ(443, cli.port());
  14229. }
  14230. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14231. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14232. std::string cert;
  14233. read_file(CA_CERT_FILE, cert);
  14234. httplib::SSLClient httplib_client("www.google.com");
  14235. // Load CA store first time
  14236. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14237. // Load CA store second time (update)
  14238. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14239. // Verify client is still valid and can make connections
  14240. httplib_client.enable_server_certificate_verification(true);
  14241. auto res = httplib_client.Get("/");
  14242. // Any status: Google may redirect or rate-limit CI runners.
  14243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14244. }
  14245. TEST(SSLClientTest, ServerNameIndication_Online) {
  14246. auto host = "httpbingo.org";
  14247. auto path = std::string{"/get"};
  14248. SSLClient cli(host, 443);
  14249. auto res = retry_service_failures([&] { return cli.Get(path); });
  14250. SKIP_ON_SERVICE_FAILURE(res);
  14251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14252. ASSERT_EQ(StatusCode::OK_200, res->status);
  14253. }
  14254. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14255. // Use a site that will cause SSL verification failure due to self-signed cert
  14256. SSLClient cli("self-signed.badssl.com", 443);
  14257. cli.enable_server_certificate_verification(true);
  14258. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14259. SKIP_ON_SERVICE_FAILURE(res);
  14260. ASSERT_TRUE(!res);
  14261. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14262. // Verify backend error is captured for SSLServerVerification
  14263. // This occurs when certificate verification fails
  14264. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14265. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14266. EXPECT_NE(0UL, res.ssl_backend_error());
  14267. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14268. res.ssl_error());
  14269. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14270. #if !defined(_WIN32) || \
  14271. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14272. // On non-Windows or when Windows Schannel is disabled, the error comes
  14273. // from OpenSSL's verification
  14274. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14275. res.ssl_backend_error());
  14276. #endif
  14277. #endif
  14278. }
  14279. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14280. // Use a site where hostname doesn't match the certificate
  14281. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14282. SSLClient cli("wrong.host.badssl.com", 443);
  14283. cli.enable_server_certificate_verification(true);
  14284. cli.enable_server_hostname_verification(true);
  14285. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14286. SKIP_ON_SERVICE_FAILURE(res);
  14287. ASSERT_TRUE(!res);
  14288. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14289. // Verify backend error is captured for hostname verification failure
  14290. EXPECT_NE(0UL, res.ssl_backend_error());
  14291. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14292. res.ssl_error());
  14293. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14294. #if !defined(_WIN32) || \
  14295. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14296. // On non-Windows or when Windows Schannel is disabled, the error comes
  14297. // from OpenSSL's hostname verification
  14298. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14299. res.ssl_backend_error());
  14300. #endif
  14301. #endif
  14302. }
  14303. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14304. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14305. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14306. SSLClient cli("www.google.com", 443);
  14307. cli.enable_server_certificate_verification(true);
  14308. auto res = cli.Get("/");
  14309. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14310. }
  14311. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14312. SSLClient cli("www.google.com", 443);
  14313. cli.enable_server_certificate_verification(true);
  14314. cli.enable_windows_certificate_verification(false);
  14315. auto res = cli.Get("/");
  14316. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14317. }
  14318. // The server sends an intermediate cross-signed by a root Windows trusts,
  14319. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14320. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14321. SSLClient cli("accounts.spotify.com", 443);
  14322. auto res = cli.Get("/");
  14323. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14324. << " ssl_backend_error=" << res.ssl_backend_error();
  14325. }
  14326. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14327. // policy status, which no backend reports for a self-signed certificate.
  14328. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14329. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14330. ASSERT_TRUE(svr.is_valid());
  14331. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14332. auto se = detail::scope_exit([&] {
  14333. svr.stop();
  14334. t.join();
  14335. ASSERT_FALSE(svr.is_running());
  14336. });
  14337. svr.wait_until_ready();
  14338. SSLClient cli("127.0.0.1", PORT);
  14339. cli.set_connection_timeout(30);
  14340. auto res = cli.Get("/");
  14341. ASSERT_FALSE(res);
  14342. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14343. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14344. }
  14345. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14346. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14347. ASSERT_TRUE(svr.is_valid());
  14348. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14349. auto se = detail::scope_exit([&] {
  14350. svr.stop();
  14351. t.join();
  14352. ASSERT_FALSE(svr.is_running());
  14353. });
  14354. svr.wait_until_ready();
  14355. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14356. {
  14357. ws::WebSocketClient client(url);
  14358. auto res = client.connect();
  14359. ASSERT_FALSE(res);
  14360. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14361. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14362. res.ssl_backend_error());
  14363. }
  14364. {
  14365. ws::WebSocketClient client(url);
  14366. client.enable_windows_certificate_verification(false);
  14367. auto res = client.connect();
  14368. ASSERT_FALSE(res);
  14369. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14370. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14371. res.ssl_backend_error());
  14372. }
  14373. }
  14374. #endif
  14375. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14376. Client cli("https://google.com");
  14377. auto res = cli.Get("/");
  14378. // Any status: Google may redirect or rate-limit CI runners.
  14379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14380. }
  14381. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14382. SSLClient cli("google.com");
  14383. cli.set_ca_cert_path(CA_CERT_FILE);
  14384. auto res = cli.Get("/");
  14385. // Any status: Google may redirect or rate-limit CI runners.
  14386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14387. }
  14388. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14389. SSLClient cli("google.com");
  14390. cli.enable_server_certificate_verification(true);
  14391. cli.set_ca_cert_path("hello");
  14392. auto res = cli.Get("/");
  14393. ASSERT_TRUE(!res);
  14394. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14395. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14396. // should be set
  14397. EXPECT_EQ(0, res.ssl_error());
  14398. // Verify backend error is captured for SSLLoadingCerts
  14399. // This error occurs when loading CA certificates fails
  14400. EXPECT_NE(0UL, res.ssl_backend_error());
  14401. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14402. // OpenSSL specific error codes:
  14403. // > openssl errstr 0x80000002
  14404. // error:80000002:system library::No such file or directory
  14405. // > openssl errstr 0xA000126
  14406. // error:0A000126:SSL routines::unexpected eof while reading
  14407. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14408. res.ssl_backend_error() == 0xA000126);
  14409. #endif
  14410. }
  14411. TEST(SSLClientTest, ServerCertificateVerification4) {
  14412. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14413. ASSERT_TRUE(svr.is_valid());
  14414. svr.Get("/test", [&](const Request &, Response &res) {
  14415. res.set_content("test", "text/plain");
  14416. svr.stop();
  14417. ASSERT_TRUE(true);
  14418. });
  14419. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14420. auto se = detail::scope_exit([&] {
  14421. t.join();
  14422. ASSERT_FALSE(svr.is_running());
  14423. });
  14424. svr.wait_until_ready();
  14425. SSLClient cli("127.0.0.1", PORT);
  14426. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14427. cli.enable_server_certificate_verification(true);
  14428. cli.set_connection_timeout(30);
  14429. auto res = cli.Get("/test");
  14430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14431. ASSERT_EQ(StatusCode::OK_200, res->status);
  14432. }
  14433. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14434. std::string cert;
  14435. read_file(CA_CERT_FILE, cert);
  14436. SSLClient cli("google.com");
  14437. cli.load_ca_cert_store(cert.data(), cert.size());
  14438. const auto res = cli.Get("/");
  14439. // Any status: Google may redirect or rate-limit CI runners.
  14440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14441. }
  14442. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14443. // clang-format off
  14444. static constexpr char cert[] =
  14445. "GlobalSign Root CA\n"
  14446. "==================\n"
  14447. "-----BEGIN CERTIFICATE-----\n"
  14448. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14449. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14450. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14451. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14452. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14453. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14454. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14455. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14456. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14457. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14458. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14459. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14460. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14461. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14462. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14463. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14464. "-----END CERTIFICATE-----\n";
  14465. // clang-format on
  14466. SSLClient cli("google.com");
  14467. cli.load_ca_cert_store(cert, sizeof(cert));
  14468. const auto res = cli.Get("/");
  14469. // Any status: Google may redirect or rate-limit CI runners.
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14471. }
  14472. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14473. SSLClient cli("www.youtube.com");
  14474. cli.set_ca_cert_path(CA_CERT_FILE);
  14475. cli.enable_server_certificate_verification(true);
  14476. cli.set_follow_location(true);
  14477. auto res = cli.Get("/");
  14478. // Any status: Google may redirect or rate-limit CI runners.
  14479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14480. }
  14481. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14482. SSLClient cli("wWw.YouTube.Com");
  14483. cli.set_ca_cert_path(CA_CERT_FILE);
  14484. cli.enable_server_certificate_verification(true);
  14485. cli.enable_server_hostname_verification(true);
  14486. cli.set_follow_location(true);
  14487. auto res = cli.Get("/");
  14488. // Any status: Google may redirect or rate-limit CI runners.
  14489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14490. }
  14491. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14492. SSLClient cli("gOoGlE.COm");
  14493. cli.enable_server_certificate_verification(true);
  14494. cli.enable_server_hostname_verification(true);
  14495. cli.set_follow_location(true);
  14496. auto res = cli.Get("/");
  14497. // Any status: Google may redirect or rate-limit CI runners.
  14498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14499. }
  14500. TEST(SSLClientTest, Issue2004_Online) {
  14501. Client client("https://google.com");
  14502. client.set_follow_location(true);
  14503. auto res = client.Get("/");
  14504. // Any status: Google may redirect or rate-limit CI runners.
  14505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14506. }
  14507. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14508. // Create SSLClient with invalid cert/key to make is_valid() return false
  14509. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14510. "nonexistent_key.pem");
  14511. // is_valid() should be false due to cert loading failure
  14512. ASSERT_FALSE(cli.is_valid());
  14513. auto res = cli.Get("/");
  14514. ASSERT_FALSE(res);
  14515. EXPECT_EQ(Error::SSLConnection, res.error());
  14516. }
  14517. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14518. // Test for Issue #2251: SSL error not properly reported when client cert
  14519. // and key paths are swapped or mismatched
  14520. // This simulates the scenario where user accidentally swaps the cert and key
  14521. // files
  14522. // Using client cert file as private key and vice versa (completely wrong)
  14523. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14524. // Should fail validation due to cert/key mismatch
  14525. ASSERT_FALSE(cli.is_valid());
  14526. // Attempt to make a request should fail with proper error
  14527. auto res = cli.Get("/");
  14528. ASSERT_FALSE(res);
  14529. EXPECT_EQ(Error::SSLConnection, res.error());
  14530. // SSL error should be recorded in the Result object (this is the key fix for
  14531. // Issue #2251)
  14532. auto backend_error = res.ssl_backend_error();
  14533. EXPECT_NE(0u, backend_error);
  14534. }
  14535. // Tests cert/key mismatch detection at the TLS context level
  14536. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14537. // Test that using mismatched cert/key causes connection failure.
  14538. // We verify this at the SSLClient level rather than through internal
  14539. // TLS API functions.
  14540. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14541. cli.enable_server_certificate_verification(false);
  14542. cli.set_connection_timeout(2);
  14543. // The mismatch should cause a connection or handshake error
  14544. auto res = cli.Get("/test");
  14545. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14546. // Either way, the request should fail
  14547. EXPECT_FALSE(res);
  14548. }
  14549. #endif
  14550. #if 0
  14551. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14552. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14553. ASSERT_TRUE(cli != nullptr);
  14554. cli->set_address_family(AF_INET6);
  14555. cli->set_interface("en0");
  14556. auto res = cli->Get("/get");
  14557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14558. ASSERT_EQ(StatusCode::OK_200, res->status);
  14559. }
  14560. #endif
  14561. // Client certificate tests - work with all TLS backends
  14562. #ifdef CPPHTTPLIB_SSL_ENABLED
  14563. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14564. void ClientCertPresent(
  14565. const std::string &client_cert_file,
  14566. const std::string &client_private_key_file,
  14567. const std::string &client_encrypted_private_key_pass = std::string(),
  14568. const ClientCertServerSetup &setup = nullptr) {
  14569. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14570. ASSERT_TRUE(svr.is_valid());
  14571. if (setup) { setup(svr); }
  14572. svr.Get("/test", [&](const Request &req, Response &res) {
  14573. res.set_content("test", "text/plain");
  14574. auto cert = req.peer_cert();
  14575. ASSERT_TRUE(static_cast<bool>(cert));
  14576. std::string common_name = cert.subject_cn();
  14577. EXPECT_EQ("Common Name", common_name);
  14578. });
  14579. auto port = svr.bind_to_any_port(HOST);
  14580. ASSERT_LT(0, port);
  14581. thread t = thread([&]() { svr.listen_after_bind(); });
  14582. auto se = detail::scope_exit([&] {
  14583. svr.stop();
  14584. t.join();
  14585. ASSERT_FALSE(svr.is_running());
  14586. });
  14587. svr.wait_until_ready();
  14588. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14589. client_encrypted_private_key_pass);
  14590. cli.enable_server_certificate_verification(false);
  14591. cli.set_connection_timeout(30);
  14592. auto res = cli.Get("/test");
  14593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14594. ASSERT_EQ(StatusCode::OK_200, res->status);
  14595. }
  14596. TEST(SSLClientServerTest, ClientCertPresent) {
  14597. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14598. }
  14599. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14600. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14601. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14602. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14603. }
  14604. // Expects svr, which must require client certificates, to reject a client
  14605. // that has none
  14606. void RejectsClientWithoutCert(SSLServer &svr) {
  14607. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14608. auto port = svr.bind_to_any_port(HOST);
  14609. ASSERT_LT(0, port);
  14610. thread t = thread([&]() { svr.listen_after_bind(); });
  14611. auto se = detail::scope_exit([&] {
  14612. svr.stop();
  14613. t.join();
  14614. ASSERT_FALSE(svr.is_running());
  14615. });
  14616. svr.wait_until_ready();
  14617. SSLClient cli(HOST, port);
  14618. cli.set_connection_timeout(30);
  14619. // Skip the server certificate check, so that the request fails because the
  14620. // client certificate is missing rather than because cert.pem is not trusted
  14621. cli.enable_server_certificate_verification(false);
  14622. auto res = cli.Get("/test");
  14623. ASSERT_FALSE(res);
  14624. // The server rejects the client during the handshake, or on TLS 1.3 right
  14625. // after it, which the client notices on its first write or read
  14626. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14627. res.error() == Error::Write || res.error() == Error::Read)
  14628. << to_string(res.error());
  14629. if (res.error() == Error::SSLConnection) {
  14630. EXPECT_NE(0UL, res.ssl_backend_error());
  14631. }
  14632. // A rejection noticed on the write keeps the TLS error the write hit
  14633. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14634. }
  14635. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14637. ASSERT_TRUE(svr.is_valid());
  14638. if (setup) { setup(svr); }
  14639. RejectsClientWithoutCert(svr);
  14640. }
  14641. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14642. // A server that requires client certificates must keep requiring them after
  14643. // setup changes it, and keep accepting a client that has one
  14644. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14645. ClientCertMissing(setup);
  14646. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14647. setup);
  14648. }
  14649. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14650. ClientCertStillRequired([](SSLServer &svr) {
  14651. ASSERT_TRUE(tls::set_verify_callback(
  14652. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14653. });
  14654. }
  14655. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14656. ClientCertStillRequired([](SSLServer &svr) {
  14657. ASSERT_TRUE(tls::set_verify_callback(
  14658. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14659. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14660. });
  14661. }
  14662. // The client verifies the server certificate during the handshake, so a
  14663. // server that fails the check never gets the client certificate, even when a
  14664. // verifier of the client's own accepts it
  14665. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14666. struct Case {
  14667. const char *trusted_ca;
  14668. const char *host;
  14669. Error error;
  14670. };
  14671. // cert2.pem names localhost: the first client does not trust it, and the
  14672. // second trusts it but asks for another name
  14673. for (const auto &c :
  14674. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14675. Case{SERVER_CERT2_FILE, "example.com",
  14676. Error::SSLServerHostnameVerification}}) {
  14677. for (auto with_verifier : {false, true}) {
  14678. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14679. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14680. CLIENT_CA_CERT_FILE);
  14681. ASSERT_TRUE(svr.is_valid());
  14682. std::atomic<bool> got_client_cert{false};
  14683. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14684. [&](const tls::VerifyContext &) {
  14685. got_client_cert = true;
  14686. return true;
  14687. }));
  14688. auto port = svr.bind_to_any_port("127.0.0.1");
  14689. ASSERT_LT(0, port);
  14690. thread t = thread([&] { svr.listen_after_bind(); });
  14691. svr.wait_until_ready();
  14692. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14693. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14694. cli.set_ca_cert_path(c.trusted_ca);
  14695. if (with_verifier) {
  14696. cli.set_server_certificate_verifier(
  14697. [](const tls::VerifyContext &) { return true; });
  14698. }
  14699. auto res = cli.Get("/");
  14700. EXPECT_FALSE(res);
  14701. EXPECT_EQ(c.error, res.error());
  14702. svr.stop();
  14703. t.join();
  14704. EXPECT_FALSE(got_client_cert);
  14705. }
  14706. }
  14707. }
  14708. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14709. std::string cert_pem, key_pem, ca_pem;
  14710. read_file(SERVER_CERT_FILE, cert_pem);
  14711. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14712. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14713. ASSERT_TRUE(
  14714. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14715. }
  14716. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14717. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14718. ASSERT_TRUE(svr.is_valid());
  14719. UpdateCertsPemWithClientCA(svr);
  14720. RejectsClientWithoutCert(svr);
  14721. }
  14722. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14723. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14724. }
  14725. // A TLS error from one request must not show up in a later request's Result
  14726. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14728. ASSERT_TRUE(svr.is_valid());
  14729. svr.Get("/test", [](const Request &, Response &res) {
  14730. res.set_content("test", "text/plain");
  14731. });
  14732. auto port = svr.bind_to_any_port(HOST);
  14733. ASSERT_LT(0, port);
  14734. thread t = thread([&]() { svr.listen_after_bind(); });
  14735. auto se = detail::scope_exit([&] {
  14736. svr.stop();
  14737. t.join();
  14738. ASSERT_FALSE(svr.is_running());
  14739. });
  14740. svr.wait_until_ready();
  14741. SSLClient cli(HOST, port);
  14742. cli.set_connection_timeout(30);
  14743. cli.enable_server_hostname_verification(false);
  14744. // cert.pem is not trusted, so the handshake fails
  14745. ASSERT_FALSE(cli.Get("/test"));
  14746. cli.enable_server_certificate_verification(false);
  14747. auto res = cli.Get("/test");
  14748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14749. EXPECT_EQ(0, res.ssl_error());
  14750. EXPECT_EQ(0UL, res.ssl_backend_error());
  14751. }
  14752. // PEM memory-based constructor tests (works with all TLS backends).
  14753. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14754. // terminator after it.
  14755. void PemMemoryClientCertPresent(
  14756. const std::string &client_cert_file,
  14757. const std::string &client_private_key_file,
  14758. const std::string &client_encrypted_private_key_pass = std::string(),
  14759. bool exact_size = false) {
  14760. // Read PEM files into memory
  14761. std::string server_cert_pem, server_key_pem;
  14762. std::string client_ca_pem;
  14763. std::string client_cert_pem, client_key_pem;
  14764. read_file(SERVER_CERT_FILE, server_cert_pem);
  14765. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14766. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14767. read_file(client_cert_file, client_cert_pem);
  14768. read_file(client_private_key_file, client_key_pem);
  14769. std::list<std::vector<char>> exact_copies;
  14770. auto data = [&](const std::string &pem) -> const char * {
  14771. if (!exact_size) { return pem.c_str(); }
  14772. exact_copies.emplace_back(pem.begin(), pem.end());
  14773. return exact_copies.back().data();
  14774. };
  14775. // Create server with PEM memory
  14776. SSLServer::PemMemory server_pem = {
  14777. data(server_cert_pem),
  14778. server_cert_pem.size(),
  14779. data(server_key_pem),
  14780. server_key_pem.size(),
  14781. data(client_ca_pem),
  14782. client_ca_pem.size(),
  14783. nullptr // no password for server key
  14784. };
  14785. SSLServer svr(server_pem);
  14786. ASSERT_TRUE(svr.is_valid());
  14787. svr.Get("/test", [&](const Request &req, Response &res) {
  14788. res.set_content("test", "text/plain");
  14789. auto cert = req.peer_cert();
  14790. ASSERT_TRUE(static_cast<bool>(cert));
  14791. EXPECT_EQ("Common Name", cert.subject_cn());
  14792. });
  14793. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14794. auto se = detail::scope_exit([&] {
  14795. svr.stop();
  14796. t.join();
  14797. ASSERT_FALSE(svr.is_running());
  14798. });
  14799. svr.wait_until_ready();
  14800. // Create client with PEM memory
  14801. const char *password = client_encrypted_private_key_pass.empty()
  14802. ? nullptr
  14803. : client_encrypted_private_key_pass.c_str();
  14804. SSLClient::PemMemory client_pem = {
  14805. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14806. client_key_pem.size(), password};
  14807. SSLClient cli(HOST, PORT, client_pem);
  14808. cli.enable_server_certificate_verification(false);
  14809. cli.set_connection_timeout(30);
  14810. auto res = cli.Get("/test");
  14811. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14812. ASSERT_EQ(StatusCode::OK_200, res->status);
  14813. }
  14814. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14815. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14816. }
  14817. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14818. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14819. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14820. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14821. }
  14822. // A server built from PEM memory with a client CA requires client certificates,
  14823. // also when the CA is a NUL-terminated string passed with a length of 0
  14824. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14825. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14826. read_file(SERVER_CERT_FILE, server_cert_pem);
  14827. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14828. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14829. SSLServer::PemMemory server_pem = {
  14830. server_cert_pem.c_str(),
  14831. server_cert_pem.size(),
  14832. server_key_pem.c_str(),
  14833. server_key_pem.size(),
  14834. client_ca_pem.c_str(),
  14835. client_ca_pem.size(),
  14836. nullptr // no password for server key
  14837. };
  14838. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14839. SCOPED_TRACE(client_ca_pem_len);
  14840. server_pem.client_ca_pem_len = client_ca_pem_len;
  14841. SSLServer svr(server_pem);
  14842. ASSERT_TRUE(svr.is_valid());
  14843. RejectsClientWithoutCert(svr);
  14844. }
  14845. // An empty CA fails to load instead of turning the check off
  14846. server_pem.client_ca_pem = "";
  14847. server_pem.client_ca_pem_len = 0;
  14848. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14849. }
  14850. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14851. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14852. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14853. true);
  14854. }
  14855. // A length shorter than the PEM cuts it short, so it no longer loads
  14856. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14857. std::string cert, key;
  14858. read_file(SERVER_CERT_FILE, cert);
  14859. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14860. for (auto cut_cert : {true, false}) {
  14861. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14862. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14863. SSLServer::PemMemory server_pem = {
  14864. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14865. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14866. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14867. key_len, nullptr};
  14868. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14869. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14870. key.c_str(), key_len, nullptr};
  14871. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14872. }
  14873. }
  14874. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14875. class NoListenSSLServer : public SSLServer {
  14876. public:
  14877. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14878. const char *client_ca_cert_file_path,
  14879. const char *client_ca_cert_dir_path = nullptr)
  14880. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14881. client_ca_cert_dir_path),
  14882. stop_(false) {}
  14883. std::atomic_bool stop_;
  14884. private:
  14885. bool process_and_close_socket(socket_t /*sock*/) override {
  14886. // Don't create SSL context
  14887. while (!stop_.load()) {
  14888. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14889. }
  14890. return true;
  14891. }
  14892. };
  14893. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14894. CLIENT_CA_CERT_FILE);
  14895. ASSERT_TRUE(svr.is_valid());
  14896. // Keep-alive parking would bypass the override.
  14897. svr.set_keep_alive_parking(false);
  14898. svr.Get("/test", [&](const Request &, Response &res) {
  14899. res.set_content("test", "text/plain");
  14900. });
  14901. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14902. auto se = detail::scope_exit([&] {
  14903. svr.stop_ = true;
  14904. svr.stop();
  14905. t.join();
  14906. ASSERT_FALSE(svr.is_running());
  14907. });
  14908. svr.wait_until_ready();
  14909. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14910. cli.enable_server_certificate_verification(false);
  14911. cli.set_connection_timeout(1);
  14912. auto res = cli.Get("/test");
  14913. ASSERT_TRUE(!res);
  14914. EXPECT_EQ(Error::SSLConnection, res.error());
  14915. // Timeout results in WantRead error code (maps to backend-specific value)
  14916. EXPECT_NE(0, res.ssl_error());
  14917. }
  14918. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14919. // Test SSLServer with client certificate verification using the standard
  14920. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14922. CLIENT_CA_CERT_DIR);
  14923. ASSERT_TRUE(svr.is_valid());
  14924. svr.Get("/test", [&](const Request &req, Response &res) {
  14925. res.set_content("test", "text/plain");
  14926. auto cert = req.peer_cert();
  14927. ASSERT_TRUE(static_cast<bool>(cert));
  14928. auto common_name = cert.subject_cn();
  14929. EXPECT_EQ("Common Name", common_name);
  14930. });
  14931. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14932. auto se = detail::scope_exit([&] {
  14933. svr.stop();
  14934. t.join();
  14935. ASSERT_FALSE(svr.is_running());
  14936. });
  14937. svr.wait_until_ready();
  14938. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14939. cli.enable_server_certificate_verification(false);
  14940. cli.set_connection_timeout(30);
  14941. auto res = cli.Get("/test");
  14942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14943. ASSERT_EQ(StatusCode::OK_200, res->status);
  14944. }
  14945. // Test verify_hostname on every backend: a host is named by a SAN only
  14946. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14947. using namespace httplib::tls;
  14948. // We need a running server to test against
  14949. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14950. ASSERT_TRUE(svr.is_valid());
  14951. svr.Get("/test", [](const Request &, Response &res) {
  14952. res.set_content("ok", "text/plain");
  14953. });
  14954. thread t([&]() { svr.listen(HOST, PORT); });
  14955. auto se = detail::scope_exit([&] {
  14956. svr.stop();
  14957. t.join();
  14958. });
  14959. svr.wait_until_ready();
  14960. bool verify_callback_called = false;
  14961. bool verify_result_wrong = false;
  14962. SSLClient cli(HOST, PORT);
  14963. cli.enable_server_certificate_verification(true);
  14964. cli.set_ca_cert_path(CA_CERT_FILE);
  14965. cli.set_connection_timeout(5);
  14966. // Note: Test certificate has CN="Common Name", not "localhost"
  14967. bool verify_result_cn = false;
  14968. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14969. verify_callback_called = true;
  14970. if (!ctx.cert) return false;
  14971. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  14972. verify_result_cn = ctx.check_hostname("Common Name");
  14973. // Test 2: wrong hostname should not match
  14974. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14975. return true; // Accept for the purpose of this test
  14976. });
  14977. auto res = cli.Get("/test");
  14978. // The request may succeed or fail depending on cert configuration
  14979. // but the callback should have been called
  14980. ASSERT_TRUE(verify_callback_called)
  14981. << "Verify callback should have been called";
  14982. EXPECT_FALSE(verify_result_cn)
  14983. << "verify_hostname must not match the certificate CN (no SAN)";
  14984. // Wrong hostname should not match
  14985. EXPECT_FALSE(verify_result_wrong)
  14986. << "verify_hostname should not match 'wronghost.example.com'";
  14987. }
  14988. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  14989. // backend verifies it.
  14990. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  14991. // Certificate CN is "localhost" and it carries no SAN.
  14992. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14993. ASSERT_TRUE(svr.is_valid());
  14994. svr.Get("/test", [](const Request &, Response &res) {
  14995. res.set_content("ok", "text/plain");
  14996. });
  14997. auto port = svr.bind_to_any_port(HOST);
  14998. thread t([&]() { svr.listen_after_bind(); });
  14999. auto se = detail::scope_exit([&] {
  15000. svr.stop();
  15001. t.join();
  15002. });
  15003. svr.wait_until_ready();
  15004. SSLClient cli("localhost", port);
  15005. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15006. cli.enable_server_certificate_verification(true);
  15007. cli.set_connection_timeout(5);
  15008. auto res = cli.Get("/test");
  15009. ASSERT_FALSE(res);
  15010. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15011. // The same certificate is accepted once host name verification is off, so the
  15012. // failure above is the host name and not the chain.
  15013. cli.enable_server_hostname_verification(false);
  15014. res = cli.Get("/test");
  15015. ASSERT_TRUE(res) << to_string(res.error());
  15016. EXPECT_EQ(StatusCode::OK_200, res->status);
  15017. }
  15018. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15019. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15020. // X509_check_ip behavior and must hold for every backend.
  15021. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15022. using namespace httplib::tls;
  15023. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15024. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15025. ASSERT_TRUE(svr.is_valid());
  15026. svr.Get("/test", [](const Request &, Response &res) {
  15027. res.set_content("ok", "text/plain");
  15028. });
  15029. thread t([&]() { svr.listen(HOST, PORT); });
  15030. auto se = detail::scope_exit([&] {
  15031. svr.stop();
  15032. t.join();
  15033. });
  15034. svr.wait_until_ready();
  15035. bool verify_callback_called = false;
  15036. bool ip_matched_via_cn = true;
  15037. SSLClient cli(HOST, PORT);
  15038. cli.enable_server_certificate_verification(true);
  15039. cli.set_ca_cert_path(CA_CERT_FILE);
  15040. cli.set_connection_timeout(5);
  15041. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15042. verify_callback_called = true;
  15043. if (!ctx.cert) return false;
  15044. // The IP appears only in the CN, so it must NOT be accepted.
  15045. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15046. return true; // Accept for the purpose of this test
  15047. });
  15048. cli.Get("/test");
  15049. ASSERT_TRUE(verify_callback_called)
  15050. << "Verify callback should have been called";
  15051. EXPECT_FALSE(ip_matched_via_cn)
  15052. << "An IP host must not be authenticated via the certificate CN";
  15053. }
  15054. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15055. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15056. using namespace httplib::tls;
  15057. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15058. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15059. ASSERT_TRUE(svr.is_valid());
  15060. svr.Get("/test", [](const Request &, Response &res) {
  15061. res.set_content("ok", "text/plain");
  15062. });
  15063. thread t([&]() { svr.listen(HOST, PORT); });
  15064. auto se = detail::scope_exit([&] {
  15065. svr.stop();
  15066. t.join();
  15067. });
  15068. svr.wait_until_ready();
  15069. bool verify_callback_called = false;
  15070. bool san_matched = false;
  15071. bool wrong_ipv6_matched = true;
  15072. bool cn_ipv6_matched = true;
  15073. SSLClient cli(HOST, PORT);
  15074. cli.enable_server_certificate_verification(true);
  15075. cli.set_ca_cert_path(CA_CERT_FILE);
  15076. cli.set_connection_timeout(5);
  15077. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15078. verify_callback_called = true;
  15079. if (!ctx.cert) return false;
  15080. // Matches the IPv6 iPAddress SAN.
  15081. san_matched = ctx.check_hostname("2001:db8::1");
  15082. // A different IPv6 address must not match.
  15083. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15084. // "::1" lives only in the CN, so it must not be accepted.
  15085. cn_ipv6_matched = ctx.check_hostname("::1");
  15086. return true; // Accept for the purpose of this test
  15087. });
  15088. cli.Get("/test");
  15089. ASSERT_TRUE(verify_callback_called)
  15090. << "Verify callback should have been called";
  15091. EXPECT_TRUE(san_matched)
  15092. << "verify_hostname should match an IPv6 iPAddress SAN";
  15093. EXPECT_FALSE(wrong_ipv6_matched)
  15094. << "verify_hostname should not match a non-matching IPv6 address";
  15095. EXPECT_FALSE(cn_ipv6_matched)
  15096. << "An IPv6 host must not be authenticated via the certificate CN";
  15097. }
  15098. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15099. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15100. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15101. using namespace httplib::tls;
  15102. // SANs: DNS:a.zz, IP:42.46.122.122
  15103. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15104. ASSERT_TRUE(svr.is_valid());
  15105. svr.Get("/test", [](const Request &, Response &res) {
  15106. res.set_content("ok", "text/plain");
  15107. });
  15108. auto port = svr.bind_to_any_port(HOST);
  15109. thread t([&]() { svr.listen_after_bind(); });
  15110. auto se = detail::scope_exit([&] {
  15111. svr.stop();
  15112. t.join();
  15113. });
  15114. svr.wait_until_ready();
  15115. bool verify_callback_called = false;
  15116. bool dns_san_matched = false;
  15117. bool ip_san_matched = false;
  15118. bool ip_matched_via_dns_san = true;
  15119. bool dns_matched_via_ip_san = true;
  15120. bool cn_matched_next_to_dns_san = true;
  15121. SSLClient cli(HOST, port);
  15122. cli.enable_server_certificate_verification(true);
  15123. cli.set_ca_cert_path(CA_CERT_FILE);
  15124. cli.set_connection_timeout(5);
  15125. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15126. verify_callback_called = true;
  15127. if (!ctx.cert) return false;
  15128. dns_san_matched = ctx.check_hostname("a.zz");
  15129. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15130. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15131. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15132. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15133. return true; // Accept for the purpose of this test
  15134. });
  15135. cli.Get("/test");
  15136. ASSERT_TRUE(verify_callback_called)
  15137. << "Verify callback should have been called";
  15138. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15139. EXPECT_TRUE(ip_san_matched)
  15140. << "verify_hostname should match an iPAddress SAN";
  15141. EXPECT_FALSE(ip_matched_via_dns_san)
  15142. << "An IP host must not be authenticated via a dNSName SAN";
  15143. EXPECT_FALSE(dns_matched_via_ip_san)
  15144. << "A DNS host must not be authenticated via an iPAddress SAN";
  15145. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15146. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15147. }
  15148. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15149. // "www.*.example.test" names one host and not every host under example.test.
  15150. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15151. using namespace httplib::tls;
  15152. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15153. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15154. ASSERT_TRUE(svr.is_valid());
  15155. svr.Get("/test", [](const Request &, Response &res) {
  15156. res.set_content("ok", "text/plain");
  15157. });
  15158. auto port = svr.bind_to_any_port(HOST);
  15159. thread t([&]() { svr.listen_after_bind(); });
  15160. auto se = detail::scope_exit([&] {
  15161. svr.stop();
  15162. t.join();
  15163. });
  15164. svr.wait_until_ready();
  15165. bool verify_callback_called = false;
  15166. bool leftmost_wildcard_matched = false;
  15167. bool wildcard_spanned_labels = true;
  15168. bool inner_wildcard_matched = true;
  15169. SSLClient cli(HOST, port);
  15170. cli.enable_server_certificate_verification(true);
  15171. cli.set_ca_cert_path(CA_CERT_FILE);
  15172. cli.set_connection_timeout(5);
  15173. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15174. verify_callback_called = true;
  15175. if (!ctx.cert) return false;
  15176. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15177. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15178. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15179. return true; // Accept for the purpose of this test
  15180. });
  15181. cli.Get("/test");
  15182. ASSERT_TRUE(verify_callback_called)
  15183. << "Verify callback should have been called";
  15184. EXPECT_TRUE(leftmost_wildcard_matched)
  15185. << "A leftmost wildcard should match a single label";
  15186. EXPECT_FALSE(wildcard_spanned_labels)
  15187. << "A wildcard label must not match more than one label";
  15188. EXPECT_FALSE(inner_wildcard_matched)
  15189. << "A wildcard outside the leftmost label must not be honoured";
  15190. }
  15191. // sans() must report each SAN entry under its own type.
  15192. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15193. using namespace httplib::tls;
  15194. // SANs: DNS:a.zz, IP:42.46.122.122
  15195. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15196. ASSERT_TRUE(svr.is_valid());
  15197. svr.Get("/test", [](const Request &, Response &res) {
  15198. res.set_content("ok", "text/plain");
  15199. });
  15200. auto port = svr.bind_to_any_port(HOST);
  15201. thread t([&]() { svr.listen_after_bind(); });
  15202. auto se = detail::scope_exit([&] {
  15203. svr.stop();
  15204. t.join();
  15205. });
  15206. svr.wait_until_ready();
  15207. bool verify_callback_called = false;
  15208. std::vector<SanEntry> sans;
  15209. SSLClient cli(HOST, port);
  15210. cli.enable_server_certificate_verification(true);
  15211. cli.set_ca_cert_path(CA_CERT_FILE);
  15212. cli.set_connection_timeout(5);
  15213. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15214. verify_callback_called = true;
  15215. if (!ctx.cert) return false;
  15216. sans = ctx.sans();
  15217. return true; // Accept for the purpose of this test
  15218. });
  15219. cli.Get("/test");
  15220. ASSERT_TRUE(verify_callback_called)
  15221. << "Verify callback should have been called";
  15222. auto has_san = [&](SanType type, const std::string &value) {
  15223. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15224. return san.type == type && san.value == value;
  15225. });
  15226. };
  15227. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15228. << "sans() should report the dNSName SAN";
  15229. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15230. << "sans() should report the iPAddress SAN";
  15231. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15232. << "sans() must not report the dNSName SAN as an address";
  15233. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15234. << "sans() must not report the iPAddress SAN as a DNS name";
  15235. }
  15236. #endif
  15237. // mbedTLS-specific callback constructor test
  15238. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15239. #ifdef CPPHTTPLIB_SSL_ENABLED
  15240. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15241. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15242. ASSERT_TRUE(svr.is_valid());
  15243. // Set up a handler to verify client certificate is present
  15244. bool client_cert_verified = false;
  15245. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15246. // Verify that client certificate was provided
  15247. client_cert_verified = true;
  15248. res.set_content("success", "text/plain");
  15249. });
  15250. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15251. auto se = detail::scope_exit([&] {
  15252. svr.stop();
  15253. t.join();
  15254. ASSERT_FALSE(svr.is_running());
  15255. });
  15256. svr.wait_until_ready();
  15257. // Client with certificate
  15258. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15259. cli.enable_server_certificate_verification(false);
  15260. cli.set_connection_timeout(30);
  15261. auto res = cli.Get("/test");
  15262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15263. ASSERT_EQ(StatusCode::OK_200, res->status);
  15264. ASSERT_TRUE(client_cert_verified);
  15265. EXPECT_EQ("success", res->body);
  15266. }
  15267. #endif
  15268. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15269. // backends
  15270. #ifdef CPPHTTPLIB_SSL_ENABLED
  15271. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15272. using namespace httplib::tls;
  15273. // Test that when client CA cert file is provided,
  15274. // the server properly requests and validates client certificates
  15275. // Create a server with client authentication
  15276. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15277. ASSERT_TRUE(svr.is_valid());
  15278. bool handler_called = false;
  15279. svr.Get("/test", [&](const Request &req, Response &res) {
  15280. handler_called = true;
  15281. // Verify that a client certificate was provided
  15282. auto cert = req.peer_cert();
  15283. ASSERT_TRUE(static_cast<bool>(cert));
  15284. // Get the issuer name
  15285. std::string issuer_str = cert.issuer_name();
  15286. ASSERT_FALSE(issuer_str.empty());
  15287. // The client certificate should be issued by our test CA
  15288. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15289. res.set_content("authenticated", "text/plain");
  15290. });
  15291. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15292. auto se = detail::scope_exit([&] {
  15293. svr.stop();
  15294. t.join();
  15295. ASSERT_FALSE(svr.is_running());
  15296. });
  15297. svr.wait_until_ready();
  15298. // Connect with a client certificate issued by the CA
  15299. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15300. cli.enable_server_certificate_verification(false);
  15301. cli.set_connection_timeout(30);
  15302. auto res = cli.Get("/test");
  15303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15304. ASSERT_EQ(StatusCode::OK_200, res->status);
  15305. ASSERT_TRUE(handler_called);
  15306. EXPECT_EQ("authenticated", res->body);
  15307. }
  15308. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15309. using namespace httplib::tls;
  15310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15311. ASSERT_TRUE(svr.is_valid());
  15312. svr.Get("/test", [](const Request &, Response &res) {
  15313. res.set_content("ok", "text/plain");
  15314. });
  15315. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15316. auto se = detail::scope_exit([&] {
  15317. svr.stop();
  15318. t.join();
  15319. });
  15320. svr.wait_until_ready();
  15321. SSLClient cli(HOST, PORT);
  15322. cli.enable_server_certificate_verification(false);
  15323. cli.set_connection_timeout(30);
  15324. bool cert_checked = false;
  15325. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15326. if (ctx.cert) {
  15327. auto sans = ctx.sans();
  15328. // Test certificate may or may not have SANs - just verify the API
  15329. // works If SANs exist, verify the types are valid
  15330. for (const auto &san : sans) {
  15331. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15332. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15333. san.type == SanType::OTHER);
  15334. EXPECT_FALSE(san.value.empty());
  15335. }
  15336. cert_checked = true;
  15337. }
  15338. return true;
  15339. });
  15340. auto res = cli.Get("/test");
  15341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15342. EXPECT_TRUE(cert_checked);
  15343. }
  15344. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15345. using namespace httplib::tls;
  15346. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15347. ASSERT_TRUE(svr.is_valid());
  15348. svr.Get("/test", [](const Request &, Response &res) {
  15349. res.set_content("ok", "text/plain");
  15350. });
  15351. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15352. auto se = detail::scope_exit([&] {
  15353. svr.stop();
  15354. t.join();
  15355. });
  15356. svr.wait_until_ready();
  15357. SSLClient cli(HOST, PORT);
  15358. cli.enable_server_certificate_verification(false);
  15359. cli.set_connection_timeout(30);
  15360. bool validity_checked = false;
  15361. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15362. if (ctx.cert) {
  15363. time_t not_before = 0, not_after = 0;
  15364. bool result = ctx.validity(not_before, not_after);
  15365. EXPECT_TRUE(result);
  15366. // Verify that not_before < now < not_after for a valid cert
  15367. time_t now = time(nullptr);
  15368. EXPECT_LT(not_before, now);
  15369. EXPECT_GT(not_after, now);
  15370. validity_checked = true;
  15371. }
  15372. return true;
  15373. });
  15374. auto res = cli.Get("/test");
  15375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15376. EXPECT_TRUE(validity_checked);
  15377. }
  15378. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15379. using namespace httplib::tls;
  15380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15381. ASSERT_TRUE(svr.is_valid());
  15382. svr.Get("/test", [](const Request &, Response &res) {
  15383. res.set_content("ok", "text/plain");
  15384. });
  15385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15386. auto se = detail::scope_exit([&] {
  15387. svr.stop();
  15388. t.join();
  15389. });
  15390. svr.wait_until_ready();
  15391. SSLClient cli(HOST, PORT);
  15392. cli.enable_server_certificate_verification(false);
  15393. cli.set_connection_timeout(30);
  15394. bool serial_checked = false;
  15395. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15396. if (ctx.cert) {
  15397. std::string serial = ctx.serial();
  15398. EXPECT_FALSE(serial.empty());
  15399. // Serial should be a hex string
  15400. for (char c : serial) {
  15401. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15402. (c >= 'a' && c <= 'f'));
  15403. }
  15404. serial_checked = true;
  15405. }
  15406. return true;
  15407. });
  15408. auto res = cli.Get("/test");
  15409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15410. EXPECT_TRUE(serial_checked);
  15411. }
  15412. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15413. // Test 1: Valid CA file - no error should be recorded
  15414. {
  15415. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15416. CLIENT_CA_CERT_FILE);
  15417. ASSERT_TRUE(svr.is_valid());
  15418. // With valid setup, last_ssl_error should be 0
  15419. EXPECT_EQ(0, svr.ssl_last_error());
  15420. }
  15421. // Test 2: Invalid CA file content
  15422. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15423. {
  15424. // Create a temporary file with completely invalid content
  15425. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15426. {
  15427. std::ofstream ofs(temp_invalid_ca);
  15428. ofs << "This is not a certificate file at all\n";
  15429. ofs << "Just plain text content\n";
  15430. }
  15431. // Create server with invalid CA file
  15432. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15433. // Clean up temporary file
  15434. std::remove(temp_invalid_ca);
  15435. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15436. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15437. // Note: SSL_CTX_load_verify_locations typically fails first,
  15438. // but our error handling code path is still exercised
  15439. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15440. }
  15441. }
  15442. TEST(VerifyCallbackTest, VerifyContextFields) {
  15443. using namespace httplib::tls;
  15444. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15445. ASSERT_TRUE(svr.is_valid());
  15446. svr.Get("/test", [](const Request &, Response &res) {
  15447. res.set_content("ok", "text/plain");
  15448. });
  15449. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15450. auto se = detail::scope_exit([&] {
  15451. svr.stop();
  15452. t.join();
  15453. });
  15454. svr.wait_until_ready();
  15455. SSLClient cli(HOST, PORT);
  15456. cli.enable_server_certificate_verification(false);
  15457. cli.set_connection_timeout(30);
  15458. int callback_count = 0;
  15459. bool saw_leaf_cert = false;
  15460. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15461. if (ctx.cert) {
  15462. callback_count++;
  15463. // We should see at least one certificate (the leaf)
  15464. std::string cn = ctx.subject_cn();
  15465. if (!cn.empty()) { saw_leaf_cert = true; }
  15466. // Verify context fields are populated
  15467. EXPECT_NE(ctx.session, nullptr);
  15468. EXPECT_GE(ctx.depth, 0);
  15469. }
  15470. return true;
  15471. });
  15472. auto res = cli.Get("/test");
  15473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15474. EXPECT_GT(callback_count, 0);
  15475. EXPECT_TRUE(saw_leaf_cert);
  15476. }
  15477. // A verifier that accepts runs alongside the built-in verification, and is the
  15478. // only check once that is turned off.
  15479. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15480. using namespace httplib::tls;
  15481. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15482. ASSERT_TRUE(svr.is_valid());
  15483. svr.Get("/test", [](const Request &, Response &res) {
  15484. res.set_content("ok", "text/plain");
  15485. });
  15486. auto port = svr.bind_to_any_port(HOST);
  15487. thread t([&]() { svr.listen_after_bind(); });
  15488. auto se = detail::scope_exit([&] {
  15489. svr.stop();
  15490. t.join();
  15491. });
  15492. svr.wait_until_ready();
  15493. SSLClient cli(HOST, port);
  15494. cli.enable_server_hostname_verification(false);
  15495. auto calls = 0;
  15496. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15497. calls++;
  15498. return true;
  15499. });
  15500. // cert.pem is not trusted
  15501. auto res = cli.Get("/test");
  15502. ASSERT_FALSE(res);
  15503. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15504. EXPECT_GT(calls, 0);
  15505. cli.enable_server_certificate_verification(false);
  15506. res = cli.Get("/test");
  15507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15508. EXPECT_EQ("ok", res->body);
  15509. }
  15510. // A verifier belongs to the client that set it, not to the thread that set it.
  15511. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15512. using namespace httplib::tls;
  15513. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15514. ASSERT_TRUE(svr.is_valid());
  15515. svr.Get("/test", [](const Request &, Response &res) {
  15516. res.set_content("ok", "text/plain");
  15517. });
  15518. auto port = svr.bind_to_any_port(HOST);
  15519. thread t([&]() { svr.listen_after_bind(); });
  15520. auto se = detail::scope_exit([&] {
  15521. svr.stop();
  15522. t.join();
  15523. });
  15524. svr.wait_until_ready();
  15525. auto rejecting_calls = 0;
  15526. SSLClient rejecting(HOST, port);
  15527. rejecting.enable_server_certificate_verification(false);
  15528. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15529. rejecting_calls++;
  15530. return false;
  15531. });
  15532. auto accepting_calls = 0;
  15533. SSLClient accepting(HOST, port);
  15534. accepting.enable_server_certificate_verification(false);
  15535. // Set on another thread than the requests below.
  15536. thread([&]() {
  15537. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15538. accepting_calls++;
  15539. return true;
  15540. });
  15541. }).join();
  15542. // Requested on another thread than the verifier was set on.
  15543. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15544. EXPECT_GT(rejecting_calls, 0);
  15545. auto res = accepting.Get("/test");
  15546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15547. EXPECT_GT(accepting_calls, 0);
  15548. }
  15549. // A verifier replaced while a handshake runs it lives until it returns.
  15550. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15551. using namespace httplib::tls;
  15552. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15553. ASSERT_TRUE(svr.is_valid());
  15554. svr.Get("/test", [](const Request &, Response &res) {
  15555. res.set_content("ok", "text/plain");
  15556. });
  15557. auto port = svr.bind_to_any_port(HOST);
  15558. thread t([&]() { svr.listen_after_bind(); });
  15559. auto se = detail::scope_exit([&] {
  15560. svr.stop();
  15561. t.join();
  15562. });
  15563. svr.wait_until_ready();
  15564. SSLClient cli(HOST, port);
  15565. cli.enable_server_certificate_verification(false);
  15566. std::promise<void> entered;
  15567. std::promise<void> replaced;
  15568. auto replaced_future = replaced.get_future();
  15569. auto first_call = true;
  15570. // Long enough to live on the heap
  15571. std::string expected(64, 'v');
  15572. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15573. if (first_call) {
  15574. first_call = false;
  15575. entered.set_value();
  15576. replaced_future.wait();
  15577. }
  15578. return expected == std::string(64, 'v');
  15579. });
  15580. thread request([&]() {
  15581. auto res = cli.Get("/test");
  15582. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15583. });
  15584. entered.get_future().wait();
  15585. cli.set_server_certificate_verifier(
  15586. [](const VerifyContext &) { return true; });
  15587. replaced.set_value();
  15588. request.join();
  15589. }
  15590. // VerifyContext::session is the same handle the other tls:: functions take.
  15591. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15592. using namespace httplib::tls;
  15593. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15594. ASSERT_TRUE(svr.is_valid());
  15595. svr.Get("/test", [](const Request &, Response &res) {
  15596. res.set_content("ok", "text/plain");
  15597. });
  15598. auto port = svr.bind_to_any_port(HOST);
  15599. thread t([&]() { svr.listen_after_bind(); });
  15600. auto se = detail::scope_exit([&] {
  15601. svr.stop();
  15602. t.join();
  15603. });
  15604. svr.wait_until_ready();
  15605. SSLClient cli(HOST, port);
  15606. cli.enable_server_certificate_verification(false);
  15607. session_t verifier_session = nullptr;
  15608. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15609. verifier_session = ctx.session;
  15610. return true;
  15611. });
  15612. session_t session_verifier_session = nullptr;
  15613. cli.set_session_verifier([&](session_t session) {
  15614. session_verifier_session = session;
  15615. return SSLVerifierResponse::NoDecisionMade;
  15616. });
  15617. auto res = cli.Get("/test");
  15618. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15619. EXPECT_NE(nullptr, verifier_session);
  15620. EXPECT_EQ(session_verifier_session, verifier_session);
  15621. }
  15622. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15623. using httplib::tls::TlsError;
  15624. // Test that verify_error_to_string returns empty for success
  15625. std::string success_str = TlsError::verify_error_to_string(0);
  15626. EXPECT_TRUE(success_str.empty());
  15627. // Test that verify_error_to_string returns non-empty for error codes
  15628. // Using a common error code (certificate expired)
  15629. std::string error_str =
  15630. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15631. EXPECT_FALSE(error_str.empty());
  15632. }
  15633. TEST(SessionVerifierTest, CertificateAccepted) {
  15634. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15635. ASSERT_TRUE(svr.is_valid());
  15636. svr.Get("/test", [](const Request &, Response &res) {
  15637. res.set_content("ok", "text/plain");
  15638. });
  15639. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15640. auto se = detail::scope_exit([&] {
  15641. svr.stop();
  15642. t.join();
  15643. });
  15644. svr.wait_until_ready();
  15645. SSLClient cli(HOST, PORT);
  15646. cli.enable_server_certificate_verification(false);
  15647. cli.set_connection_timeout(30);
  15648. bool callback_called = false;
  15649. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15650. EXPECT_NE(session, nullptr);
  15651. callback_called = true;
  15652. return SSLVerifierResponse::CertificateAccepted;
  15653. });
  15654. auto res = cli.Get("/test");
  15655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15656. EXPECT_EQ(200, res->status);
  15657. EXPECT_TRUE(callback_called);
  15658. }
  15659. TEST(SessionVerifierTest, CertificateRejected) {
  15660. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15661. ASSERT_TRUE(svr.is_valid());
  15662. svr.Get("/test", [](const Request &, Response &res) {
  15663. res.set_content("ok", "text/plain");
  15664. });
  15665. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15666. auto se = detail::scope_exit([&] {
  15667. svr.stop();
  15668. t.join();
  15669. });
  15670. svr.wait_until_ready();
  15671. SSLClient cli(HOST, PORT);
  15672. cli.enable_server_certificate_verification(false);
  15673. cli.set_connection_timeout(30);
  15674. bool callback_called = false;
  15675. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15676. EXPECT_NE(session, nullptr);
  15677. callback_called = true;
  15678. return SSLVerifierResponse::CertificateRejected;
  15679. });
  15680. auto res = cli.Get("/test");
  15681. EXPECT_FALSE(res);
  15682. EXPECT_TRUE(callback_called);
  15683. }
  15684. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15685. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15686. ASSERT_TRUE(svr.is_valid());
  15687. svr.Get("/test", [](const Request &, Response &res) {
  15688. res.set_content("ok", "text/plain");
  15689. });
  15690. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15691. auto se = detail::scope_exit([&] {
  15692. svr.stop();
  15693. t.join();
  15694. });
  15695. svr.wait_until_ready();
  15696. // NoDecisionMade with verification disabled should succeed (no default check)
  15697. SSLClient cli(HOST, PORT);
  15698. cli.enable_server_certificate_verification(false);
  15699. cli.set_connection_timeout(30);
  15700. bool callback_called = false;
  15701. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15702. EXPECT_NE(session, nullptr);
  15703. callback_called = true;
  15704. return SSLVerifierResponse::NoDecisionMade;
  15705. });
  15706. auto res = cli.Get("/test");
  15707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15708. EXPECT_EQ(200, res->status);
  15709. EXPECT_TRUE(callback_called);
  15710. }
  15711. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15713. ASSERT_TRUE(svr.is_valid());
  15714. svr.Get("/test", [](const Request &, Response &res) {
  15715. res.set_content("ok", "text/plain");
  15716. });
  15717. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15718. auto se = detail::scope_exit([&] {
  15719. svr.stop();
  15720. t.join();
  15721. });
  15722. svr.wait_until_ready();
  15723. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15724. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15725. // so we only check that the request fails, not whether the callback was
  15726. // called.
  15727. SSLClient cli(HOST, PORT);
  15728. cli.enable_server_certificate_verification(true);
  15729. cli.set_connection_timeout(30);
  15730. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15731. EXPECT_NE(session, nullptr);
  15732. return SSLVerifierResponse::NoDecisionMade;
  15733. });
  15734. auto res = cli.Get("/test");
  15735. EXPECT_FALSE(res);
  15736. }
  15737. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15738. // Test SSL server using PemMemory constructor with client CA certificates
  15739. // Read PEM files
  15740. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15741. read_file(SERVER_CERT_FILE, server_cert_pem);
  15742. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15743. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15744. // Create SSLServer with PemMemory constructor including client CA
  15745. SSLServer::PemMemory server_pem = {
  15746. server_cert_pem.c_str(),
  15747. server_cert_pem.size(),
  15748. server_key_pem.c_str(),
  15749. server_key_pem.size(),
  15750. client_ca_pem.c_str(),
  15751. client_ca_pem.size(),
  15752. nullptr // no password for server key
  15753. };
  15754. SSLServer svr(server_pem);
  15755. ASSERT_TRUE(svr.is_valid());
  15756. // No SSL error should be recorded for valid setup
  15757. EXPECT_EQ(0, svr.ssl_last_error());
  15758. // Set up server endpoints
  15759. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15760. res.set_content("ok", "text/plain");
  15761. });
  15762. // Start server in a thread
  15763. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15764. svr.wait_until_ready();
  15765. // Connect with client certificate (using constructor with paths)
  15766. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15767. cli.enable_server_certificate_verification(false);
  15768. auto res = cli.Get("/test-pem-ca");
  15769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15770. EXPECT_EQ(200, res->status);
  15771. EXPECT_EQ("ok", res->body);
  15772. svr.stop();
  15773. server_thread.join();
  15774. }
  15775. #endif
  15776. #ifdef _WIN32
  15777. TEST(CleanupTest, WSACleanup) {
  15778. int ret = WSACleanup();
  15779. ASSERT_EQ(0, ret);
  15780. }
  15781. #endif
  15782. #ifndef CPPHTTPLIB_SSL_ENABLED
  15783. TEST(NoSSLSupport, SimpleInterface) {
  15784. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15785. }
  15786. #endif
  15787. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15788. TEST(InvalidScheme, SimpleInterface) {
  15789. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15790. }
  15791. #endif
  15792. TEST(NoScheme, SimpleInterface) {
  15793. Client cli("yahoo.com:80");
  15794. ASSERT_TRUE(cli.is_valid());
  15795. }
  15796. TEST(SendAPI, SimpleInterface_Online) {
  15797. Client cli("http://yahoo.com");
  15798. Request req;
  15799. req.method = "GET";
  15800. req.path = "/";
  15801. auto res = cli.send(req);
  15802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15803. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15804. }
  15805. TEST(SendAPI, WithParamsInRequest) {
  15806. Server svr;
  15807. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15808. EXPECT_TRUE(req.has_param("test"));
  15809. EXPECT_EQ("test_value", req.get_param_value("test"));
  15810. });
  15811. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15812. auto se = detail::scope_exit([&] {
  15813. svr.stop();
  15814. t.join();
  15815. ASSERT_FALSE(svr.is_running());
  15816. });
  15817. svr.wait_until_ready();
  15818. Client cli(HOST, PORT);
  15819. {
  15820. Request req;
  15821. req.method = "GET";
  15822. req.path = "/";
  15823. req.params.emplace("test", "test_value");
  15824. auto res = cli.send(req);
  15825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15826. }
  15827. {
  15828. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15830. }
  15831. }
  15832. TEST(ClientImplMethods, GetSocketTest) {
  15833. httplib::Server svr;
  15834. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15835. res.status = StatusCode::OK_200;
  15836. });
  15837. auto port = svr.bind_to_any_port("127.0.0.1");
  15838. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15839. auto se = detail::scope_exit([&] {
  15840. svr.stop();
  15841. thread.join();
  15842. ASSERT_FALSE(svr.is_running());
  15843. });
  15844. svr.wait_until_ready();
  15845. {
  15846. httplib::Client cli("127.0.0.1", port);
  15847. cli.set_keep_alive(true);
  15848. // Use the behavior of cpp-httplib of opening the connection
  15849. // only when the first request happens. If that changes,
  15850. // this test would be obsolete.
  15851. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15852. // This also implicitly tests the server. But other tests would fail much
  15853. // earlier than this one to be considered.
  15854. auto res = cli.Get("/");
  15855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15856. EXPECT_EQ(StatusCode::OK_200, res->status);
  15857. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15858. }
  15859. }
  15860. #ifdef CPPHTTPLIB_SSL_ENABLED
  15861. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15862. Client cli("http://yahoo.com");
  15863. auto res = cli.Get("/");
  15864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15865. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15866. cli.set_follow_location(true);
  15867. res = cli.Get("/");
  15868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15869. EXPECT_EQ(StatusCode::OK_200, res->status);
  15870. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15871. }
  15872. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15873. Client cli("https://yahoo.com");
  15874. auto res = cli.Get("/");
  15875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15876. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15877. cli.set_follow_location(true);
  15878. res = cli.Get("/");
  15879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15880. EXPECT_EQ(StatusCode::OK_200, res->status);
  15881. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15882. }
  15883. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15884. Client cli("https://yahoo.com");
  15885. auto res = cli.Get("/");
  15886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15887. ASSERT_FALSE(!res);
  15888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15889. ASSERT_FALSE(res == nullptr);
  15890. ASSERT_TRUE(res != nullptr);
  15891. EXPECT_EQ(Error::Success, res.error());
  15892. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15893. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15894. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15895. cli.set_follow_location(true);
  15896. res = cli.Get("/");
  15897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15898. EXPECT_EQ(Error::Success, res.error());
  15899. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15900. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15901. EXPECT_EQ(StatusCode::OK_200, res->status);
  15902. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15903. }
  15904. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15905. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15906. Client cli("https://cdnjs.cloudflare.com");
  15907. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15908. Headers{{"Accept-Encoding", "br"}});
  15909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15910. EXPECT_EQ(StatusCode::OK_200, res->status);
  15911. EXPECT_EQ(287630U, res->body.size());
  15912. EXPECT_EQ("application/javascript; charset=utf-8",
  15913. res->get_header_value("Content-Type"));
  15914. }
  15915. #endif
  15916. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15917. #undef REDIR_HOST // Silence compiler warning
  15918. #define REDIR_HOST "https://httpbingo.org"
  15919. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15920. Client cli(REDIR_HOST);
  15921. cli.set_follow_location(true);
  15922. auto res = retry_service_failures([&] {
  15923. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15924. });
  15925. SKIP_ON_SERVICE_FAILURE(res);
  15926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15927. EXPECT_EQ(StatusCode::OK_200, res->status);
  15928. }
  15929. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15930. Client cli(REDIR_HOST);
  15931. cli.set_follow_location(true);
  15932. Params params;
  15933. params.emplace("url", "http://example.com");
  15934. params.emplace("status_code", "302");
  15935. auto res = retry_service_failures(
  15936. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15937. SKIP_ON_SERVICE_FAILURE(res);
  15938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15939. EXPECT_EQ(StatusCode::OK_200, res->status);
  15940. }
  15941. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15942. Client cli(REDIR_HOST);
  15943. cli.set_follow_location(true);
  15944. Params params;
  15945. params.emplace("url", "http://example.com");
  15946. auto res = retry_service_failures([&] {
  15947. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15948. });
  15949. SKIP_ON_SERVICE_FAILURE(res);
  15950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15951. EXPECT_EQ(StatusCode::OK_200, res->status);
  15952. }
  15953. TEST(HttpToHttpsRedirectTest, CertFile) {
  15954. auto ssl_port = PORT + 1;
  15955. Server svr;
  15956. ASSERT_TRUE(svr.is_valid());
  15957. svr.Get("/index", [&](const Request &, Response &res) {
  15958. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15959. "/index");
  15960. svr.stop();
  15961. });
  15962. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15963. ASSERT_TRUE(ssl_svr.is_valid());
  15964. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15965. res.set_content("test", "text/plain");
  15966. ssl_svr.stop();
  15967. });
  15968. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15969. thread t2 =
  15970. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15971. auto se = detail::scope_exit([&] {
  15972. t2.join();
  15973. t.join();
  15974. ASSERT_FALSE(svr.is_running());
  15975. });
  15976. svr.wait_until_ready();
  15977. ssl_svr.wait_until_ready();
  15978. Client cli("127.0.0.1", PORT);
  15979. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15980. cli.enable_server_certificate_verification(true);
  15981. cli.set_follow_location(true);
  15982. cli.set_connection_timeout(30);
  15983. auto res = cli.Get("/index");
  15984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15985. ASSERT_EQ(StatusCode::OK_200, res->status);
  15986. }
  15987. TEST(UppercaseSchemeTest, UsesTLS) {
  15988. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15989. ASSERT_TRUE(ssl_svr.is_valid());
  15990. ssl_svr.Get("/index", [](const Request &, Response &res) {
  15991. res.set_content("test", "text/plain");
  15992. });
  15993. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  15994. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  15995. Server svr;
  15996. svr.Get("/index", [&](const Request &, Response &res) {
  15997. res.set_redirect(https_url + "/index");
  15998. });
  15999. auto port = svr.bind_to_any_port("127.0.0.1");
  16000. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  16001. auto t2 = thread([&] { svr.listen_after_bind(); });
  16002. auto se = detail::scope_exit([&] {
  16003. svr.stop();
  16004. ssl_svr.stop();
  16005. t2.join();
  16006. t.join();
  16007. });
  16008. ssl_svr.wait_until_ready();
  16009. svr.wait_until_ready();
  16010. {
  16011. Client cli(https_url);
  16012. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16013. auto res = cli.Get("/index");
  16014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16015. EXPECT_EQ("test", res->body);
  16016. }
  16017. {
  16018. Client cli("127.0.0.1", port);
  16019. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16020. cli.set_follow_location(true);
  16021. auto res = cli.Get("/index");
  16022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16023. EXPECT_EQ("test", res->body);
  16024. }
  16025. }
  16026. TEST(SSLClientRedirectTest, CertFile) {
  16027. auto ssl_port = PORT + 1;
  16028. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16029. ASSERT_TRUE(ssl_svr1.is_valid());
  16030. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16031. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16032. "/index");
  16033. ssl_svr1.stop();
  16034. });
  16035. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16036. ASSERT_TRUE(ssl_svr2.is_valid());
  16037. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16038. res.set_content("test", "text/plain");
  16039. ssl_svr2.stop();
  16040. });
  16041. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16042. thread t2 =
  16043. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16044. auto se = detail::scope_exit([&] {
  16045. t2.join();
  16046. t.join();
  16047. ASSERT_FALSE(ssl_svr1.is_running());
  16048. });
  16049. ssl_svr1.wait_until_ready();
  16050. ssl_svr2.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_server_certificate_verification(true);
  16056. cli.set_follow_location(true);
  16057. cli.set_connection_timeout(30);
  16058. auto res = cli.Get("/index");
  16059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16060. ASSERT_EQ(StatusCode::OK_200, res->status);
  16061. }
  16062. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16063. // another port, so the client follows it with a new client.
  16064. static Result GetThroughTlsRedirectToDifferentPort(
  16065. const std::function<void(SSLClient &)> &setup,
  16066. const char *target_cert = SERVER_CERT2_FILE,
  16067. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16068. auto ssl_port = PORT + 1;
  16069. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16070. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16071. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16072. "/index");
  16073. });
  16074. SSLServer ssl_svr2(target_cert, target_key);
  16075. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16076. res.set_content("test", "text/plain");
  16077. });
  16078. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16079. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16080. auto se = detail::scope_exit([&] {
  16081. ssl_svr2.stop();
  16082. ssl_svr1.stop();
  16083. t2.join();
  16084. t.join();
  16085. });
  16086. ssl_svr1.wait_until_ready();
  16087. ssl_svr2.wait_until_ready();
  16088. SSLClient cli("127.0.0.1", PORT);
  16089. cli.set_follow_location(true);
  16090. cli.set_connection_timeout(30);
  16091. setup(cli);
  16092. return cli.Get("/index");
  16093. }
  16094. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16095. auto calls = 0;
  16096. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16097. cli.enable_server_certificate_verification(false);
  16098. // Accept the first server only.
  16099. cli.set_session_verifier([&](tls::session_t) {
  16100. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16101. : SSLVerifierResponse::CertificateRejected;
  16102. });
  16103. });
  16104. ASSERT_FALSE(res);
  16105. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16106. EXPECT_EQ(2, calls);
  16107. }
  16108. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16109. std::string pinned;
  16110. auto res = GetThroughTlsRedirectToDifferentPort(
  16111. [&](SSLClient &cli) {
  16112. cli.enable_server_certificate_verification(false);
  16113. // Pin the first certificate seen.
  16114. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16115. if (pinned.empty()) { pinned = ctx.serial(); }
  16116. return ctx.serial() == pinned;
  16117. });
  16118. },
  16119. // A certificate other than the first server's.
  16120. SERVER_CERT_FILE);
  16121. EXPECT_FALSE(res);
  16122. EXPECT_FALSE(pinned.empty());
  16123. }
  16124. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16125. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16126. std::string cert;
  16127. read_file(SERVER_CERT2_FILE, cert);
  16128. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16129. });
  16130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16131. EXPECT_EQ(StatusCode::OK_200, res->status);
  16132. }
  16133. // The target's certificate is signed by the root CA, which the first server's
  16134. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16135. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16136. auto res = GetThroughTlsRedirectToDifferentPort(
  16137. [](SSLClient &cli) {
  16138. std::string root_ca, cert;
  16139. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16140. read_file(SERVER_CERT2_FILE, cert);
  16141. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16142. cli.load_ca_cert_store(cert.data(), cert.size());
  16143. cli.enable_server_hostname_verification(false);
  16144. },
  16145. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16147. EXPECT_EQ(StatusCode::OK_200, res->status);
  16148. }
  16149. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16150. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16151. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16152. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16153. auto res = GetThroughTlsRedirectToDifferentPort(
  16154. [](SSLClient &cli) {
  16155. std::string root_ca, cert;
  16156. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16157. read_file(SERVER_CERT2_FILE, cert);
  16158. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16159. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16160. cli.enable_server_hostname_verification(false);
  16161. },
  16162. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16163. ASSERT_FALSE(res);
  16164. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16165. }
  16166. #endif
  16167. #endif
  16168. #ifdef CPPHTTPLIB_SSL_ENABLED
  16169. // Test that set_ca_cert_store() skips system certs (consistent with
  16170. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16171. // should be trusted - system certs should NOT be loaded.
  16172. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16173. // Load a specific cert that is NOT a system CA cert
  16174. std::string cert;
  16175. read_file(SERVER_CERT2_FILE, cert);
  16176. SSLClient cli("google.com");
  16177. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16178. cli.enable_server_certificate_verification(true);
  16179. // This should FAIL because:
  16180. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16181. // 2. System certs should NOT be loaded when custom store is set
  16182. // If system certs WERE loaded, this would succeed
  16183. auto res = cli.Get("/");
  16184. ASSERT_FALSE(res);
  16185. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16186. }
  16187. // Same as above, but through the native store handle path. Regression test:
  16188. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16189. // merged system certs into the user-provided store.
  16190. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16191. std::string cert;
  16192. read_file(SERVER_CERT2_FILE, cert);
  16193. SSLClient cli("google.com");
  16194. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16195. cli.enable_server_certificate_verification(true);
  16196. auto res = cli.Get("/");
  16197. ASSERT_FALSE(res);
  16198. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16199. }
  16200. // A custom store set via the native handle must still verify a server whose
  16201. // cert it does contain.
  16202. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16203. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16204. ASSERT_TRUE(svr.is_valid());
  16205. svr.Get("/test", [&](const Request &, Response &res) {
  16206. res.set_content("test", "text/plain");
  16207. });
  16208. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16209. auto se = detail::scope_exit([&] {
  16210. svr.stop();
  16211. t.join();
  16212. ASSERT_FALSE(svr.is_running());
  16213. });
  16214. svr.wait_until_ready();
  16215. SSLClient cli("127.0.0.1", PORT);
  16216. std::string cert;
  16217. read_file(SERVER_CERT2_FILE, cert);
  16218. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16219. cli.enable_server_certificate_verification(true);
  16220. cli.set_connection_timeout(30);
  16221. auto res = cli.Get("/test");
  16222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16223. ASSERT_EQ(StatusCode::OK_200, res->status);
  16224. }
  16225. // CA certs loaded through the universal Client must be transferred to the
  16226. // client created internally for following an HTTPS redirect. Regression test:
  16227. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16228. // the CA data for redirect transfer.
  16229. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16230. auto ssl_port = PORT + 1;
  16231. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16232. ASSERT_TRUE(ssl_svr1.is_valid());
  16233. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16234. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16235. "/index");
  16236. });
  16237. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16238. ASSERT_TRUE(ssl_svr2.is_valid());
  16239. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16240. res.set_content("test", "text/plain");
  16241. });
  16242. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16243. thread t2 =
  16244. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16245. auto se = detail::scope_exit([&] {
  16246. ssl_svr2.stop();
  16247. ssl_svr1.stop();
  16248. t2.join();
  16249. t.join();
  16250. ASSERT_FALSE(ssl_svr1.is_running());
  16251. });
  16252. ssl_svr1.wait_until_ready();
  16253. ssl_svr2.wait_until_ready();
  16254. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16255. std::string cert;
  16256. read_file(SERVER_CERT2_FILE, cert);
  16257. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16258. cli.enable_server_certificate_verification(true);
  16259. cli.set_follow_location(true);
  16260. cli.set_connection_timeout(30);
  16261. auto res = cli.Get("/index");
  16262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16263. ASSERT_EQ(StatusCode::OK_200, res->status);
  16264. }
  16265. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16266. // so a host signed by a system CA verifies even though a custom CA is set
  16267. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16268. std::string cert;
  16269. read_file(SERVER_CERT2_FILE, cert);
  16270. SSLClient cli("google.com");
  16271. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16272. cli.enable_system_ca(true);
  16273. cli.enable_server_certificate_verification(true);
  16274. auto res = cli.Get("/");
  16275. // Any status: Google may redirect or rate-limit CI runners.
  16276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16277. }
  16278. // The custom CA remains effective when combined with the system CA
  16279. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16280. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16281. ASSERT_TRUE(svr.is_valid());
  16282. svr.Get("/test", [&](const Request &, Response &res) {
  16283. res.set_content("test", "text/plain");
  16284. });
  16285. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16286. auto se = detail::scope_exit([&] {
  16287. svr.stop();
  16288. t.join();
  16289. ASSERT_FALSE(svr.is_running());
  16290. });
  16291. svr.wait_until_ready();
  16292. SSLClient cli("127.0.0.1", PORT);
  16293. std::string cert;
  16294. read_file(SERVER_CERT2_FILE, cert);
  16295. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16296. cli.enable_system_ca(true);
  16297. cli.enable_server_certificate_verification(true);
  16298. cli.set_connection_timeout(30);
  16299. auto res = cli.Get("/test");
  16300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16301. ASSERT_EQ(StatusCode::OK_200, res->status);
  16302. }
  16303. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16304. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16305. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16306. static CFDictionaryRef
  16307. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16308. const SecTrustSettingsResult *result) {
  16309. auto constraint =
  16310. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16311. &kCFTypeDictionaryValueCallBacks);
  16312. if (policy) {
  16313. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16314. }
  16315. if (policy_string) {
  16316. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16317. kCFStringEncodingUTF8);
  16318. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16319. CFRelease(str);
  16320. }
  16321. if (result) {
  16322. auto number_value = static_cast<SInt32>(*result);
  16323. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16324. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16325. CFRelease(number);
  16326. }
  16327. return constraint;
  16328. }
  16329. static SecTrustSettingsResult
  16330. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16331. auto trust_settings =
  16332. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16333. for (auto constraint : constraints) {
  16334. CFArrayAppendValue(trust_settings, constraint);
  16335. CFRelease(constraint);
  16336. }
  16337. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16338. CFRelease(trust_settings);
  16339. return result;
  16340. }
  16341. // The system CA loader takes a Keychain certificate as a trusted root only
  16342. // when its Trust Settings say so for SSL, not merely because it has some.
  16343. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16344. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16345. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16346. const auto deny = kSecTrustSettingsResultDeny;
  16347. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16348. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16349. auto x509_policy = SecPolicyCreateBasicX509();
  16350. // "Always Trust", which stores no constraint at all
  16351. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16352. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16353. ssl_trust_settings_result(
  16354. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16355. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16356. ssl_trust_settings_result(
  16357. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16358. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16359. ssl_trust_settings_result(
  16360. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16361. // "Never Trust", for everything or for SSL
  16362. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16363. ssl_trust_settings_result(
  16364. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16365. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16366. ssl_trust_settings_result(
  16367. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16368. // Trusted for another policy, for one host, or not at all
  16369. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16370. ssl_trust_settings_result(
  16371. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16372. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16373. ssl_trust_settings_result({make_usage_constraint(
  16374. ssl_policy, "www.example.com", &trust_root)}));
  16375. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16376. ssl_trust_settings_result(
  16377. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16378. // The first constraint that applies to SSL decides
  16379. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16380. ssl_trust_settings_result(
  16381. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16382. make_usage_constraint(nullptr, nullptr, &deny)}));
  16383. CFRelease(x509_policy);
  16384. CFRelease(ssl_policy);
  16385. }
  16386. #endif
  16387. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16388. // skip chain verification entirely (only the certificate identity was
  16389. // checked), so a server presenting an untrusted certificate with a matching
  16390. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16391. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16392. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16393. ASSERT_TRUE(svr.is_valid());
  16394. svr.Get("/test", [&](const Request &, Response &res) {
  16395. res.set_content("test", "text/plain");
  16396. });
  16397. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16398. auto se = detail::scope_exit([&] {
  16399. svr.stop();
  16400. t.join();
  16401. ASSERT_FALSE(svr.is_running());
  16402. });
  16403. svr.wait_until_ready();
  16404. SSLClient cli("127.0.0.1", PORT);
  16405. std::string cert;
  16406. // A trusted CA that did not sign the server certificate. The server cert
  16407. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16408. // this connection.
  16409. read_file(CLIENT_CA_CERT_FILE, cert);
  16410. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16411. cli.enable_server_certificate_verification(true);
  16412. cli.set_connection_timeout(30);
  16413. auto res = cli.Get("/test");
  16414. ASSERT_FALSE(res);
  16415. }
  16416. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16417. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16418. // CA that failed to come through fails verification instead of trusting them.
  16419. // (wolfSSL does not list the system CAs it loaded.)
  16420. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16421. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16422. ASSERT_TRUE(svr.is_valid());
  16423. auto port = svr.bind_to_any_port("127.0.0.1");
  16424. ASSERT_LT(0, port);
  16425. thread t = thread([&] { svr.listen_after_bind(); });
  16426. auto se = detail::scope_exit([&] {
  16427. svr.stop();
  16428. t.join();
  16429. ASSERT_FALSE(svr.is_running());
  16430. });
  16431. svr.wait_until_ready();
  16432. // The CAs a client trusts once its first request has loaded them
  16433. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16434. Client cli("https://127.0.0.1:" + std::to_string(port));
  16435. setup(cli);
  16436. cli.Get("/");
  16437. return tls::get_ca_names(cli.tls_context()).size();
  16438. };
  16439. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16440. EXPECT_EQ(0u,
  16441. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16442. }
  16443. #endif
  16444. // A TLS setting changed between requests applies to the next one, not just to
  16445. // the next connection
  16446. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16447. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16448. ASSERT_TRUE(svr.is_valid());
  16449. svr.Get("/", [](const Request &req, Response &res) {
  16450. res.set_content(std::to_string(req.remote_port), "text/plain");
  16451. });
  16452. auto port = svr.bind_to_any_port("127.0.0.1");
  16453. ASSERT_LT(0, port);
  16454. thread t = thread([&] { svr.listen_after_bind(); });
  16455. auto se = detail::scope_exit([&] {
  16456. svr.stop();
  16457. t.join();
  16458. ASSERT_FALSE(svr.is_running());
  16459. });
  16460. svr.wait_until_ready();
  16461. SSLClient cli("127.0.0.1", port);
  16462. cli.set_keep_alive(true);
  16463. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16464. cli.enable_server_certificate_verification(false);
  16465. // The port the request went out from, so a new one means a new connection
  16466. auto client_port = [&] {
  16467. auto res = cli.Get("/");
  16468. return res ? res->body : std::string();
  16469. };
  16470. auto last = client_port();
  16471. ASSERT_FALSE(last.empty());
  16472. // Setting a value it already has keeps the connection
  16473. cli.enable_server_certificate_verification(false);
  16474. cli.enable_server_hostname_verification(true);
  16475. EXPECT_EQ(last, client_port());
  16476. cli.enable_server_certificate_verification(true);
  16477. auto res = cli.Get("/");
  16478. EXPECT_FALSE(res);
  16479. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16480. std::string ca;
  16481. read_file(SERVER_CERT2_FILE, ca);
  16482. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16483. last = client_port();
  16484. ASSERT_FALSE(last.empty());
  16485. std::vector<std::function<void()>> setters = {
  16486. [&] { cli.enable_server_hostname_verification(false); },
  16487. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16488. [&] {
  16489. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16490. },
  16491. [&] {
  16492. cli.set_server_certificate_verifier(
  16493. [](const tls::VerifyContext &) { return true; });
  16494. },
  16495. [&] {
  16496. cli.set_session_verifier(
  16497. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16498. },
  16499. };
  16500. for (const auto &setter : setters) {
  16501. setter();
  16502. auto next = client_port();
  16503. ASSERT_FALSE(next.empty());
  16504. EXPECT_NE(last, next);
  16505. last = next;
  16506. }
  16507. cli.set_session_verifier(
  16508. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16509. auto handle = cli.open_stream("GET", "/");
  16510. EXPECT_FALSE(handle.is_valid());
  16511. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16512. }
  16513. // A PEM given to create_ca_store() needs no NUL after it
  16514. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16515. std::string pem;
  16516. read_file(SERVER_CERT2_FILE, pem);
  16517. auto buf = pem + "X";
  16518. auto store = tls::create_ca_store(buf.data(), pem.size());
  16519. EXPECT_TRUE(store != nullptr);
  16520. SSLClient cli("localhost");
  16521. cli.set_ca_cert_store(store);
  16522. }
  16523. // enable_system_ca(false) prevents system CA loading entirely
  16524. TEST(SSLClientTest, DisableSystemCa_Online) {
  16525. SSLClient cli("google.com");
  16526. cli.enable_system_ca(false);
  16527. cli.enable_server_certificate_verification(true);
  16528. auto res = cli.Get("/");
  16529. ASSERT_FALSE(res);
  16530. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16531. // itself when the CA chain is empty
  16532. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16533. res.error() == Error::SSLConnection);
  16534. }
  16535. // The universal Client forwards enable_system_ca()
  16536. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16537. std::string cert;
  16538. read_file(SERVER_CERT2_FILE, cert);
  16539. Client cli("https://google.com");
  16540. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16541. cli.enable_system_ca(true);
  16542. cli.enable_server_certificate_verification(true);
  16543. auto res = cli.Get("/");
  16544. // Any status: Google may redirect or rate-limit CI runners.
  16545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16546. }
  16547. // The system CA policy must carry over to the client created internally for
  16548. // following a cross-host HTTPS redirect
  16549. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16550. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16551. ASSERT_TRUE(svr.is_valid());
  16552. svr.Get("/index", [&](const Request &, Response &res) {
  16553. res.set_redirect("https://www.google.com/");
  16554. });
  16555. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16556. auto se = detail::scope_exit([&] {
  16557. svr.stop();
  16558. t.join();
  16559. ASSERT_FALSE(svr.is_running());
  16560. });
  16561. svr.wait_until_ready();
  16562. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16563. std::string cert;
  16564. read_file(SERVER_CERT2_FILE, cert);
  16565. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16566. cli.enable_system_ca(true);
  16567. cli.enable_server_certificate_verification(true);
  16568. cli.set_follow_location(true);
  16569. cli.set_connection_timeout(30);
  16570. // Receiving any response proves the redirect client completed the TLS
  16571. // handshake with a system-CA-signed host
  16572. auto res = cli.Get("/index");
  16573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16574. }
  16575. TEST(MultipartFormDataTest, LargeData) {
  16576. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16577. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16578. const ContentReader &content_reader) {
  16579. if (req.is_multipart_form_data()) {
  16580. std::vector<FormData> items;
  16581. content_reader(
  16582. [&](const FormData &file) {
  16583. items.push_back(file);
  16584. return true;
  16585. },
  16586. [&](const char *data, size_t data_length) {
  16587. items.back().content.append(data, data_length);
  16588. return true;
  16589. });
  16590. EXPECT_TRUE(std::string(items[0].name) == "document");
  16591. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16592. EXPECT_TRUE(items[0].filename == "2MB_data");
  16593. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16594. EXPECT_TRUE(items[1].name == "hello");
  16595. EXPECT_TRUE(items[1].content == "world");
  16596. EXPECT_TRUE(items[1].filename == "");
  16597. EXPECT_TRUE(items[1].content_type == "");
  16598. } else {
  16599. std::string body;
  16600. content_reader([&](const char *data, size_t data_length) {
  16601. body.append(data, data_length);
  16602. return true;
  16603. });
  16604. }
  16605. });
  16606. auto port = svr.bind_to_any_port(HOST);
  16607. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16608. auto se = detail::scope_exit([&] {
  16609. svr.stop();
  16610. t.join();
  16611. ASSERT_FALSE(svr.is_running());
  16612. });
  16613. svr.wait_until_ready();
  16614. {
  16615. std::string data(1024 * 1024 * 2, '.');
  16616. std::stringstream buffer;
  16617. buffer << data;
  16618. SSLClient cli(HOST, port);
  16619. cli.enable_server_certificate_verification(false);
  16620. UploadFormDataItems items{
  16621. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16622. {"hello", "world", "", ""},
  16623. };
  16624. auto res = cli.Post("/post", items);
  16625. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16626. ASSERT_EQ(StatusCode::OK_200, res->status);
  16627. }
  16628. }
  16629. TEST(MultipartFormDataTest, DataProviderItems) {
  16630. std::random_device seed_gen;
  16631. std::mt19937 random(seed_gen());
  16632. std::string rand1;
  16633. rand1.resize(1000);
  16634. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16635. std::string rand2;
  16636. rand2.resize(3000);
  16637. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16638. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16639. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16640. const ContentReader &content_reader) {
  16641. ASSERT_FALSE(req.is_multipart_form_data());
  16642. std::string body;
  16643. content_reader([&](const char *data, size_t data_length) {
  16644. body.append(data, data_length);
  16645. return true;
  16646. });
  16647. EXPECT_EQ(body, "");
  16648. });
  16649. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16650. const ContentReader &content_reader) {
  16651. ASSERT_TRUE(req.is_multipart_form_data());
  16652. std::vector<FormData> items;
  16653. content_reader(
  16654. [&](const FormData &file) {
  16655. items.push_back(file);
  16656. return true;
  16657. },
  16658. [&](const char *data, size_t data_length) {
  16659. items.back().content.append(data, data_length);
  16660. return true;
  16661. });
  16662. ASSERT_TRUE(items.size() == 2);
  16663. EXPECT_EQ(std::string(items[0].name), "name1");
  16664. EXPECT_EQ(items[0].content, "Testing123");
  16665. EXPECT_EQ(items[0].filename, "filename1");
  16666. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16667. EXPECT_EQ(items[1].name, "name2");
  16668. EXPECT_EQ(items[1].content, "Testing456");
  16669. EXPECT_EQ(items[1].filename, "");
  16670. EXPECT_EQ(items[1].content_type, "");
  16671. });
  16672. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16673. const ContentReader &content_reader) {
  16674. ASSERT_TRUE(req.is_multipart_form_data());
  16675. std::vector<FormData> items;
  16676. content_reader(
  16677. [&](const FormData &file) {
  16678. items.push_back(file);
  16679. return true;
  16680. },
  16681. [&](const char *data, size_t data_length) {
  16682. items.back().content.append(data, data_length);
  16683. return true;
  16684. });
  16685. ASSERT_TRUE(items.size() == 2);
  16686. EXPECT_EQ(items[0].name, "name3");
  16687. EXPECT_EQ(items[0].content, rand1);
  16688. EXPECT_EQ(items[0].filename, "filename3");
  16689. EXPECT_EQ(items[0].content_type, "");
  16690. EXPECT_EQ(items[1].name, "name4");
  16691. EXPECT_EQ(items[1].content, rand2);
  16692. EXPECT_EQ(items[1].filename, "filename4");
  16693. EXPECT_EQ(items[1].content_type, "");
  16694. });
  16695. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16696. const ContentReader &content_reader) {
  16697. ASSERT_TRUE(req.is_multipart_form_data());
  16698. std::vector<FormData> items;
  16699. content_reader(
  16700. [&](const FormData &file) {
  16701. items.push_back(file);
  16702. return true;
  16703. },
  16704. [&](const char *data, size_t data_length) {
  16705. items.back().content.append(data, data_length);
  16706. return true;
  16707. });
  16708. ASSERT_TRUE(items.size() == 4);
  16709. EXPECT_EQ(std::string(items[0].name), "name1");
  16710. EXPECT_EQ(items[0].content, "Testing123");
  16711. EXPECT_EQ(items[0].filename, "filename1");
  16712. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16713. EXPECT_EQ(items[1].name, "name2");
  16714. EXPECT_EQ(items[1].content, "Testing456");
  16715. EXPECT_EQ(items[1].filename, "");
  16716. EXPECT_EQ(items[1].content_type, "");
  16717. EXPECT_EQ(items[2].name, "name3");
  16718. EXPECT_EQ(items[2].content, rand1);
  16719. EXPECT_EQ(items[2].filename, "filename3");
  16720. EXPECT_EQ(items[2].content_type, "");
  16721. EXPECT_EQ(items[3].name, "name4");
  16722. EXPECT_EQ(items[3].content, rand2);
  16723. EXPECT_EQ(items[3].filename, "filename4");
  16724. EXPECT_EQ(items[3].content_type, "");
  16725. });
  16726. auto port = svr.bind_to_any_port("localhost");
  16727. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16728. auto se = detail::scope_exit([&] {
  16729. svr.stop();
  16730. t.join();
  16731. ASSERT_FALSE(svr.is_running());
  16732. });
  16733. svr.wait_until_ready();
  16734. {
  16735. SSLClient cli("localhost", port);
  16736. cli.enable_server_certificate_verification(false);
  16737. UploadFormDataItems items{
  16738. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16739. {"name2", "Testing456", "", ""}, // not a file
  16740. };
  16741. {
  16742. auto res = cli.Post("/post-none", {}, {}, {});
  16743. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16744. ASSERT_EQ(StatusCode::OK_200, res->status);
  16745. }
  16746. FormDataProviderItems providers;
  16747. {
  16748. auto res =
  16749. cli.Post("/post-items", {}, items, providers); // empty providers
  16750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16751. ASSERT_EQ(StatusCode::OK_200, res->status);
  16752. }
  16753. providers.push_back({"name3",
  16754. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16755. // test the offset is given correctly at each step
  16756. if (!offset)
  16757. sink.os.write(rand1.data(), 30);
  16758. else if (offset == 30)
  16759. sink.os.write(rand1.data() + 30, 300);
  16760. else if (offset == 330)
  16761. sink.os.write(rand1.data() + 330, 670);
  16762. else if (offset == rand1.size())
  16763. sink.done();
  16764. return true;
  16765. },
  16766. "filename3",
  16767. {}});
  16768. providers.push_back({"name4",
  16769. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16770. // test the offset is given correctly at each step
  16771. if (!offset)
  16772. sink.os.write(rand2.data(), 2000);
  16773. else if (offset == 2000)
  16774. sink.os.write(rand2.data() + 2000, 1);
  16775. else if (offset == 2001)
  16776. sink.os.write(rand2.data() + 2001, 999);
  16777. else if (offset == rand2.size())
  16778. sink.done();
  16779. return true;
  16780. },
  16781. "filename4",
  16782. {}});
  16783. {
  16784. auto res = cli.Post("/post-providers", {}, {}, providers);
  16785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16786. ASSERT_EQ(StatusCode::OK_200, res->status);
  16787. }
  16788. {
  16789. auto res = cli.Post("/post-both", {}, items, providers);
  16790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16791. ASSERT_EQ(StatusCode::OK_200, res->status);
  16792. }
  16793. }
  16794. }
  16795. TEST(MultipartFormDataTest, BadHeader) {
  16796. Server svr;
  16797. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16798. res.set_content("ok", "text/plain");
  16799. });
  16800. thread t = thread([&] { svr.listen(HOST, PORT); });
  16801. auto se = detail::scope_exit([&] {
  16802. svr.stop();
  16803. t.join();
  16804. ASSERT_FALSE(svr.is_running());
  16805. });
  16806. svr.wait_until_ready();
  16807. const std::string body =
  16808. "This is the preamble. It is to be ignored, though it\r\n"
  16809. "is a handy place for composition agents to include an\r\n"
  16810. "explanatory note to non-MIME conformant readers.\r\n"
  16811. "\r\n"
  16812. "\r\n"
  16813. "--simple boundary\r\n"
  16814. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16815. ": BAD...\r\n"
  16816. "\r\n"
  16817. "value1\r\n"
  16818. "--simple boundary\r\n"
  16819. "Content-Disposition: form-data; name=\"field2\"; "
  16820. "filename=\"example.txt\"\r\n"
  16821. "\r\n"
  16822. "value2\r\n"
  16823. "--simple boundary--\r\n"
  16824. "This is the epilogue. It is also to be ignored.\r\n";
  16825. std::string content_type =
  16826. R"(multipart/form-data; boundary="simple boundary")";
  16827. Client cli(HOST, PORT);
  16828. auto res = cli.Post("/post", body, content_type.c_str());
  16829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16830. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16831. }
  16832. TEST(MultipartFormDataTest, WithPreamble) {
  16833. Server svr;
  16834. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16835. res.set_content("ok", "text/plain");
  16836. });
  16837. thread t = thread([&] { svr.listen(HOST, PORT); });
  16838. auto se = detail::scope_exit([&] {
  16839. svr.stop();
  16840. t.join();
  16841. ASSERT_FALSE(svr.is_running());
  16842. });
  16843. svr.wait_until_ready();
  16844. const std::string body =
  16845. "This is the preamble. It is to be ignored, though it\r\n"
  16846. "is a handy place for composition agents to include an\r\n"
  16847. "explanatory note to non-MIME conformant readers.\r\n"
  16848. "\r\n"
  16849. "\r\n"
  16850. "--simple boundary\r\n"
  16851. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16852. "\r\n"
  16853. "value1\r\n"
  16854. "--simple boundary\r\n"
  16855. "Content-Disposition: form-data; name=\"field2\"; "
  16856. "filename=\"example.txt\"\r\n"
  16857. "\r\n"
  16858. "value2\r\n"
  16859. "--simple boundary--\r\n"
  16860. "This is the epilogue. It is also to be ignored.\r\n";
  16861. std::string content_type =
  16862. R"(multipart/form-data; boundary="simple boundary")";
  16863. Client cli(HOST, PORT);
  16864. auto res = cli.Post("/post", body, content_type.c_str());
  16865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16866. EXPECT_EQ(StatusCode::OK_200, res->status);
  16867. }
  16868. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16869. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16870. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16871. const ContentReader &content_reader) {
  16872. if (req.is_multipart_form_data()) {
  16873. std::vector<FormData> items;
  16874. content_reader(
  16875. [&](const FormData &file) {
  16876. items.push_back(file);
  16877. return true;
  16878. },
  16879. [&](const char *data, size_t data_length) {
  16880. items.back().content.append(data, data_length);
  16881. return true;
  16882. });
  16883. EXPECT_TRUE(std::string(items[0].name) == "document");
  16884. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16885. EXPECT_TRUE(items[0].filename == "2MB_data");
  16886. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16887. EXPECT_TRUE(items[1].name == "hello");
  16888. EXPECT_TRUE(items[1].content == "world");
  16889. EXPECT_TRUE(items[1].filename == "");
  16890. EXPECT_TRUE(items[1].content_type == "");
  16891. } else {
  16892. std::string body;
  16893. content_reader([&](const char *data, size_t data_length) {
  16894. body.append(data, data_length);
  16895. return true;
  16896. });
  16897. }
  16898. });
  16899. auto port = svr.bind_to_any_port("localhost");
  16900. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16901. auto se = detail::scope_exit([&] {
  16902. svr.stop();
  16903. t.join();
  16904. ASSERT_FALSE(svr.is_running());
  16905. });
  16906. svr.wait_until_ready();
  16907. {
  16908. std::string data(1024 * 1024 * 2, '.');
  16909. std::stringstream buffer;
  16910. buffer << data;
  16911. SSLClient cli("localhost", port);
  16912. cli.enable_server_certificate_verification(false);
  16913. UploadFormDataItems items{
  16914. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16915. {"hello", "world", "", ""},
  16916. };
  16917. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16919. ASSERT_EQ(StatusCode::OK_200, res->status);
  16920. }
  16921. }
  16922. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16923. std::string data(1024 * 1024 * 2, '&');
  16924. std::stringstream buffer;
  16925. buffer << data;
  16926. Client cli("https://localhost:8080");
  16927. UploadFormDataItems items{
  16928. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16929. {"hello", "world", "", ""},
  16930. };
  16931. for (const char &c : " \t\r\n") {
  16932. auto res =
  16933. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16934. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16935. ASSERT_FALSE(res);
  16936. }
  16937. }
  16938. TEST(MultipartFormDataTest, PutFormData) {
  16939. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16940. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16941. const ContentReader &content_reader) {
  16942. if (req.is_multipart_form_data()) {
  16943. std::vector<FormData> items;
  16944. content_reader(
  16945. [&](const FormData &file) {
  16946. items.push_back(file);
  16947. return true;
  16948. },
  16949. [&](const char *data, size_t data_length) {
  16950. items.back().content.append(data, data_length);
  16951. return true;
  16952. });
  16953. EXPECT_TRUE(std::string(items[0].name) == "document");
  16954. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16955. EXPECT_TRUE(items[0].filename == "2MB_data");
  16956. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16957. EXPECT_TRUE(items[1].name == "hello");
  16958. EXPECT_TRUE(items[1].content == "world");
  16959. EXPECT_TRUE(items[1].filename == "");
  16960. EXPECT_TRUE(items[1].content_type == "");
  16961. } else {
  16962. std::string body;
  16963. content_reader([&](const char *data, size_t data_length) {
  16964. body.append(data, data_length);
  16965. return true;
  16966. });
  16967. }
  16968. });
  16969. auto port = svr.bind_to_any_port("localhost");
  16970. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16971. auto se = detail::scope_exit([&] {
  16972. svr.stop();
  16973. t.join();
  16974. ASSERT_FALSE(svr.is_running());
  16975. });
  16976. svr.wait_until_ready();
  16977. {
  16978. std::string data(1024 * 1024 * 2, '&');
  16979. std::stringstream buffer;
  16980. buffer << data;
  16981. SSLClient cli("localhost", port);
  16982. cli.enable_server_certificate_verification(false);
  16983. UploadFormDataItems items{
  16984. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16985. {"hello", "world", "", ""},
  16986. };
  16987. auto res = cli.Put("/put", items);
  16988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16989. ASSERT_EQ(StatusCode::OK_200, res->status);
  16990. }
  16991. }
  16992. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  16993. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16994. svr.Put("/put_customboundary",
  16995. [&](const Request &req, const Response & /*res*/,
  16996. const ContentReader &content_reader) {
  16997. if (req.is_multipart_form_data()) {
  16998. std::vector<FormData> items;
  16999. content_reader(
  17000. [&](const FormData &file) {
  17001. items.push_back(file);
  17002. return true;
  17003. },
  17004. [&](const char *data, size_t data_length) {
  17005. items.back().content.append(data, data_length);
  17006. return true;
  17007. });
  17008. EXPECT_TRUE(std::string(items[0].name) == "document");
  17009. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17010. EXPECT_TRUE(items[0].filename == "2MB_data");
  17011. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17012. EXPECT_TRUE(items[1].name == "hello");
  17013. EXPECT_TRUE(items[1].content == "world");
  17014. EXPECT_TRUE(items[1].filename == "");
  17015. EXPECT_TRUE(items[1].content_type == "");
  17016. } else {
  17017. std::string body;
  17018. content_reader([&](const char *data, size_t data_length) {
  17019. body.append(data, data_length);
  17020. return true;
  17021. });
  17022. }
  17023. });
  17024. auto port = svr.bind_to_any_port("localhost");
  17025. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17026. auto se = detail::scope_exit([&] {
  17027. svr.stop();
  17028. t.join();
  17029. ASSERT_FALSE(svr.is_running());
  17030. });
  17031. svr.wait_until_ready();
  17032. {
  17033. std::string data(1024 * 1024 * 2, '&');
  17034. std::stringstream buffer;
  17035. buffer << data;
  17036. SSLClient cli("localhost", port);
  17037. cli.enable_server_certificate_verification(false);
  17038. UploadFormDataItems items{
  17039. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17040. {"hello", "world", "", ""},
  17041. };
  17042. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17044. ASSERT_EQ(StatusCode::OK_200, res->status);
  17045. }
  17046. }
  17047. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17048. std::string data(1024 * 1024 * 2, '&');
  17049. std::stringstream buffer;
  17050. buffer << data;
  17051. Client cli("https://localhost:8080");
  17052. cli.enable_server_certificate_verification(false);
  17053. UploadFormDataItems items{
  17054. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17055. {"hello", "world", "", ""},
  17056. };
  17057. for (const char &c : " \t\r\n") {
  17058. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17059. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17060. ASSERT_FALSE(res);
  17061. }
  17062. }
  17063. TEST(MultipartFormDataTest, AlternateFilename) {
  17064. auto handled = false;
  17065. Server svr;
  17066. svr.Post("/test", [&](const Request &req, Response &res) {
  17067. ASSERT_EQ(2u, req.form.files.size());
  17068. ASSERT_EQ(1u, req.form.fields.size());
  17069. // Test files
  17070. const auto &file1 = req.form.get_file("file1");
  17071. ASSERT_EQ("file1", file1.name);
  17072. ASSERT_EQ("A.txt", file1.filename);
  17073. ASSERT_EQ("text/plain", file1.content_type);
  17074. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17075. const auto &file2 = req.form.get_file("file2");
  17076. ASSERT_EQ("file2", file2.name);
  17077. ASSERT_EQ("a.html", file2.filename);
  17078. ASSERT_EQ("text/html", file2.content_type);
  17079. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17080. file2.content);
  17081. // Test text field
  17082. const auto &text = req.form.get_field("text");
  17083. ASSERT_EQ("text default", text);
  17084. res.set_content("ok", "text/plain");
  17085. handled = true;
  17086. });
  17087. thread t = thread([&] { svr.listen(HOST, PORT); });
  17088. auto se = detail::scope_exit([&] {
  17089. svr.stop();
  17090. t.join();
  17091. ASSERT_FALSE(svr.is_running());
  17092. ASSERT_TRUE(handled);
  17093. });
  17094. svr.wait_until_ready();
  17095. auto req = "POST /test HTTP/1.1\r\n"
  17096. "Host: localhost\r\n"
  17097. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17098. "Content-Length: 399\r\n"
  17099. "\r\n"
  17100. "----------\r\n"
  17101. "Content-Disposition: form-data; name=\"text\"\r\n"
  17102. "\r\n"
  17103. "text default\r\n"
  17104. "----------\r\n"
  17105. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17106. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17107. "Content-Type: text/plain\r\n"
  17108. "\r\n"
  17109. "Content of a.txt.\r\n"
  17110. "\r\n"
  17111. "----------\r\n"
  17112. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17113. "\"a.html\"\r\n"
  17114. "Content-Type: text/html\r\n"
  17115. "\r\n"
  17116. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17117. "\r\n"
  17118. "------------\r\n";
  17119. ASSERT_TRUE(send_request(1, req));
  17120. }
  17121. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17122. auto handled = false;
  17123. Server svr;
  17124. svr.Post("/test", [&](const Request &req, Response &res) {
  17125. // Case-insensitive "utf-8''" prefix with a long value
  17126. const auto &file = req.form.get_file("file1");
  17127. ASSERT_EQ("file1", file.name);
  17128. // 8000 chars exercises both the Content-Disposition parser and the
  17129. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17130. // Prior to the fix, std::regex_match on this header would cause O(N)
  17131. // stack recursion in libstdc++, leading to SIGSEGV.
  17132. std::string expected_filename(8000, 'A');
  17133. ASSERT_EQ(expected_filename, file.filename);
  17134. res.set_content("ok", "text/plain");
  17135. handled = true;
  17136. });
  17137. thread t = thread([&] { svr.listen(HOST, PORT); });
  17138. auto se = detail::scope_exit([&] {
  17139. svr.stop();
  17140. t.join();
  17141. ASSERT_FALSE(svr.is_running());
  17142. ASSERT_TRUE(handled);
  17143. });
  17144. svr.wait_until_ready();
  17145. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17146. // Regression test for GHSA-qq6v-r583-3h69
  17147. std::string long_filename(8000, 'A');
  17148. std::string body = "----------\r\n"
  17149. "Content-Disposition: form-data; name=\"file1\"; "
  17150. "filename*=\"Utf-8''" +
  17151. long_filename +
  17152. "\"\r\n"
  17153. "\r\n"
  17154. "hello\r\n"
  17155. "------------\r\n";
  17156. auto req = "POST /test HTTP/1.1\r\n"
  17157. "Host: localhost\r\n"
  17158. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17159. "Content-Length: " +
  17160. std::to_string(body.size()) + "\r\n\r\n" + body;
  17161. ASSERT_TRUE(send_request(1, req));
  17162. }
  17163. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17164. auto handled = false;
  17165. Server svr;
  17166. svr.Post("/test", [&](const Request &req, Response &) {
  17167. ASSERT_EQ(2u, req.form.fields.size());
  17168. const auto &text1 = req.form.get_field("text1");
  17169. ASSERT_EQ("text1", text1);
  17170. const auto &text2 = req.form.get_field("text2");
  17171. ASSERT_EQ("text2", text2);
  17172. handled = true;
  17173. });
  17174. thread t = thread([&] { svr.listen(HOST, PORT); });
  17175. auto se = detail::scope_exit([&] {
  17176. svr.stop();
  17177. t.join();
  17178. ASSERT_FALSE(svr.is_running());
  17179. ASSERT_TRUE(handled);
  17180. });
  17181. svr.wait_until_ready();
  17182. auto req = "POST /test HTTP/1.1\r\n"
  17183. "Host: localhost\r\n"
  17184. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17185. "Content-Length: 146\r\n"
  17186. "\r\n----------\r\n"
  17187. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17188. "\r\n"
  17189. "text1"
  17190. "\r\n----------\r\n"
  17191. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17192. "\r\n"
  17193. "text2"
  17194. "\r\n------------";
  17195. std::string response;
  17196. ASSERT_TRUE(send_request(1, req, &response));
  17197. ASSERT_EQ("200", response.substr(9, 3));
  17198. }
  17199. TEST(MultipartFormDataTest, ContentLength) {
  17200. auto handled = false;
  17201. Server svr;
  17202. svr.Post("/test", [&](const Request &req, Response &) {
  17203. ASSERT_EQ(2u, req.form.fields.size());
  17204. const auto &text1 = req.form.get_field("text1");
  17205. ASSERT_EQ("text1", text1);
  17206. const auto &text2 = req.form.get_field("text2");
  17207. ASSERT_EQ("text2", text2);
  17208. handled = true;
  17209. });
  17210. thread t = thread([&] { svr.listen(HOST, PORT); });
  17211. auto se = detail::scope_exit([&] {
  17212. svr.stop();
  17213. t.join();
  17214. ASSERT_FALSE(svr.is_running());
  17215. ASSERT_TRUE(handled);
  17216. });
  17217. svr.wait_until_ready();
  17218. auto req = "POST /test HTTP/1.1\r\n"
  17219. "Host: localhost\r\n"
  17220. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17221. "Content-Length: 167\r\n"
  17222. "\r\n----------\r\n"
  17223. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17224. "Content-Length: 5\r\n"
  17225. "\r\n"
  17226. "text1"
  17227. "\r\n----------\r\n"
  17228. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17229. "\r\n"
  17230. "text2"
  17231. "\r\n------------\r\n";
  17232. std::string response;
  17233. ASSERT_TRUE(send_request(1, req, &response));
  17234. ASSERT_EQ("200", response.substr(9, 3));
  17235. }
  17236. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17237. auto handled = false;
  17238. Server svr;
  17239. svr.Post("/test", [&](const Request &req, Response &) {
  17240. ASSERT_EQ(2u, req.form.fields.size());
  17241. const auto &text1 = req.form.get_field("text1");
  17242. ASSERT_EQ("text1", text1);
  17243. // TODO: Add header access for text fields if needed
  17244. const auto &text2 = req.form.get_field("text2");
  17245. ASSERT_EQ("text2", text2);
  17246. // TODO: Header access for text fields needs to be implemented
  17247. // auto &headers = it->second.headers;
  17248. // ASSERT_EQ(3U, headers.size());
  17249. // auto custom_header = headers.find("x-whatever");
  17250. // ASSERT_TRUE(custom_header != headers.end());
  17251. // ASSERT_NE("customvalue", custom_header->second);
  17252. // ASSERT_EQ("CustomValue", custom_header->second);
  17253. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17254. handled = true;
  17255. });
  17256. thread t = thread([&] { svr.listen(HOST, PORT); });
  17257. auto se = detail::scope_exit([&] {
  17258. svr.stop();
  17259. t.join();
  17260. ASSERT_FALSE(svr.is_running());
  17261. ASSERT_TRUE(handled);
  17262. });
  17263. svr.wait_until_ready();
  17264. auto req = "POST /test HTTP/1.1\r\n"
  17265. "Host: localhost\r\n"
  17266. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17267. "Content-Length: 232\r\n"
  17268. "\r\n----------\r\n"
  17269. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17270. "Content-Length: 5\r\n"
  17271. "X-Test: 1\r\n"
  17272. "\r\n"
  17273. "text1"
  17274. "\r\n----------\r\n"
  17275. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17276. "Content-Type: text/plain\r\n"
  17277. "X-Whatever: CustomValue\r\n"
  17278. "\r\n"
  17279. "text2"
  17280. "\r\n------------\r\n"
  17281. "That should be disregarded. Not even read";
  17282. std::string response;
  17283. ASSERT_TRUE(send_request(1, req, &response));
  17284. ASSERT_EQ("200", response.substr(9, 3));
  17285. }
  17286. TEST(MultipartFormDataTest, LargeHeader) {
  17287. auto handled = false;
  17288. Server svr;
  17289. svr.Post("/test", [&](const Request &req, Response &) {
  17290. ASSERT_EQ(1u, req.form.fields.size());
  17291. const auto &text = req.form.get_field("name1");
  17292. ASSERT_EQ("text1", text);
  17293. handled = true;
  17294. });
  17295. thread t = thread([&] { svr.listen(HOST, PORT); });
  17296. auto se = detail::scope_exit([&] {
  17297. svr.stop();
  17298. t.join();
  17299. ASSERT_FALSE(svr.is_running());
  17300. ASSERT_TRUE(handled);
  17301. });
  17302. svr.wait_until_ready();
  17303. auto boundary = std::string("cpp-httplib-multipart-data");
  17304. std::string content = "--" + boundary +
  17305. "\r\n"
  17306. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17307. "\r\n"
  17308. "text1\r\n"
  17309. "--" +
  17310. boundary + "--\r\n";
  17311. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17312. "Host: localhost\r\n"
  17313. "Content-Type: multipart/form-data;boundary=" +
  17314. boundary +
  17315. "\r\n"
  17316. "Content-Length: " +
  17317. std::to_string(content.size()) +
  17318. "\r\n"
  17319. "Dummy-Header: ";
  17320. std::string header_suffix = "\r\n"
  17321. "\r\n";
  17322. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17323. size_t header_dummy_size =
  17324. read_buff_size -
  17325. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17326. auto header_dummy = std::string(header_dummy_size, '@');
  17327. auto req = header_prefix + header_dummy + header_suffix + content;
  17328. std::string response;
  17329. ASSERT_TRUE(send_request(1, req, &response));
  17330. ASSERT_EQ("200", response.substr(9, 3));
  17331. }
  17332. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17333. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17334. // (not chunked Transfer-Encoding) after the streaming refactor.
  17335. auto handled = false;
  17336. Server svr;
  17337. svr.Post("/upload", [&](const Request &req, Response &res) {
  17338. auto cl_it = req.headers.find("Content-Length");
  17339. EXPECT_TRUE(cl_it != req.headers.end());
  17340. auto te_it = req.headers.find("Transfer-Encoding");
  17341. EXPECT_TRUE(te_it == req.headers.end());
  17342. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17343. res.set_content("ok", "text/plain");
  17344. handled = true;
  17345. });
  17346. auto port = svr.bind_to_any_port(HOST);
  17347. auto t = thread([&] { svr.listen_after_bind(); });
  17348. auto se = detail::scope_exit([&] {
  17349. svr.stop();
  17350. t.join();
  17351. ASSERT_FALSE(svr.is_running());
  17352. ASSERT_TRUE(handled);
  17353. });
  17354. svr.wait_until_ready();
  17355. UploadFormDataItems items = {
  17356. {"field1", "hello", "", "text/plain"},
  17357. {"file1", "world", "test.txt", "application/octet-stream"},
  17358. };
  17359. Client cli(HOST, port);
  17360. auto res = cli.Post("/upload", {}, items);
  17361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17362. EXPECT_EQ(StatusCode::OK_200, res->status);
  17363. }
  17364. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17365. // Verify that make_multipart_content_provider coalesces many small segments
  17366. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17367. constexpr size_t kItemCount = 1000;
  17368. UploadFormDataItems items;
  17369. items.reserve(kItemCount);
  17370. for (size_t i = 0; i < kItemCount; i++) {
  17371. items.push_back(
  17372. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17373. }
  17374. const std::string boundary = "----test-boundary";
  17375. auto content_length = detail::get_multipart_content_length(items, boundary);
  17376. auto provider = detail::make_multipart_content_provider(items, boundary);
  17377. // Drive the provider the same way write_content_with_progress does
  17378. size_t write_count = 0;
  17379. size_t total_bytes = 0;
  17380. DataSink sink;
  17381. size_t offset = 0;
  17382. sink.write = [&](const char *d, size_t l) -> bool {
  17383. (void)d;
  17384. write_count++;
  17385. total_bytes += l;
  17386. offset += l;
  17387. return true;
  17388. };
  17389. sink.is_writable = []() -> bool { return true; };
  17390. while (offset < content_length) {
  17391. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17392. }
  17393. EXPECT_EQ(content_length, total_bytes);
  17394. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17395. // With buffering into 64KB blocks, write_count should be much smaller.
  17396. auto segment_count = 3 * kItemCount + 1;
  17397. EXPECT_LT(write_count, segment_count / 10);
  17398. }
  17399. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17400. // Integration test: send many UploadFormDataItems and verify the server
  17401. // receives all of them correctly (#2410).
  17402. constexpr size_t kItemCount = 500;
  17403. auto handled = false;
  17404. Server svr;
  17405. svr.Post("/upload", [&](const Request &req, Response &res) {
  17406. EXPECT_EQ(kItemCount, req.form.fields.size());
  17407. for (size_t i = 0; i < kItemCount; i++) {
  17408. auto key = "field" + std::to_string(i);
  17409. auto val = "value" + std::to_string(i);
  17410. auto it = req.form.fields.find(key);
  17411. if (it != req.form.fields.end()) {
  17412. EXPECT_EQ(val, it->second.content);
  17413. } else {
  17414. ADD_FAILURE() << "Missing field: " << key;
  17415. }
  17416. }
  17417. res.set_content("ok", "text/plain");
  17418. handled = true;
  17419. });
  17420. auto port = svr.bind_to_any_port(HOST);
  17421. auto t = thread([&] { svr.listen_after_bind(); });
  17422. auto se = detail::scope_exit([&] {
  17423. svr.stop();
  17424. t.join();
  17425. ASSERT_FALSE(svr.is_running());
  17426. ASSERT_TRUE(handled);
  17427. });
  17428. svr.wait_until_ready();
  17429. UploadFormDataItems items;
  17430. items.reserve(kItemCount);
  17431. for (size_t i = 0; i < kItemCount; i++) {
  17432. items.push_back(
  17433. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17434. }
  17435. Client cli(HOST, port);
  17436. auto res = cli.Post("/upload", items);
  17437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17438. EXPECT_EQ(StatusCode::OK_200, res->status);
  17439. }
  17440. TEST(MultipartFormDataTest, MakeFileProvider) {
  17441. // Verify make_file_provider sends a file's contents correctly.
  17442. const std::string file_content(4096, 'Z');
  17443. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17444. {
  17445. std::ofstream ofs(tmp_path, std::ios::binary);
  17446. ofs.write(file_content.data(),
  17447. static_cast<std::streamsize>(file_content.size()));
  17448. }
  17449. auto handled = false;
  17450. Server svr;
  17451. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17452. const ContentReader &content_reader) {
  17453. ASSERT_TRUE(req.is_multipart_form_data());
  17454. std::vector<FormData> items;
  17455. content_reader(
  17456. [&](const FormData &file) {
  17457. items.push_back(file);
  17458. return true;
  17459. },
  17460. [&](const char *data, size_t data_length) {
  17461. items.back().content.append(data, data_length);
  17462. return true;
  17463. });
  17464. ASSERT_EQ(1u, items.size());
  17465. EXPECT_EQ("myfile", items[0].name);
  17466. EXPECT_EQ("data.bin", items[0].filename);
  17467. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17468. EXPECT_EQ(file_content, items[0].content);
  17469. handled = true;
  17470. });
  17471. auto port = svr.bind_to_any_port(HOST);
  17472. auto t = thread([&] { svr.listen_after_bind(); });
  17473. auto se = detail::scope_exit([&] {
  17474. svr.stop();
  17475. t.join();
  17476. ASSERT_FALSE(svr.is_running());
  17477. ASSERT_TRUE(handled);
  17478. std::remove(tmp_path.c_str());
  17479. });
  17480. svr.wait_until_ready();
  17481. FormDataProviderItems providers;
  17482. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17483. "application/octet-stream"));
  17484. Client cli(HOST, port);
  17485. auto res = cli.Post("/upload", {}, {}, providers);
  17486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17487. EXPECT_EQ(StatusCode::OK_200, res->status);
  17488. }
  17489. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17490. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17491. // (100) headers is rejected with a 400 Bad Request response.
  17492. Server svr;
  17493. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17494. res.set_content("ok", "text/plain");
  17495. });
  17496. thread t = thread([&] { svr.listen(HOST, PORT); });
  17497. auto se = detail::scope_exit([&] {
  17498. svr.stop();
  17499. t.join();
  17500. ASSERT_FALSE(svr.is_running());
  17501. });
  17502. svr.wait_until_ready();
  17503. // Build a multipart part with 101 custom headers (exceeding
  17504. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17505. std::stringstream body;
  17506. body << "--simpleboundary\r\n"
  17507. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17508. for (int i = 0; i < 101; i++) {
  17509. body << "X-Custom-Header-" << i << ": value\r\n";
  17510. }
  17511. body << "\r\n"
  17512. << "value1\r\n"
  17513. << "--simpleboundary--\r\n";
  17514. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17515. Client cli(HOST, PORT);
  17516. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17518. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17519. }
  17520. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17521. // A body that never contains the declared boundary must not be accumulated
  17522. // while the parser waits for it. Buffering it would also make every read
  17523. // rescan everything seen so far, which is quadratic in the body size.
  17524. Server svr;
  17525. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17526. res.set_content("ok", "text/plain");
  17527. });
  17528. auto port = svr.bind_to_any_port(HOST);
  17529. thread t = thread([&] { svr.listen_after_bind(); });
  17530. auto se = detail::scope_exit([&] {
  17531. svr.stop();
  17532. t.join();
  17533. ASSERT_FALSE(svr.is_running());
  17534. });
  17535. svr.wait_until_ready();
  17536. Client cli(HOST, port);
  17537. cli.set_read_timeout(60, 0);
  17538. cli.set_write_timeout(60, 0);
  17539. // '-' is the worst case: it matches the first character of the boundary, so
  17540. // every position has to be checked against it.
  17541. auto post_dashes = [&](size_t size) {
  17542. const std::string body(size, '-');
  17543. auto start = std::chrono::steady_clock::now();
  17544. auto res =
  17545. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17546. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17547. std::chrono::steady_clock::now() - start)
  17548. .count();
  17549. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17550. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17551. return ms;
  17552. };
  17553. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17554. // Windows.
  17555. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17556. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17557. // Comparing the two sizes rather than checking an absolute duration keeps
  17558. // this meaningful across build types and CI load, both of which move the
  17559. // absolute numbers by more than an order of magnitude. Four times the bytes
  17560. // costs about four times the time when parsing is linear, and about sixteen
  17561. // times when the body is buffered and rescanned.
  17562. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17563. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17564. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17565. << "ms, which suggests the body is being buffered and rescanned";
  17566. }
  17567. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17568. // A boundary can only be followed by CRLF or by "--", so anything else is
  17569. // malformed no matter what comes next. The parser must say so right away
  17570. // instead of buffering the rest of the declared body.
  17571. Server svr;
  17572. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17573. res.set_content("ok", "text/plain");
  17574. });
  17575. auto port = svr.bind_to_any_port(HOST);
  17576. thread t = thread([&] { svr.listen_after_bind(); });
  17577. auto se = detail::scope_exit([&] {
  17578. svr.stop();
  17579. t.join();
  17580. ASSERT_FALSE(svr.is_running());
  17581. });
  17582. svr.wait_until_ready();
  17583. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17584. // buffers instead of failing would still be waiting for the remaining bytes.
  17585. const std::string body = "--zzzz\r\n"
  17586. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17587. "\r\n"
  17588. "text1"
  17589. "\r\n--zzzzXX";
  17590. const std::string req = "POST /post HTTP/1.1\r\n"
  17591. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17592. "Content-Length: 1048576\r\n"
  17593. "\r\n" +
  17594. body;
  17595. std::string response;
  17596. ASSERT_TRUE(send_request(3, req, &response, port));
  17597. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17598. EXPECT_EQ("400", response.substr(9, 3));
  17599. }
  17600. // Posts a multipart body split into two writes, so that the server sees the
  17601. // split at whatever offset the caller chose, and expects the single "text1"
  17602. // field to come through.
  17603. static void expect_split_multipart_ok(const std::string &body1,
  17604. const std::string &body2) {
  17605. auto handled = false;
  17606. Server svr;
  17607. svr.Post("/post", [&](const Request &req, Response &) {
  17608. EXPECT_EQ(1u, req.form.fields.size());
  17609. EXPECT_EQ("text1", req.form.get_field("text1"));
  17610. handled = true;
  17611. });
  17612. auto port = svr.bind_to_any_port(HOST);
  17613. thread t = thread([&] { svr.listen_after_bind(); });
  17614. auto se = detail::scope_exit([&] {
  17615. svr.stop();
  17616. t.join();
  17617. ASSERT_FALSE(svr.is_running());
  17618. ASSERT_TRUE(handled);
  17619. });
  17620. svr.wait_until_ready();
  17621. // "Connection: close" makes the server close once it has answered, so the
  17622. // response drain ends immediately instead of idling until the read timeout.
  17623. const std::string head =
  17624. "POST /post HTTP/1.1\r\n"
  17625. "Host: localhost\r\n"
  17626. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17627. "Connection: close\r\n"
  17628. "Content-Length: " +
  17629. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17630. std::string response;
  17631. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17632. ASSERT_GE(response.size(), 12u) << "no response";
  17633. EXPECT_EQ("200", response.substr(9, 3));
  17634. }
  17635. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17636. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17637. // ignored, including when it does not arrive in the same read as the
  17638. // close-delimiter itself.
  17639. expect_split_multipart_ok("--zzzz\r\n"
  17640. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17641. "\r\n"
  17642. "text1"
  17643. "\r\n--zzzz--",
  17644. "\r\nthis epilogue must be ignored\r\n");
  17645. }
  17646. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17647. // The initial boundary may be preceded by a preamble of any length and may
  17648. // straddle a read boundary. Discarding data while waiting for it must not
  17649. // throw away a partial boundary sitting at the end of the buffer.
  17650. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17651. "zz\r\n"
  17652. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17653. "\r\n"
  17654. "text1"
  17655. "\r\n--zzzz--\r\n");
  17656. }
  17657. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17658. // The received boundary was only checked for being non-empty, so it could be
  17659. // as long as a header is allowed to be. The parser scans the body for
  17660. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17661. // costs a nearly full comparison at nearly every position, making the
  17662. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17663. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17664. Server svr;
  17665. svr.Post("/post", [](const Request &req, Response &res) {
  17666. EXPECT_EQ(1u, req.form.fields.size());
  17667. EXPECT_EQ("text1", req.form.get_field("text1"));
  17668. res.set_content("ok", "text/plain");
  17669. });
  17670. auto port = svr.bind_to_any_port(HOST);
  17671. thread t = thread([&] { svr.listen_after_bind(); });
  17672. auto se = detail::scope_exit([&] {
  17673. svr.stop();
  17674. t.join();
  17675. ASSERT_FALSE(svr.is_running());
  17676. });
  17677. svr.wait_until_ready();
  17678. Client cli(HOST, port);
  17679. auto post_with_boundary_of_length = [&](size_t len) {
  17680. const std::string boundary(len, 'a');
  17681. const std::string body =
  17682. "--" + boundary +
  17683. "\r\n"
  17684. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17685. "\r\n"
  17686. "text1"
  17687. "\r\n--" +
  17688. boundary + "--\r\n";
  17689. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17690. };
  17691. auto res = post_with_boundary_of_length(70);
  17692. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17693. EXPECT_EQ(StatusCode::OK_200, res->status);
  17694. res = post_with_boundary_of_length(71);
  17695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17696. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17697. }
  17698. TEST(MakeFileBodyTest, Basic) {
  17699. const std::string file_content(4096, 'Z');
  17700. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17701. {
  17702. std::ofstream ofs(tmp_path, std::ios::binary);
  17703. ofs.write(file_content.data(),
  17704. static_cast<std::streamsize>(file_content.size()));
  17705. }
  17706. auto handled = false;
  17707. Server svr;
  17708. svr.Post("/upload", [&](const Request &req, Response &res) {
  17709. EXPECT_EQ(file_content, req.body);
  17710. handled = true;
  17711. res.status = StatusCode::OK_200;
  17712. });
  17713. auto port = svr.bind_to_any_port(HOST);
  17714. auto t = thread([&] { svr.listen_after_bind(); });
  17715. auto se = detail::scope_exit([&] {
  17716. svr.stop();
  17717. t.join();
  17718. ASSERT_FALSE(svr.is_running());
  17719. ASSERT_TRUE(handled);
  17720. std::remove(tmp_path.c_str());
  17721. });
  17722. svr.wait_until_ready();
  17723. auto fb = make_file_body(tmp_path);
  17724. ASSERT_GT(fb.first, 0u);
  17725. Client cli(HOST, port);
  17726. auto res =
  17727. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17729. EXPECT_EQ(StatusCode::OK_200, res->status);
  17730. }
  17731. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17732. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17733. {
  17734. std::ofstream ofs(path, std::ios::binary);
  17735. const std::string content(100, 'A');
  17736. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17737. }
  17738. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17739. auto body = make_file_body(path);
  17740. ASSERT_EQ(100u, body.first);
  17741. ASSERT_TRUE(static_cast<bool>(body.second));
  17742. // Rewritten shorter after its length was measured - and, on a server, after
  17743. // that length has already gone out as Content-Length.
  17744. {
  17745. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17746. const std::string content(10, 'A');
  17747. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17748. }
  17749. std::string written;
  17750. DataSink sink;
  17751. sink.write = [&](const char *d, size_t l) {
  17752. written.append(d, l);
  17753. return true;
  17754. };
  17755. // The provider has to report failure. write_content_with_progress() advances
  17756. // its offset only by what was written, so a provider that returns true
  17757. // without completing the length it promised is called again straight away,
  17758. // and again.
  17759. EXPECT_FALSE(body.second(0, body.first, sink));
  17760. EXPECT_EQ(std::string(10, 'A'), written);
  17761. }
  17762. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17763. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17764. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17765. {
  17766. std::ofstream ofs(path, std::ios::binary);
  17767. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17768. }
  17769. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17770. auto body = make_file_body(path);
  17771. ASSERT_EQ(content.size(), body.first);
  17772. ASSERT_TRUE(static_cast<bool>(body.second));
  17773. std::string written;
  17774. DataSink sink;
  17775. sink.write = [&](const char *d, size_t l) {
  17776. written.append(d, l);
  17777. return true;
  17778. };
  17779. EXPECT_TRUE(body.second(0, body.first, sink));
  17780. EXPECT_EQ(content, written);
  17781. }
  17782. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17783. static constexpr unsigned int number_of_tasks{1000000};
  17784. std::atomic_uint count{0};
  17785. std::unique_ptr<TaskQueue> task_queue{
  17786. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17787. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17788. auto queued = task_queue->enqueue(
  17789. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17790. EXPECT_TRUE(queued);
  17791. }
  17792. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17793. task_queue->shutdown();
  17794. #else
  17795. EXPECT_NO_THROW(task_queue->shutdown());
  17796. #endif
  17797. EXPECT_EQ(number_of_tasks, count.load());
  17798. }
  17799. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17800. static constexpr unsigned int number_of_tasks{1000000};
  17801. static constexpr unsigned int qlimit{2};
  17802. unsigned int queued_count{0};
  17803. std::atomic_uint count{0};
  17804. std::unique_ptr<TaskQueue> task_queue{
  17805. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17806. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17807. if (task_queue->enqueue(
  17808. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17809. queued_count++;
  17810. }
  17811. }
  17812. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17813. task_queue->shutdown();
  17814. #else
  17815. EXPECT_NO_THROW(task_queue->shutdown());
  17816. #endif
  17817. EXPECT_EQ(queued_count, count.load());
  17818. EXPECT_TRUE(queued_count <= number_of_tasks);
  17819. EXPECT_TRUE(queued_count >= qlimit);
  17820. }
  17821. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17822. // Use a short idle timeout so a dynamic thread spawns, times out and
  17823. // exits during the test, and the pool keeps working afterwards.
  17824. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17825. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17826. /*idle_timeout_sec=*/1}};
  17827. std::atomic_uint count{0};
  17828. std::condition_variable cv;
  17829. std::mutex mtx;
  17830. bool release = false;
  17831. // Block the base thread so the second task spawns a dynamic thread.
  17832. EXPECT_TRUE(task_queue->enqueue([&] {
  17833. std::unique_lock<std::mutex> lock(mtx);
  17834. while (!release) {
  17835. cv.wait(lock);
  17836. }
  17837. count++;
  17838. }));
  17839. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17840. // Let the dynamic thread finish its task and exceed the idle timeout.
  17841. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17842. {
  17843. std::unique_lock<std::mutex> lock(mtx);
  17844. release = true;
  17845. }
  17846. cv.notify_all();
  17847. // The pool must still accept and run tasks after the dynamic thread exited.
  17848. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17849. task_queue->shutdown();
  17850. EXPECT_EQ(3u, count.load());
  17851. }
  17852. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17853. static constexpr size_t number_of_tasks{32};
  17854. std::unique_ptr<TaskQueue> task_queue{
  17855. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17856. // Let the base threads go idle so the burst below finds them waiting.
  17857. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17858. std::mutex mtx;
  17859. std::condition_variable cv;
  17860. size_t running = 0;
  17861. bool release = false;
  17862. for (size_t i = 0; i < number_of_tasks; i++) {
  17863. EXPECT_TRUE(task_queue->enqueue([&] {
  17864. std::unique_lock<std::mutex> lock(mtx);
  17865. running++;
  17866. cv.notify_all();
  17867. cv.wait(lock, [&] { return release; });
  17868. }));
  17869. }
  17870. {
  17871. std::unique_lock<std::mutex> lock(mtx);
  17872. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17873. [&] { return running == number_of_tasks; }));
  17874. release = true;
  17875. }
  17876. cv.notify_all();
  17877. task_queue->shutdown();
  17878. }
  17879. TEST(TaskQueueTest, MaxQueuedRequests) {
  17880. static constexpr unsigned int qlimit{3};
  17881. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17882. std::condition_variable sem_cv;
  17883. std::mutex sem_mtx;
  17884. int credits = 0;
  17885. bool queued;
  17886. /* Fill up the queue with tasks that will block until we give them credits to
  17887. * complete. */
  17888. for (unsigned int n = 0; n <= qlimit;) {
  17889. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17890. std::unique_lock<std::mutex> lock(sem_mtx);
  17891. while (credits <= 0) {
  17892. sem_cv.wait(lock);
  17893. }
  17894. /* Consume the credit and signal the test code if they are all gone. */
  17895. if (--credits == 0) { sem_cv.notify_one(); }
  17896. });
  17897. if (n < qlimit) {
  17898. /* The first qlimit enqueues must succeed. */
  17899. EXPECT_TRUE(queued);
  17900. } else {
  17901. /* The last one will succeed only when the worker thread
  17902. * starts and dequeues the first blocking task. Although
  17903. * not necessary for the correctness of this test, we sleep for
  17904. * a short while to avoid busy waiting. */
  17905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17906. }
  17907. if (queued) { n++; }
  17908. }
  17909. /* Further enqueues must fail since the queue is full. */
  17910. for (auto i = 0; i < 4; i++) {
  17911. queued = task_queue->enqueue([] {});
  17912. EXPECT_FALSE(queued);
  17913. }
  17914. /* Give the credits to allow the previous tasks to complete. */
  17915. {
  17916. std::unique_lock<std::mutex> lock(sem_mtx);
  17917. credits += qlimit + 1;
  17918. }
  17919. sem_cv.notify_all();
  17920. /* Wait for all the credits to be consumed. */
  17921. {
  17922. std::unique_lock<std::mutex> lock(sem_mtx);
  17923. while (credits > 0) {
  17924. sem_cv.wait(lock);
  17925. }
  17926. }
  17927. /* Check that we are able again to enqueue at least qlimit tasks. */
  17928. for (unsigned int i = 0; i < qlimit; i++) {
  17929. queued = task_queue->enqueue([] {});
  17930. EXPECT_TRUE(queued);
  17931. }
  17932. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17933. task_queue->shutdown();
  17934. #else
  17935. EXPECT_NO_THROW(task_queue->shutdown());
  17936. #endif
  17937. }
  17938. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17939. Server svr;
  17940. std::string method;
  17941. std::string body;
  17942. auto has_content_length = false;
  17943. auto has_transfer_encoding = false;
  17944. std::atomic<int> bad_requests{0};
  17945. // Leftover body bytes get parsed as a malformed request and answered with
  17946. // 400
  17947. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17948. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17949. });
  17950. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17951. res.set_redirect("/down", StatusCode::SeeOther_303);
  17952. });
  17953. svr.Get("/down", [&](const Request &req, Response &res) {
  17954. method = req.method;
  17955. body = req.body;
  17956. has_content_length = req.has_header("Content-Length");
  17957. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17958. res.set_content("ok", "text/plain");
  17959. });
  17960. auto port = svr.bind_to_any_port(HOST);
  17961. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17962. auto se = detail::scope_exit([&] {
  17963. svr.stop();
  17964. thread.join();
  17965. ASSERT_FALSE(svr.is_running());
  17966. });
  17967. svr.wait_until_ready();
  17968. const std::string payload = "SECRET-BODY";
  17969. auto check = [&](Client &cli, const Result &res) {
  17970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17971. EXPECT_EQ(StatusCode::OK_200, res->status);
  17972. EXPECT_EQ("ok", res->body);
  17973. EXPECT_EQ("GET", method);
  17974. EXPECT_TRUE(body.empty());
  17975. EXPECT_FALSE(has_content_length);
  17976. EXPECT_FALSE(has_transfer_encoding);
  17977. // Nothing of the original body may be left on the connection
  17978. auto res2 = cli.Get("/down");
  17979. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17980. EXPECT_EQ(StatusCode::OK_200, res2->status);
  17981. EXPECT_EQ("ok", res2->body);
  17982. EXPECT_EQ(0, bad_requests);
  17983. };
  17984. // With content length
  17985. {
  17986. Client cli(HOST, port);
  17987. cli.set_keep_alive(true);
  17988. cli.set_follow_location(true);
  17989. auto res = cli.Post(
  17990. "/up", payload.size(),
  17991. [&](size_t offset, size_t length, DataSink &sink) {
  17992. return sink.write(payload.data() + offset, length);
  17993. },
  17994. "text/plain");
  17995. check(cli, res);
  17996. }
  17997. // Without content length (chunked)
  17998. {
  17999. Client cli(HOST, port);
  18000. cli.set_keep_alive(true);
  18001. cli.set_follow_location(true);
  18002. auto res = cli.Post(
  18003. "/up",
  18004. [&](size_t /*offset*/, DataSink &sink) {
  18005. sink.write(payload.data(), payload.size());
  18006. sink.done();
  18007. return true;
  18008. },
  18009. "text/plain");
  18010. check(cli, res);
  18011. }
  18012. }
  18013. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18014. Server svr;
  18015. std::string target;
  18016. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18017. // Echo the still-encoded name back in the Location
  18018. const std::string prefix = "/start/";
  18019. res.status = StatusCode::Found_302;
  18020. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18021. });
  18022. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18023. target = req.target;
  18024. res.set_content("ok", "text/plain");
  18025. });
  18026. auto port = svr.bind_to_any_port(HOST);
  18027. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18028. auto se = detail::scope_exit([&] {
  18029. svr.stop();
  18030. thread.join();
  18031. ASSERT_FALSE(svr.is_running());
  18032. });
  18033. svr.wait_until_ready();
  18034. // Decoding the Location path would turn the first four into a path
  18035. // separator, a query delimiter, a fragment delimiter and a different
  18036. // percent-encoded octet. The rest must keep reaching the server as they are.
  18037. const std::vector<std::string> names = {
  18038. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18039. };
  18040. for (auto path_encode : {true, false}) {
  18041. Client cli(HOST, port);
  18042. cli.set_follow_location(true);
  18043. cli.set_path_encode(path_encode);
  18044. for (const auto &name : names) {
  18045. target.clear();
  18046. auto res = cli.Get("/start/" + name);
  18047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18048. EXPECT_EQ(StatusCode::OK_200, res->status);
  18049. EXPECT_EQ("/dest/" + name, target);
  18050. }
  18051. }
  18052. }
  18053. TEST(RedirectTest, NotModifiedIsReturned) {
  18054. Server svr;
  18055. svr.Get("/cached", [](const Request &, Response &res) {
  18056. res.status = StatusCode::NotModified_304;
  18057. });
  18058. auto port = svr.bind_to_any_port(HOST);
  18059. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18060. auto se = detail::scope_exit([&] {
  18061. svr.stop();
  18062. thread.join();
  18063. ASSERT_FALSE(svr.is_running());
  18064. });
  18065. svr.wait_until_ready();
  18066. Client cli(HOST, port);
  18067. cli.set_follow_location(true);
  18068. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18070. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18071. }
  18072. TEST(RedirectTest, NoLocationIsReturned) {
  18073. Server svr;
  18074. svr.Get("/no-location", [](const Request &, Response &res) {
  18075. res.status = StatusCode::Found_302;
  18076. res.set_content("no location", "text/plain");
  18077. });
  18078. auto port = svr.bind_to_any_port(HOST);
  18079. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18080. auto se = detail::scope_exit([&] {
  18081. svr.stop();
  18082. thread.join();
  18083. ASSERT_FALSE(svr.is_running());
  18084. });
  18085. svr.wait_until_ready();
  18086. Client cli(HOST, port);
  18087. cli.set_follow_location(true);
  18088. auto res = cli.Get("/no-location");
  18089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18090. EXPECT_EQ(StatusCode::Found_302, res->status);
  18091. EXPECT_EQ("no location", res->body);
  18092. // The callbacks see the body of the response that is returned
  18093. auto handler_called = false;
  18094. auto progress_called = false;
  18095. std::string body;
  18096. auto res2 = cli.Get(
  18097. "/no-location",
  18098. [&](const Response &) {
  18099. handler_called = true;
  18100. return true;
  18101. },
  18102. [&](const char *data, size_t data_length) {
  18103. body.append(data, data_length);
  18104. return true;
  18105. },
  18106. [&](size_t, size_t) {
  18107. progress_called = true;
  18108. return true;
  18109. });
  18110. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18111. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18112. EXPECT_TRUE(handler_called);
  18113. EXPECT_TRUE(progress_called);
  18114. EXPECT_EQ("no location", body);
  18115. }
  18116. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18117. Server svr;
  18118. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18119. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18120. });
  18121. svr.Get("/hello", [](const Request &req, Response &res) {
  18122. res.set_content(req.get_param_value("key"), "text/plain");
  18123. });
  18124. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18125. auto se = detail::scope_exit([&] {
  18126. svr.stop();
  18127. thread.join();
  18128. ASSERT_FALSE(svr.is_running());
  18129. });
  18130. svr.wait_until_ready();
  18131. {
  18132. Client cli(HOST, PORT);
  18133. cli.set_follow_location(true);
  18134. auto res = cli.Get("/");
  18135. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18136. EXPECT_EQ(StatusCode::OK_200, res->status);
  18137. EXPECT_EQ("val&key2=val2", res->body);
  18138. }
  18139. }
  18140. #endif
  18141. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18142. Server svr;
  18143. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18144. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18145. });
  18146. svr.Get("/hello", [](const Request &req, Response &res) {
  18147. res.set_content(req.get_param_value("key"), "text/plain");
  18148. });
  18149. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18150. auto se = detail::scope_exit([&] {
  18151. svr.stop();
  18152. thread.join();
  18153. ASSERT_FALSE(svr.is_running());
  18154. });
  18155. svr.wait_until_ready();
  18156. {
  18157. Client cli(HOST, PORT);
  18158. cli.set_follow_location(true);
  18159. auto res = cli.Get("/");
  18160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18161. EXPECT_EQ(StatusCode::OK_200, res->status);
  18162. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18163. }
  18164. }
  18165. TEST(RedirectTest, RedirectWithPlusInPath) {
  18166. Server svr;
  18167. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18168. res.set_redirect("/a+b");
  18169. });
  18170. // Route pattern uses regex; escape + as \\+
  18171. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18172. res.set_content(req.path, "text/plain");
  18173. });
  18174. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18175. auto se = detail::scope_exit([&] {
  18176. svr.stop();
  18177. thread.join();
  18178. ASSERT_FALSE(svr.is_running());
  18179. });
  18180. svr.wait_until_ready();
  18181. {
  18182. Client cli(HOST, PORT);
  18183. cli.set_follow_location(true);
  18184. auto res = cli.Get("/");
  18185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18186. EXPECT_EQ(StatusCode::OK_200, res->status);
  18187. EXPECT_EQ("/a+b", res->body);
  18188. }
  18189. }
  18190. TEST(RedirectTest, ResolveRelativeLocation) {
  18191. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18192. const std::vector<std::pair<std::string, std::string>> cases = {
  18193. {"g", "/b/c/g"},
  18194. {"./g", "/b/c/g"},
  18195. {"g/", "/b/c/g/"},
  18196. {"?y", "/b/c/d;p?y"},
  18197. {"g?y", "/b/c/g?y"},
  18198. {"#s", "/b/c/d;p?q#s"},
  18199. {"g#s", "/b/c/g#s"},
  18200. {"g?y#s", "/b/c/g?y#s"},
  18201. {";x", "/b/c/;x"},
  18202. {"g;x", "/b/c/g;x"},
  18203. {".", "/b/c/"},
  18204. {"./", "/b/c/"},
  18205. {"..", "/b/"},
  18206. {"../", "/b/"},
  18207. {"../g", "/b/g"},
  18208. {"../..", "/"},
  18209. {"../../", "/"},
  18210. {"../../g", "/g"},
  18211. {"../../../g", "/g"},
  18212. {"g.", "/b/c/g."},
  18213. {".g", "/b/c/.g"},
  18214. {"g..", "/b/c/g.."},
  18215. {"..g", "/b/c/..g"},
  18216. {"./../g", "/b/g"},
  18217. {"./g/.", "/b/c/g/"},
  18218. {"g/./h", "/b/c/g/h"},
  18219. {"g/../h", "/b/c/h"},
  18220. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18221. {"g;x=1/../y", "/b/c/y"},
  18222. {"g?y/./x", "/b/c/g?y/./x"},
  18223. {"g#s/../x", "/b/c/g#s/../x"},
  18224. // Not relative-path references, so left for parse_url.
  18225. {"/g", "/g"},
  18226. {"//g", "//g"},
  18227. {"http://g/x", "http://g/x"},
  18228. {"g:h", "g:h"},
  18229. };
  18230. for (const auto &c : cases) {
  18231. EXPECT_EQ(c.second,
  18232. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18233. << c.first;
  18234. }
  18235. // A result starting with "//" is still a path, not a network-path reference
  18236. EXPECT_EQ("/.//g",
  18237. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18238. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18239. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18240. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18241. }
  18242. TEST(RedirectTest, RemoveDotSegments) {
  18243. // RFC 3986 section 5.2.4
  18244. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18245. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18246. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18247. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18248. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18249. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18250. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18251. }
  18252. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18253. Server svr;
  18254. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18255. res.set_redirect("/dir/../target?x=1");
  18256. });
  18257. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18258. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18259. "/dir/./../target");
  18260. });
  18261. svr.Get("/target", [](const Request &req, Response &res) {
  18262. res.set_content(req.path, "text/plain");
  18263. });
  18264. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18265. auto se = detail::scope_exit([&] {
  18266. svr.stop();
  18267. th.join();
  18268. ASSERT_FALSE(svr.is_running());
  18269. });
  18270. svr.wait_until_ready();
  18271. Client cli("localhost", PORT);
  18272. cli.set_follow_location(true);
  18273. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18274. auto res = cli.Get(path);
  18275. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18276. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18277. EXPECT_EQ("/target", res->body) << path;
  18278. }
  18279. }
  18280. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18281. Server svr;
  18282. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18283. res.set_redirect(req.get_param_value("to"));
  18284. });
  18285. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18286. res.set_content(req.target, "text/plain");
  18287. });
  18288. svr.Get("/other", [](const Request &req, Response &res) {
  18289. res.set_content(req.target, "text/plain");
  18290. });
  18291. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18292. auto se = detail::scope_exit([&] {
  18293. svr.stop();
  18294. thread.join();
  18295. ASSERT_FALSE(svr.is_running());
  18296. });
  18297. svr.wait_until_ready();
  18298. const std::vector<std::pair<std::string, std::string>> cases = {
  18299. {"next", "/dir/next"},
  18300. {"./next?x=1", "/dir/next?x=1"},
  18301. {"next?source=https://example.com/catalog",
  18302. "/dir/next?source=https://example.com/catalog"},
  18303. {"../other", "/other"},
  18304. };
  18305. for (const auto &c : cases) {
  18306. Client cli(HOST, PORT);
  18307. cli.set_follow_location(true);
  18308. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18309. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18310. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18311. EXPECT_EQ(c.second, res->body) << c.first;
  18312. }
  18313. }
  18314. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18315. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18316. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18317. Server other;
  18318. std::atomic<int> other_hits{0};
  18319. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18320. other_hits++;
  18321. res.set_content("other", "text/plain");
  18322. });
  18323. auto other_port = other.bind_to_any_port("127.0.0.1");
  18324. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18325. Server svr;
  18326. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18327. res.set_redirect(req.get_param_value("to"));
  18328. });
  18329. svr.Get(".*", [](const Request &req, Response &res) {
  18330. res.set_content(req.path, "text/plain");
  18331. });
  18332. auto port = svr.bind_to_any_port(HOST);
  18333. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18334. auto se = detail::scope_exit([&] {
  18335. svr.stop();
  18336. thread.join();
  18337. other.stop();
  18338. other_thread.join();
  18339. ASSERT_FALSE(svr.is_running());
  18340. ASSERT_FALSE(other.is_running());
  18341. });
  18342. svr.wait_until_ready();
  18343. other.wait_until_ready();
  18344. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18345. for (const auto &to :
  18346. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18347. Client cli(HOST, port);
  18348. cli.set_follow_location(true);
  18349. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18350. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18351. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18352. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18353. }
  18354. EXPECT_EQ(0, other_hits.load());
  18355. }
  18356. #ifdef CPPHTTPLIB_SSL_ENABLED
  18357. TEST(RedirectTest, Issue2185_Online) {
  18358. SSLClient client("github.com");
  18359. client.set_follow_location(true);
  18360. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18361. "Coollab-Windows.zip");
  18362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18363. EXPECT_EQ(StatusCode::OK_200, res->status);
  18364. EXPECT_EQ(9920427U, res->body.size());
  18365. }
  18366. #endif
  18367. TEST(VulnerabilityTest, CRLFInjection) {
  18368. Server svr;
  18369. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18370. res.set_content("Hello 1", "text/plain");
  18371. });
  18372. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18373. res.set_content("Hello 2", "text/plain");
  18374. });
  18375. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18376. res.set_content("Hello 3", "text/plain");
  18377. });
  18378. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18379. res.set_content("Hello 4", "text/plain");
  18380. });
  18381. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18382. for (const auto &x : req.headers) {
  18383. auto key = x.first;
  18384. EXPECT_STRNE("evil", key.c_str());
  18385. }
  18386. });
  18387. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18388. auto se = detail::scope_exit([&] {
  18389. svr.stop();
  18390. thread.join();
  18391. ASSERT_FALSE(svr.is_running());
  18392. });
  18393. svr.wait_until_ready();
  18394. {
  18395. Client cli(HOST, PORT);
  18396. cli.Post("/test1", "A=B",
  18397. "application/x-www-form-urlencoded\r\nevil: hello1");
  18398. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18399. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18400. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18401. }
  18402. }
  18403. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18404. auto server_thread = std::thread([] {
  18405. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18406. default_socket_options(srv);
  18407. sockaddr_in addr{};
  18408. addr.sin_family = AF_INET;
  18409. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18410. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18411. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18412. ::listen(srv, 1);
  18413. sockaddr_in cli_addr{};
  18414. socklen_t cli_len = sizeof(cli_addr);
  18415. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18416. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18417. std::string buf_all;
  18418. char buf[2048];
  18419. ssize_t n;
  18420. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18421. buf_all.append(buf, static_cast<size_t>(n));
  18422. size_t pos;
  18423. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18424. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18425. auto e = request_block.find("\r\n");
  18426. if (e != std::string::npos) {
  18427. auto request_line = request_block.substr(0, e);
  18428. std::string msg =
  18429. "CRLF injection detected in request line: '" + request_line + "'";
  18430. EXPECT_FALSE(true) << msg;
  18431. }
  18432. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18433. ::send(cli,
  18434. #ifdef _WIN32
  18435. static_cast<const char *>(resp.c_str()),
  18436. static_cast<int>(resp.size()),
  18437. #else
  18438. resp.c_str(), resp.size(),
  18439. #endif
  18440. 0);
  18441. buf_all.erase(0, pos + 4);
  18442. }
  18443. }
  18444. detail::close_socket(cli);
  18445. detail::close_socket(srv);
  18446. });
  18447. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18448. auto cli = Client("127.0.0.1", PORT + 1);
  18449. auto headers = Headers{
  18450. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18451. {"Connection", "keep-alive"}};
  18452. auto res = cli.Get("/hi", headers);
  18453. EXPECT_FALSE(res);
  18454. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18455. server_thread.join();
  18456. }
  18457. // A request rejected before any byte reaches the socket must fail right away
  18458. // instead of waiting for a response the server will never send.
  18459. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18460. // The kernel completes the TCP handshake from the listen backlog, so the
  18461. // client connects, but nothing ever reads, responds or closes.
  18462. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18463. default_socket_options(srv);
  18464. sockaddr_in addr{};
  18465. addr.sin_family = AF_INET;
  18466. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18467. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18468. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18469. ASSERT_EQ(0, ::listen(srv, 8));
  18470. auto cli = Client("127.0.0.1", PORT + 1);
  18471. cli.set_read_timeout(10, 0);
  18472. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18473. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18474. std::chrono::steady_clock::now() - start)
  18475. .count();
  18476. };
  18477. {
  18478. Request req;
  18479. req.method = "GE T";
  18480. req.path = "/";
  18481. auto start = std::chrono::steady_clock::now();
  18482. auto res = cli.send(req);
  18483. EXPECT_FALSE(res);
  18484. EXPECT_EQ(Error::Write, res.error());
  18485. EXPECT_LT(elapsed_ms(start), 1000);
  18486. }
  18487. {
  18488. auto start = std::chrono::steady_clock::now();
  18489. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18490. EXPECT_FALSE(res);
  18491. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18492. EXPECT_LT(elapsed_ms(start), 1000);
  18493. }
  18494. EXPECT_FALSE(cli.is_socket_open());
  18495. detail::close_socket(srv);
  18496. }
  18497. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18498. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18499. default_socket_options(srv);
  18500. sockaddr_in addr{};
  18501. addr.sin_family = AF_INET;
  18502. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18503. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18504. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18505. ASSERT_EQ(0, ::listen(srv, 1));
  18506. std::string received;
  18507. auto server_thread = std::thread([&] {
  18508. auto sock = ::accept(srv, nullptr, nullptr);
  18509. if (sock == INVALID_SOCKET) { return; }
  18510. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18511. char buf[2048];
  18512. ssize_t n;
  18513. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18514. received.append(buf, static_cast<size_t>(n));
  18515. }
  18516. detail::close_socket(sock);
  18517. });
  18518. {
  18519. auto cli = Client("127.0.0.1", PORT + 1);
  18520. // "Z" sorts after the default headers, so writing straight to the socket
  18521. // would have sent the request line and those headers before the rejection.
  18522. auto handle =
  18523. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18524. EXPECT_FALSE(handle.is_valid());
  18525. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18526. }
  18527. server_thread.join();
  18528. detail::close_socket(srv);
  18529. EXPECT_TRUE(received.empty()) << received;
  18530. }
  18531. TEST(PathParamsTest, StaticMatch) {
  18532. const auto pattern = "/users/all";
  18533. detail::PathParamsMatcher matcher(pattern);
  18534. Request request;
  18535. request.path = "/users/all";
  18536. ASSERT_TRUE(matcher.match(request));
  18537. std::unordered_map<std::string, std::string> expected_params = {};
  18538. EXPECT_EQ(request.path_params, expected_params);
  18539. }
  18540. TEST(PathParamsTest, StaticMismatch) {
  18541. const auto pattern = "/users/all";
  18542. detail::PathParamsMatcher matcher(pattern);
  18543. Request request;
  18544. request.path = "/users/1";
  18545. ASSERT_FALSE(matcher.match(request));
  18546. }
  18547. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18548. const auto pattern = "/users/:id/subscriptions";
  18549. detail::PathParamsMatcher matcher(pattern);
  18550. Request request;
  18551. request.path = "/users/42/subscriptions";
  18552. ASSERT_TRUE(matcher.match(request));
  18553. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18554. EXPECT_EQ(request.path_params, expected_params);
  18555. }
  18556. TEST(PathParamsTest, SingleParamInTheEnd) {
  18557. const auto pattern = "/users/:id";
  18558. detail::PathParamsMatcher matcher(pattern);
  18559. Request request;
  18560. request.path = "/users/24";
  18561. ASSERT_TRUE(matcher.match(request));
  18562. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18563. EXPECT_EQ(request.path_params, expected_params);
  18564. }
  18565. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18566. const auto pattern = "/users/:id/";
  18567. detail::PathParamsMatcher matcher(pattern);
  18568. Request request;
  18569. request.path = "/users/42/";
  18570. ASSERT_TRUE(matcher.match(request));
  18571. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18572. EXPECT_EQ(request.path_params, expected_params);
  18573. }
  18574. TEST(PathParamsTest, EmptyParam) {
  18575. const auto pattern = "/users/:id/";
  18576. detail::PathParamsMatcher matcher(pattern);
  18577. Request request;
  18578. request.path = "/users//";
  18579. ASSERT_TRUE(matcher.match(request));
  18580. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18581. EXPECT_EQ(request.path_params, expected_params);
  18582. }
  18583. TEST(PathParamsTest, FragmentMismatch) {
  18584. const auto pattern = "/users/:id/";
  18585. detail::PathParamsMatcher matcher(pattern);
  18586. Request request;
  18587. request.path = "/admins/24/";
  18588. ASSERT_FALSE(matcher.match(request));
  18589. }
  18590. TEST(PathParamsTest, ExtraFragments) {
  18591. const auto pattern = "/users/:id";
  18592. detail::PathParamsMatcher matcher(pattern);
  18593. Request request;
  18594. request.path = "/users/42/subscriptions";
  18595. ASSERT_FALSE(matcher.match(request));
  18596. }
  18597. TEST(PathParamsTest, MissingTrailingParam) {
  18598. const auto pattern = "/users/:id";
  18599. detail::PathParamsMatcher matcher(pattern);
  18600. Request request;
  18601. request.path = "/users";
  18602. ASSERT_FALSE(matcher.match(request));
  18603. }
  18604. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18605. const auto pattern = "/users/:id/subscriptions";
  18606. detail::PathParamsMatcher matcher(pattern);
  18607. Request request;
  18608. request.path = "/users/subscriptions";
  18609. ASSERT_FALSE(matcher.match(request));
  18610. }
  18611. TEST(PathParamsTest, MultipleParams) {
  18612. const auto pattern = "/users/:userid/subscriptions/:subid";
  18613. detail::PathParamsMatcher matcher(pattern);
  18614. Request request;
  18615. request.path = "/users/42/subscriptions/2";
  18616. ASSERT_TRUE(matcher.match(request));
  18617. std::unordered_map<std::string, std::string> expected_params = {
  18618. {"userid", "42"}, {"subid", "2"}};
  18619. EXPECT_EQ(request.path_params, expected_params);
  18620. }
  18621. TEST(PathParamsTest, SequenceOfParams) {
  18622. const auto pattern = "/values/:x/:y/:z";
  18623. detail::PathParamsMatcher matcher(pattern);
  18624. Request request;
  18625. request.path = "/values/1/2/3";
  18626. ASSERT_TRUE(matcher.match(request));
  18627. std::unordered_map<std::string, std::string> expected_params = {
  18628. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18629. EXPECT_EQ(request.path_params, expected_params);
  18630. }
  18631. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18632. const auto pattern = "/prefix:suffix";
  18633. detail::PathParamsMatcher matcher(pattern);
  18634. Request request;
  18635. request.path = "/prefix:suffix";
  18636. ASSERT_TRUE(matcher.match(request));
  18637. const std::unordered_map<std::string, std::string> expected_params = {};
  18638. EXPECT_EQ(request.path_params, expected_params);
  18639. }
  18640. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18641. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18642. // calling thread's stack on a long enough path for a quantified pattern;
  18643. // RegexMatcher must refuse to run regex matching on paths beyond
  18644. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18645. detail::RegexMatcher matcher("/files/(.*)");
  18646. Request within_limit;
  18647. within_limit.path = "/files/" + std::string(10, 'A');
  18648. EXPECT_TRUE(matcher.match(within_limit));
  18649. Request over_limit;
  18650. over_limit.path =
  18651. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18652. EXPECT_FALSE(matcher.match(over_limit));
  18653. }
  18654. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18655. Server svr;
  18656. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18657. res.set_content("ok", "text/plain");
  18658. });
  18659. auto port = svr.bind_to_any_port(HOST);
  18660. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18661. auto se = detail::scope_exit([&] {
  18662. svr.stop();
  18663. thread.join();
  18664. ASSERT_FALSE(svr.is_running());
  18665. });
  18666. svr.wait_until_ready();
  18667. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18668. // request URI limit; this used to be able to crash the process.
  18669. std::string path =
  18670. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18671. std::string req = "GET " + path +
  18672. " HTTP/1.1\r\n"
  18673. "Host: " +
  18674. std::string(HOST) + ":" + std::to_string(port) +
  18675. "\r\n"
  18676. "Connection: close\r\n"
  18677. "\r\n";
  18678. std::string response;
  18679. ASSERT_TRUE(send_request(5, req, &response, port));
  18680. EXPECT_NE(std::string::npos, response.find("404"));
  18681. }
  18682. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18683. Server svr;
  18684. auto handler = [](const Request & /*req*/, Response &res) {
  18685. res.set_content("hit", "text/plain");
  18686. };
  18687. // No regex metacharacter, so this one is compared literally
  18688. svr.Get("/literal/route", handler);
  18689. // '.' is a regex metacharacter, so this one must keep regex semantics
  18690. svr.Get("/a.c", handler);
  18691. auto port = svr.bind_to_any_port(HOST);
  18692. std::thread t([&]() { svr.listen_after_bind(); });
  18693. auto se = detail::scope_exit([&] {
  18694. svr.stop();
  18695. t.join();
  18696. ASSERT_FALSE(svr.is_running());
  18697. });
  18698. svr.wait_until_ready();
  18699. Client cli(HOST, port);
  18700. struct {
  18701. const char *path;
  18702. int status;
  18703. } cases[] = {
  18704. {"/literal/route", StatusCode::OK_200},
  18705. {"/literal/routes", StatusCode::NotFound_404},
  18706. {"/literal/rout", StatusCode::NotFound_404},
  18707. {"/abc", StatusCode::OK_200},
  18708. {"/a.c", StatusCode::OK_200},
  18709. };
  18710. for (const auto &x : cases) {
  18711. auto res = cli.Get(x.path);
  18712. ASSERT_TRUE(res) << x.path;
  18713. EXPECT_EQ(x.status, res->status) << x.path;
  18714. }
  18715. }
  18716. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18717. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18718. // from exhausting the stack, so it must only constrain routes that actually
  18719. // run a regular expression. A literal route is matched by comparison and
  18720. // stays usable at any length.
  18721. Server svr;
  18722. const std::string pattern =
  18723. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18724. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18725. res.set_content("hit", "text/plain");
  18726. });
  18727. auto port = svr.bind_to_any_port(HOST);
  18728. std::thread t([&]() { svr.listen_after_bind(); });
  18729. auto se = detail::scope_exit([&] {
  18730. svr.stop();
  18731. t.join();
  18732. ASSERT_FALSE(svr.is_running());
  18733. });
  18734. svr.wait_until_ready();
  18735. Client cli(HOST, port);
  18736. auto res = cli.Get(pattern);
  18737. ASSERT_TRUE(res);
  18738. EXPECT_EQ(StatusCode::OK_200, res->status);
  18739. }
  18740. TEST(ParseUrlTest, VariousPatterns) {
  18741. {
  18742. detail::UrlComponents uc;
  18743. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18744. EXPECT_EQ("http", uc.scheme);
  18745. EXPECT_EQ("example.com", uc.host);
  18746. EXPECT_EQ("8080", uc.port);
  18747. EXPECT_EQ("/path", uc.path);
  18748. EXPECT_EQ("?q=1", uc.query);
  18749. }
  18750. {
  18751. detail::UrlComponents uc;
  18752. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18753. EXPECT_EQ("https", uc.scheme);
  18754. EXPECT_EQ("example.com", uc.host);
  18755. EXPECT_TRUE(uc.port.empty());
  18756. EXPECT_EQ("/path", uc.path);
  18757. }
  18758. {
  18759. detail::UrlComponents uc;
  18760. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18761. EXPECT_EQ("::1", uc.host);
  18762. EXPECT_EQ("8080", uc.port);
  18763. EXPECT_EQ("/path", uc.path);
  18764. }
  18765. {
  18766. detail::UrlComponents uc;
  18767. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18768. }
  18769. {
  18770. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18771. // the path while the connection still targets the bracketed host.
  18772. detail::UrlComponents uc;
  18773. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18774. }
  18775. {
  18776. detail::UrlComponents uc;
  18777. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18778. }
  18779. {
  18780. detail::UrlComponents uc;
  18781. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18782. EXPECT_EQ("::1", uc.host);
  18783. EXPECT_TRUE(uc.port.empty());
  18784. EXPECT_EQ("/path", uc.path);
  18785. }
  18786. {
  18787. detail::UrlComponents uc;
  18788. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18789. EXPECT_TRUE(uc.scheme.empty());
  18790. EXPECT_EQ("example.com", uc.host);
  18791. EXPECT_EQ("/path", uc.path);
  18792. EXPECT_EQ("?q=1", uc.query);
  18793. }
  18794. {
  18795. detail::UrlComponents uc;
  18796. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18797. EXPECT_TRUE(uc.host.empty());
  18798. EXPECT_EQ("/path", uc.path);
  18799. EXPECT_EQ("?q=1", uc.query);
  18800. }
  18801. {
  18802. detail::UrlComponents uc;
  18803. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18804. EXPECT_EQ("example.com", uc.host);
  18805. EXPECT_EQ("8080", uc.port);
  18806. }
  18807. {
  18808. // Unix socket path — must not be parsed as host
  18809. detail::UrlComponents uc;
  18810. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18811. EXPECT_TRUE(uc.host.empty());
  18812. }
  18813. {
  18814. detail::UrlComponents uc;
  18815. ASSERT_TRUE(detail::parse_url("", uc));
  18816. EXPECT_TRUE(uc.host.empty());
  18817. EXPECT_TRUE(uc.path.empty());
  18818. }
  18819. {
  18820. detail::UrlComponents uc;
  18821. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18822. EXPECT_EQ("http", uc.scheme);
  18823. }
  18824. {
  18825. detail::UrlComponents uc;
  18826. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18827. }
  18828. {
  18829. // Accepted by parse_url; callers restrict to http/https
  18830. detail::UrlComponents uc;
  18831. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18832. EXPECT_EQ("ftp", uc.scheme);
  18833. }
  18834. {
  18835. detail::UrlComponents uc;
  18836. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18837. }
  18838. {
  18839. detail::UrlComponents uc;
  18840. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18841. }
  18842. }
  18843. TEST(ParseUrlTest, FragmentHandling) {
  18844. {
  18845. detail::UrlComponents uc;
  18846. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18847. EXPECT_EQ("/path", uc.path);
  18848. EXPECT_TRUE(uc.query.empty());
  18849. }
  18850. {
  18851. detail::UrlComponents uc;
  18852. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18853. EXPECT_TRUE(uc.path.empty());
  18854. EXPECT_TRUE(uc.query.empty());
  18855. }
  18856. }
  18857. TEST(ParseUrlTest, UserinfoHandling) {
  18858. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18859. // parsers would see evil.com as the host.
  18860. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18861. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18862. for (auto url : urls) {
  18863. detail::UrlComponents uc;
  18864. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18865. }
  18866. }
  18867. TEST(ParseUrlTest, IPv6EdgeCases) {
  18868. {
  18869. detail::UrlComponents uc;
  18870. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18871. EXPECT_TRUE(uc.scheme.empty());
  18872. EXPECT_EQ("::1", uc.host);
  18873. EXPECT_EQ("8080", uc.port);
  18874. }
  18875. {
  18876. // Zone ID '%25' is not in [a-fA-F0-9:]
  18877. detail::UrlComponents uc;
  18878. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18879. }
  18880. }
  18881. TEST(ParseUrlTest, SchemeEdgeCases) {
  18882. {
  18883. detail::UrlComponents uc;
  18884. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18885. }
  18886. {
  18887. detail::UrlComponents uc;
  18888. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18889. }
  18890. {
  18891. detail::UrlComponents uc;
  18892. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18893. }
  18894. {
  18895. detail::UrlComponents uc;
  18896. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18897. EXPECT_EQ("https", uc.scheme);
  18898. }
  18899. {
  18900. detail::UrlComponents uc;
  18901. ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
  18902. EXPECT_TRUE(uc.scheme.empty());
  18903. EXPECT_TRUE(uc.host.empty());
  18904. EXPECT_EQ("/path", uc.path);
  18905. EXPECT_EQ("?next=https://example.com/", uc.query);
  18906. }
  18907. }
  18908. TEST(ParseUrlTest, PortEdgeCases) {
  18909. {
  18910. detail::UrlComponents uc;
  18911. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18912. EXPECT_TRUE(uc.port.empty());
  18913. EXPECT_EQ("/path", uc.path);
  18914. }
  18915. {
  18916. // parse_url accepts any port string; validation is done by parse_port
  18917. detail::UrlComponents uc;
  18918. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18919. EXPECT_EQ("abc", uc.port);
  18920. }
  18921. }
  18922. TEST(ParseUrlTest, WebSocketPatterns) {
  18923. {
  18924. detail::UrlComponents uc;
  18925. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18926. EXPECT_EQ("ws", uc.scheme);
  18927. EXPECT_EQ("echo.example.com", uc.host);
  18928. EXPECT_EQ("8080", uc.port);
  18929. EXPECT_EQ("/ws", uc.path);
  18930. }
  18931. {
  18932. detail::UrlComponents uc;
  18933. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18934. EXPECT_EQ("wss", uc.scheme);
  18935. EXPECT_EQ("echo.example.com", uc.host);
  18936. EXPECT_TRUE(uc.port.empty());
  18937. EXPECT_EQ("/ws", uc.path);
  18938. }
  18939. }
  18940. TEST(ParseUrlTest, QueryOnly) {
  18941. detail::UrlComponents uc;
  18942. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18943. EXPECT_TRUE(uc.host.empty());
  18944. EXPECT_TRUE(uc.path.empty());
  18945. EXPECT_EQ("?q=1&r=2", uc.query);
  18946. }
  18947. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18948. detail::UrlComponents uc;
  18949. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18950. EXPECT_TRUE(uc.scheme.empty());
  18951. EXPECT_EQ("example.com", uc.host);
  18952. EXPECT_EQ("443", uc.port);
  18953. EXPECT_EQ("/path", uc.path);
  18954. }
  18955. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18956. // If ipv6 regex working, regex match codepath is taken.
  18957. // else port will default to 80 in Client impl
  18958. int clientImplMagicPort = 80;
  18959. int port = 4321;
  18960. // above ports must be different to avoid false negative
  18961. EXPECT_NE(clientImplMagicPort, port);
  18962. std::string ipV6TestURL = "http://[ff06::c3]";
  18963. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18964. CLIENT_PRIVATE_KEY_FILE);
  18965. EXPECT_EQ(cli.port(), port);
  18966. }
  18967. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  18968. auto file_path = "./www/dir/index.html";
  18969. auto dir_path = "./www/dir";
  18970. detail::FileStat stat_file(file_path);
  18971. EXPECT_TRUE(stat_file.is_file());
  18972. EXPECT_FALSE(stat_file.is_dir());
  18973. detail::FileStat stat_dir(dir_path);
  18974. EXPECT_FALSE(stat_dir.is_file());
  18975. EXPECT_TRUE(stat_dir.is_dir());
  18976. }
  18977. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  18978. // IPv4 with default HTTP port (80)
  18979. EXPECT_EQ("example.com",
  18980. detail::make_host_and_port_string("example.com", 80, false));
  18981. // IPv4 with default HTTPS port (443)
  18982. EXPECT_EQ("example.com",
  18983. detail::make_host_and_port_string("example.com", 443, true));
  18984. // IPv4 with non-default HTTP port
  18985. EXPECT_EQ("example.com:8080",
  18986. detail::make_host_and_port_string("example.com", 8080, false));
  18987. // IPv4 with non-default HTTPS port
  18988. EXPECT_EQ("example.com:8443",
  18989. detail::make_host_and_port_string("example.com", 8443, true));
  18990. // IPv6 with default HTTP port (80)
  18991. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  18992. // IPv6 with default HTTPS port (443)
  18993. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  18994. // IPv6 with non-default HTTP port
  18995. EXPECT_EQ("[::1]:8080",
  18996. detail::make_host_and_port_string("::1", 8080, false));
  18997. // IPv6 with non-default HTTPS port
  18998. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  18999. // IPv6 full address with default port
  19000. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  19001. detail::make_host_and_port_string(
  19002. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  19003. // IPv6 full address with non-default port
  19004. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  19005. detail::make_host_and_port_string(
  19006. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  19007. // IPv6 localhost with non-default port
  19008. EXPECT_EQ("[::1]:3000",
  19009. detail::make_host_and_port_string("::1", 3000, false));
  19010. // IPv6 with zone ID (link-local address) with default port
  19011. EXPECT_EQ("[fe80::1%eth0]",
  19012. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19013. // IPv6 with zone ID (link-local address) with non-default port
  19014. EXPECT_EQ("[fe80::1%eth0]:8080",
  19015. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19016. // Edge case: Port 443 with is_ssl=false (should add port)
  19017. EXPECT_EQ("example.com:443",
  19018. detail::make_host_and_port_string("example.com", 443, false));
  19019. // Edge case: Port 80 with is_ssl=true (should add port)
  19020. EXPECT_EQ("example.com:80",
  19021. detail::make_host_and_port_string("example.com", 80, true));
  19022. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19023. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19024. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19025. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19026. // Security fix: Already bracketed IPv6 should not get double brackets
  19027. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19028. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19029. EXPECT_EQ("[::1]:8080",
  19030. detail::make_host_and_port_string("[::1]", 8080, false));
  19031. EXPECT_EQ("[2001:db8::1]:8080",
  19032. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19033. EXPECT_EQ("[fe80::1%eth0]",
  19034. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19035. EXPECT_EQ("[fe80::1%eth0]:8080",
  19036. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19037. // Edge case: Empty host (should return as-is)
  19038. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19039. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19040. // This is a known limitation but shouldn't crash
  19041. EXPECT_EQ("[host:name]",
  19042. detail::make_host_and_port_string("host:name", 80, false));
  19043. // Port number edge cases (no validation, but should not crash)
  19044. EXPECT_EQ("example.com:0",
  19045. detail::make_host_and_port_string("example.com", 0, false));
  19046. EXPECT_EQ("example.com:-1",
  19047. detail::make_host_and_port_string("example.com", -1, false));
  19048. EXPECT_EQ("example.com:65535",
  19049. detail::make_host_and_port_string("example.com", 65535, false));
  19050. EXPECT_EQ("example.com:65536",
  19051. detail::make_host_and_port_string("example.com", 65536, false));
  19052. }
  19053. namespace httplib {
  19054. namespace detail {
  19055. std::string
  19056. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19057. const std::string &host, int port);
  19058. } // namespace detail
  19059. } // namespace httplib
  19060. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19061. std::map<std::string, std::string> addr_map = {
  19062. {"ipv4.example", "192.0.2.10"},
  19063. {"ipv6.example", "2001:db8::1"},
  19064. {"name.example", "internal.example.lan"},
  19065. {"empty.example", ""}};
  19066. EXPECT_EQ("192.0.2.10:443",
  19067. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19068. EXPECT_EQ("[2001:db8::1]:443",
  19069. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19070. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19071. addr_map, "name.example", 8443));
  19072. // An empty or absent mapping keeps the hostname as the target
  19073. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19074. addr_map, "empty.example", 443));
  19075. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19076. addr_map, "other.example", 443));
  19077. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19078. }
  19079. #ifdef CPPHTTPLIB_SSL_ENABLED
  19080. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19081. httplib::SSLClient cli("roblox.com", 443);
  19082. cli.set_follow_location(true);
  19083. auto res = cli.Get("/");
  19084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19085. EXPECT_EQ(StatusCode::OK_200, res->status);
  19086. }
  19087. #endif
  19088. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19089. Server svr;
  19090. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19091. EXPECT_EQ(res.status, 400);
  19092. });
  19093. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19094. auto se = detail::scope_exit([&] {
  19095. svr.stop();
  19096. thread.join();
  19097. ASSERT_FALSE(svr.is_running());
  19098. });
  19099. svr.wait_until_ready();
  19100. Client cli(HOST, PORT);
  19101. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19102. }
  19103. TEST(InvalidHeaderCharsTest, is_field_name) {
  19104. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19105. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19106. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19107. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19108. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19109. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19110. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19111. EXPECT_FALSE(detail::fields::is_field_name(""));
  19112. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19113. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19114. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19115. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19116. }
  19117. TEST(InvalidHeaderCharsTest, is_field_value) {
  19118. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19119. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19120. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19121. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19122. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19123. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19124. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19125. EXPECT_TRUE(detail::fields::is_field_value(""));
  19126. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19127. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19128. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19129. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19130. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19131. }
  19132. TEST(InvalidHeaderCharsTest, OnServer) {
  19133. Server svr;
  19134. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19135. std::string header = "Not Set";
  19136. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19137. res.set_header(header, "value");
  19138. res.set_content("Page Content Page Content", "text/plain");
  19139. });
  19140. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19141. std::string header = "Not Set";
  19142. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19143. res.set_header("X-Test", header);
  19144. res.set_content("Page Content Page Content", "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. Client cli(HOST, PORT);
  19154. {
  19155. auto res = cli.Get(
  19156. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19158. EXPECT_EQ("Page Content Page Content", res->body);
  19159. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19160. }
  19161. {
  19162. auto res = cli.Get(
  19163. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19165. EXPECT_EQ("Page Content Page Content", res->body);
  19166. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19167. }
  19168. }
  19169. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19170. auto handled = false;
  19171. Server svr;
  19172. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19173. thread t = thread([&] { svr.listen(HOST, PORT); });
  19174. auto se = detail::scope_exit([&] {
  19175. svr.stop();
  19176. t.join();
  19177. ASSERT_FALSE(svr.is_running());
  19178. ASSERT_FALSE(handled);
  19179. });
  19180. svr.wait_until_ready();
  19181. auto req = "POST /test HTTP/1.1\r\n"
  19182. "Content-Length: x\r\n"
  19183. "\r\n";
  19184. std::string response;
  19185. ASSERT_TRUE(send_request(1, req, &response));
  19186. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19187. response.substr(0, response.find("\r\n")));
  19188. }
  19189. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19190. // case-insensitive, and a server that receives a 100-continue expectation in
  19191. // an HTTP/1.0 request MUST ignore it.
  19192. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19193. std::string response;
  19194. ASSERT_TRUE(send_request(1, req, &response, port));
  19195. *got_100 = response.find("100 Continue") != std::string::npos;
  19196. }
  19197. class ExpectTokenTest : public ::testing::Test {
  19198. protected:
  19199. void SetUp() override {
  19200. svr_.Post("/p", [](const Request &, Response &res) {
  19201. res.set_content("ok", "text/plain");
  19202. });
  19203. port_ = svr_.bind_to_any_port(HOST);
  19204. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19205. svr_.wait_until_ready();
  19206. }
  19207. void TearDown() override {
  19208. svr_.stop();
  19209. if (thread_.joinable()) { thread_.join(); }
  19210. }
  19211. std::string request(const char *version, const char *expect_value) const {
  19212. return std::string("POST /p ") + version +
  19213. "\r\n"
  19214. "Host: localhost\r\n"
  19215. "Content-Length: 2\r\n"
  19216. "Connection: close\r\n"
  19217. "Expect: " +
  19218. expect_value +
  19219. "\r\n"
  19220. "\r\n"
  19221. "hi";
  19222. }
  19223. Server svr_;
  19224. int port_ = 0;
  19225. thread thread_;
  19226. };
  19227. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19228. bool got_100 = false;
  19229. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19230. EXPECT_TRUE(got_100);
  19231. }
  19232. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19233. bool got_100 = true;
  19234. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19235. EXPECT_FALSE(got_100);
  19236. }
  19237. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19238. bool got_100 = false;
  19239. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19240. EXPECT_TRUE(got_100);
  19241. }
  19242. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19243. bool got_100 = false;
  19244. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19245. EXPECT_TRUE(got_100);
  19246. }
  19247. // `100 Continue` is sent only when the server starts reading the body, so a
  19248. // request rejected before that never invites the client to send it. The
  19249. // requests below carry the expectation but withhold the body, as a client
  19250. // waiting for `100 Continue` would.
  19251. // A POST that expects `100 Continue` and withholds its two-byte body.
  19252. static std::string expect_headers_only(const std::string &path) {
  19253. return "POST " + path +
  19254. " HTTP/1.1\r\n"
  19255. "Host: localhost\r\n"
  19256. "Content-Length: 2\r\n"
  19257. "Expect: 100-continue\r\n"
  19258. "\r\n";
  19259. }
  19260. class ExpectLazyContinueTest : public ::testing::Test {
  19261. protected:
  19262. void SetUp() override {
  19263. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19264. if (req.path == "/pre-routing") {
  19265. res.status = StatusCode::Unauthorized_401;
  19266. return Server::HandlerResponse::Handled;
  19267. }
  19268. return Server::HandlerResponse::Unhandled;
  19269. });
  19270. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19271. if (req.matched_route == "/pre-request") {
  19272. res.status = StatusCode::Forbidden_403;
  19273. return Server::HandlerResponse::Handled;
  19274. }
  19275. return Server::HandlerResponse::Unhandled;
  19276. });
  19277. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19278. res.set_content("ok", "text/plain");
  19279. });
  19280. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19281. res.set_content("ok", "text/plain");
  19282. });
  19283. svr_.Post("/reader-used", [](const Request &, Response &res,
  19284. const ContentReader &content_reader) {
  19285. std::string body;
  19286. content_reader([&](const char *data, size_t len) {
  19287. body.append(data, len);
  19288. return true;
  19289. });
  19290. res.set_content(body, "text/plain");
  19291. });
  19292. svr_.Post("/reader-unused",
  19293. [](const Request &, Response &res, const ContentReader &) {
  19294. res.set_content("ignored", "text/plain");
  19295. });
  19296. port_ = svr_.bind_to_any_port(HOST);
  19297. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19298. svr_.wait_until_ready();
  19299. }
  19300. void TearDown() override {
  19301. svr_.stop();
  19302. if (thread_.joinable()) { thread_.join(); }
  19303. }
  19304. // Sends `req` and reads until the server closes the connection. Returns
  19305. // false if the read had to wait for the client-side timeout instead.
  19306. bool send_until_closed(const std::string &req, std::string *resp) const {
  19307. auto start = std::chrono::steady_clock::now();
  19308. if (!send_request(3, req, resp, port_)) { return false; }
  19309. auto elapsed = std::chrono::steady_clock::now() - start;
  19310. return elapsed < std::chrono::seconds(2);
  19311. }
  19312. // The final response comes without `100 Continue`, and the server closes
  19313. // the connection since the body may or may not follow.
  19314. void expect_final_without_interim(const std::string &path,
  19315. const char *status_line) const {
  19316. std::string resp;
  19317. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19318. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19319. EXPECT_EQ(0u, resp.find(status_line));
  19320. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19321. }
  19322. Server svr_;
  19323. int port_ = 0;
  19324. thread thread_;
  19325. };
  19326. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19327. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19328. }
  19329. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19330. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19331. }
  19332. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19333. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19334. }
  19335. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19336. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19337. }
  19338. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19339. // The body follows once `100 Continue` has had time to arrive.
  19340. auto req = expect_headers_only("/reader-used");
  19341. req.insert(req.size() - 2, "Connection: close\r\n");
  19342. std::string resp;
  19343. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19344. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19345. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19346. EXPECT_NE(std::string::npos, resp.find("hi"));
  19347. }
  19348. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19349. // Large enough for the client to add `Expect: 100-continue` itself.
  19350. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19351. std::atomic<bool> body_sent{false};
  19352. Client cli(HOST, port_);
  19353. auto res = cli.Post(
  19354. "/pre-request", length,
  19355. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19356. body_sent = true;
  19357. std::string chunk(len, 'x');
  19358. sink.write(chunk.data(), chunk.size());
  19359. return true;
  19360. },
  19361. "application/octet-stream");
  19362. ASSERT_TRUE(res);
  19363. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19364. EXPECT_FALSE(body_sent);
  19365. }
  19366. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19367. Server svr;
  19368. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19369. return StatusCode::ExpectationFailed_417;
  19370. });
  19371. svr.Post("/p", [](const Request &, Response &res) {
  19372. res.set_content("ok", "text/plain");
  19373. });
  19374. auto port = svr.bind_to_any_port(HOST);
  19375. thread t = thread([&] { svr.listen_after_bind(); });
  19376. auto se = detail::scope_exit([&] {
  19377. svr.stop();
  19378. t.join();
  19379. });
  19380. svr.wait_until_ready();
  19381. std::string resp;
  19382. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19383. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19384. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19385. // Exactly one response: the route handler must not run after the 417.
  19386. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19387. }
  19388. #ifndef _WIN32
  19389. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19390. static constexpr char reject[] = "Unauthorized";
  19391. static constexpr char accept[] = "Upload accepted";
  19392. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19393. Server svr;
  19394. svr.set_expect_100_continue_handler(
  19395. [](const Request & /*req*/, Response &res) {
  19396. res.status = StatusCode::Unauthorized_401;
  19397. res.set_content(reject, "text/plain");
  19398. return res.status;
  19399. });
  19400. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19401. res.set_content(accept, "text/plain");
  19402. });
  19403. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19404. auto se = detail::scope_exit([&] {
  19405. svr.stop();
  19406. thread.join();
  19407. ASSERT_FALSE(svr.is_running());
  19408. });
  19409. svr.wait_until_ready();
  19410. {
  19411. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19412. curl_easy_init(), &curl_easy_cleanup};
  19413. ASSERT_NE(curl, nullptr);
  19414. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19415. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19416. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19417. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19418. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19419. &curl_slist_free_all};
  19420. ASSERT_NE(list, nullptr);
  19421. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19422. struct read_data {
  19423. uint64_t read_size;
  19424. uint64_t total_size;
  19425. } data = {0, total_size};
  19426. using read_callback_t =
  19427. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19428. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19429. void *userdata) -> size_t {
  19430. read_data *d = (read_data *)userdata;
  19431. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19432. std::fill_n(ptr, size * nmemb, 'A');
  19433. d->read_size += size * nmemb;
  19434. return size * nmemb;
  19435. };
  19436. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19437. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19438. std::vector<char> buffer;
  19439. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19440. using write_callback_t =
  19441. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19442. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19443. void *userdata) -> size_t {
  19444. std::vector<char> *buf = (std::vector<char> *)userdata;
  19445. buf->reserve(buf->size() + size * nmemb + 1);
  19446. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19447. return size * nmemb;
  19448. };
  19449. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19450. {
  19451. const auto res = curl_easy_perform(curl.get());
  19452. ASSERT_EQ(res, CURLE_OK);
  19453. }
  19454. {
  19455. auto response_code = long{};
  19456. const auto res =
  19457. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19458. ASSERT_EQ(res, CURLE_OK);
  19459. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19460. }
  19461. {
  19462. auto dl = curl_off_t{};
  19463. const auto res =
  19464. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19465. ASSERT_EQ(res, CURLE_OK);
  19466. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19467. }
  19468. {
  19469. buffer.push_back('\0');
  19470. ASSERT_STRCASEEQ(buffer.data(), reject);
  19471. }
  19472. }
  19473. }
  19474. #endif
  19475. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19476. // Regression test for #2458.
  19477. //
  19478. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19479. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19480. // ticket can make the client socket spuriously readable during the
  19481. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19482. // the client withholds the body and then blocks reading a response that never
  19483. // comes, failing with `Failed to read connection`.
  19484. //
  19485. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19486. // within the timeout. This raw OpenSSL server deliberately never sends
  19487. // `100 Continue`; the client must still deliver the body and receive 200.
  19488. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19489. signal(SIGPIPE, SIG_IGN);
  19490. const auto port = PORT + 4;
  19491. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19492. ASSERT_NE(srv, INVALID_SOCKET);
  19493. int opt = 1;
  19494. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19495. sockaddr_in addr{};
  19496. addr.sin_family = AF_INET;
  19497. addr.sin_port = htons(static_cast<uint16_t>(port));
  19498. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19499. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19500. ASSERT_EQ(0, ::listen(srv, 1));
  19501. std::atomic<size_t> server_body_bytes{0};
  19502. auto server_thread = std::thread([&] {
  19503. sockaddr_in cli_addr{};
  19504. socklen_t cli_len = sizeof(cli_addr);
  19505. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19506. if (cli == INVALID_SOCKET) { return; }
  19507. // Bound the lifetime of the server side so a buggy client (which never
  19508. // sends the body) cannot make this thread block forever on join.
  19509. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19510. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19511. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19512. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19513. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19514. SSL *ssl = SSL_new(ctx);
  19515. SSL_set_fd(ssl, static_cast<int>(cli));
  19516. if (SSL_accept(ssl) > 0) {
  19517. // Read the request headers. Reading here also flushes the TLS 1.3
  19518. // session tickets to the client. Deliberately do NOT send
  19519. // `100 Continue`.
  19520. std::string buf;
  19521. char tmp[1024];
  19522. while (buf.find("\r\n\r\n") == std::string::npos) {
  19523. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19524. if (n <= 0) { break; }
  19525. buf.append(tmp, static_cast<size_t>(n));
  19526. }
  19527. // A correct client sends the body now; count what arrives.
  19528. auto pos = buf.find("\r\n\r\n");
  19529. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19530. while (body < 4096) {
  19531. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19532. if (n <= 0) { break; }
  19533. body += static_cast<size_t>(n);
  19534. }
  19535. server_body_bytes = body;
  19536. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19537. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19538. SSL_shutdown(ssl);
  19539. }
  19540. SSL_free(ssl);
  19541. detail::close_socket(cli);
  19542. SSL_CTX_free(ctx);
  19543. });
  19544. auto se = detail::scope_exit([&] {
  19545. server_thread.join();
  19546. detail::close_socket(srv);
  19547. });
  19548. SSLClient cli("127.0.0.1", port);
  19549. cli.enable_server_certificate_verification(false);
  19550. cli.set_connection_timeout(5, 0);
  19551. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19552. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19553. std::string body(4096, 'A');
  19554. auto res = cli.Put("/api/test", body, "application/json");
  19555. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19556. EXPECT_EQ(StatusCode::OK_200, res->status);
  19557. EXPECT_EQ(body.size(), server_body_bytes.load());
  19558. }
  19559. #endif
  19560. template <typename S, typename C>
  19561. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19562. svr.Get("/stream", [&](const Request &, Response &res) {
  19563. auto data = new std::string("01234567890123456789");
  19564. res.set_content_provider(
  19565. data->size(), "text/plain",
  19566. [&, data](size_t offset, size_t length, DataSink &sink) {
  19567. const size_t DATA_CHUNK_SIZE = 4;
  19568. const auto &d = *data;
  19569. std::this_thread::sleep_for(std::chrono::seconds(1));
  19570. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19571. return true;
  19572. },
  19573. [data](bool success) {
  19574. EXPECT_FALSE(success);
  19575. delete data;
  19576. });
  19577. });
  19578. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19579. auto i = new size_t(0);
  19580. res.set_content_provider(
  19581. "text/plain",
  19582. [i](size_t, DataSink &sink) {
  19583. if (*i < 5) {
  19584. std::this_thread::sleep_for(std::chrono::seconds(1));
  19585. sink.write("abcd", 4);
  19586. (*i)++;
  19587. } else {
  19588. sink.done();
  19589. }
  19590. return true;
  19591. },
  19592. [i](bool success) {
  19593. EXPECT_FALSE(success);
  19594. delete i;
  19595. });
  19596. });
  19597. svr.Get("/chunked", [&](const Request &, Response &res) {
  19598. auto i = new size_t(0);
  19599. res.set_chunked_content_provider(
  19600. "text/plain",
  19601. [i](size_t, DataSink &sink) {
  19602. if (*i < 5) {
  19603. std::this_thread::sleep_for(std::chrono::seconds(1));
  19604. sink.os << "abcd";
  19605. (*i)++;
  19606. } else {
  19607. sink.done();
  19608. }
  19609. return true;
  19610. },
  19611. [i](bool success) {
  19612. EXPECT_FALSE(success);
  19613. delete i;
  19614. });
  19615. });
  19616. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19617. auto se = detail::scope_exit([&] {
  19618. svr.stop();
  19619. listen_thread.join();
  19620. ASSERT_FALSE(svr.is_running());
  19621. });
  19622. svr.wait_until_ready();
  19623. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19624. {
  19625. auto start = std::chrono::steady_clock::now();
  19626. auto res = cli.Get("/stream");
  19627. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19628. std::chrono::steady_clock::now() - start)
  19629. .count();
  19630. ASSERT_FALSE(res);
  19631. EXPECT_EQ(Error::Read, res.error());
  19632. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19633. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19634. }
  19635. {
  19636. auto start = std::chrono::steady_clock::now();
  19637. auto res = cli.Get("/stream_without_length");
  19638. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19639. std::chrono::steady_clock::now() - start)
  19640. .count();
  19641. ASSERT_FALSE(res);
  19642. EXPECT_EQ(Error::Read, res.error());
  19643. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19644. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19645. }
  19646. {
  19647. auto start = std::chrono::steady_clock::now();
  19648. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19649. EXPECT_EQ("abcd", string(data, data_length));
  19650. return true;
  19651. });
  19652. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19653. std::chrono::steady_clock::now() - start)
  19654. .count();
  19655. ASSERT_FALSE(res);
  19656. EXPECT_EQ(Error::Read, res.error());
  19657. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19658. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19659. }
  19660. }
  19661. TEST(MaxTimeoutTest, ContentStream) {
  19662. time_t timeout = 2000;
  19663. time_t threshold = 200;
  19664. Server svr;
  19665. Client cli("localhost", PORT);
  19666. max_timeout_test(svr, cli, timeout, threshold);
  19667. }
  19668. #ifdef CPPHTTPLIB_SSL_ENABLED
  19669. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19670. time_t timeout = 2000;
  19671. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19673. SSLClient cli("localhost", PORT);
  19674. cli.enable_server_certificate_verification(false);
  19675. max_timeout_test(svr, cli, timeout, threshold);
  19676. }
  19677. #endif
  19678. class EventDispatcher {
  19679. public:
  19680. EventDispatcher() {}
  19681. bool wait_event(DataSink *sink) {
  19682. unique_lock<mutex> lk(m_);
  19683. int id = id_;
  19684. // Wait with timeout to prevent hanging if client disconnects
  19685. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19686. [&] { return cid_ == id; })) {
  19687. return false; // Timeout occurred
  19688. }
  19689. sink->write(message_.data(), message_.size());
  19690. return true;
  19691. }
  19692. void send_event(const string &message) {
  19693. lock_guard<mutex> lk(m_);
  19694. cid_ = id_++;
  19695. message_ = message;
  19696. cv_.notify_all();
  19697. }
  19698. private:
  19699. mutex m_;
  19700. condition_variable cv_;
  19701. atomic_int id_{0};
  19702. atomic_int cid_{-1};
  19703. string message_;
  19704. };
  19705. TEST(ClientInThreadTest, Issue2068) {
  19706. EventDispatcher ed;
  19707. Server svr;
  19708. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19709. res.set_chunked_content_provider("text/event-stream",
  19710. [&](size_t /*offset*/, DataSink &sink) {
  19711. return ed.wait_event(&sink);
  19712. });
  19713. });
  19714. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19715. svr.wait_until_ready();
  19716. thread event_thread([&] {
  19717. int id = 0;
  19718. while (svr.is_running()) {
  19719. this_thread::sleep_for(chrono::milliseconds(500));
  19720. std::stringstream ss;
  19721. ss << "data: " << id << "\n\n";
  19722. ed.send_event(ss.str());
  19723. id++;
  19724. }
  19725. });
  19726. auto se = detail::scope_exit([&] {
  19727. svr.stop();
  19728. listen_thread.join();
  19729. event_thread.join();
  19730. ASSERT_FALSE(svr.is_running());
  19731. });
  19732. {
  19733. auto client = detail::make_unique<Client>(HOST, PORT);
  19734. client->set_read_timeout(std::chrono::minutes(10));
  19735. std::atomic<bool> stop{false};
  19736. std::thread t([&] {
  19737. client->Get("/event1",
  19738. [&](const char *, size_t) -> bool { return !stop; });
  19739. });
  19740. std::this_thread::sleep_for(std::chrono::seconds(2));
  19741. stop = true;
  19742. client->stop();
  19743. t.join();
  19744. // Reset client after thread has finished
  19745. client.reset();
  19746. }
  19747. }
  19748. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19749. auto handled = false;
  19750. Server svr;
  19751. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19752. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19753. auto se = detail::scope_exit([&] {
  19754. svr.stop();
  19755. t.join();
  19756. ASSERT_FALSE(svr.is_running());
  19757. ASSERT_FALSE(handled);
  19758. });
  19759. svr.wait_until_ready();
  19760. // Two Content-Length headers with different values — must be rejected
  19761. auto req = "POST /test HTTP/1.1\r\n"
  19762. "Content-Length: 5\r\n"
  19763. "Content-Length: 10\r\n"
  19764. "\r\n"
  19765. "hello";
  19766. std::string response;
  19767. ASSERT_TRUE(send_request(1, req, &response));
  19768. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19769. response.substr(0, response.find("\r\n")));
  19770. }
  19771. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19772. auto handled = false;
  19773. Server svr;
  19774. svr.Post("/test", [&](const Request &, Response &res) {
  19775. handled = true;
  19776. res.set_content("ok", "text/plain");
  19777. });
  19778. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19779. auto se = detail::scope_exit([&] {
  19780. svr.stop();
  19781. t.join();
  19782. ASSERT_FALSE(svr.is_running());
  19783. ASSERT_TRUE(handled);
  19784. });
  19785. svr.wait_until_ready();
  19786. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19787. auto req = "POST /test HTTP/1.1\r\n"
  19788. "Host: localhost\r\n"
  19789. "Content-Length: 5\r\n"
  19790. "Content-Length: 5\r\n"
  19791. "\r\n"
  19792. "hello";
  19793. std::string response;
  19794. ASSERT_TRUE(send_request(1, req, &response));
  19795. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19796. }
  19797. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19798. Server svr;
  19799. svr.Get("/test", [](const Request &, Response &res) {
  19800. res.set_content("ok", "text/plain");
  19801. });
  19802. auto port = svr.bind_to_any_port(HOST);
  19803. thread t = thread([&] { svr.listen_after_bind(); });
  19804. auto se = detail::scope_exit([&] {
  19805. svr.stop();
  19806. t.join();
  19807. ASSERT_FALSE(svr.is_running());
  19808. });
  19809. svr.wait_until_ready();
  19810. auto status_line = [&](const std::string &host_lines) {
  19811. std::string res;
  19812. send_request(
  19813. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19814. &res, port);
  19815. return res.substr(0, res.find("\r\n"));
  19816. };
  19817. const char *accepted[] = {
  19818. "Host: localhost\r\n",
  19819. "Host: a.example:8080\r\n",
  19820. "Host: my_service\r\n",
  19821. "Host: [::1]:8080\r\n",
  19822. "Host: [fe80::1%25eth0]\r\n",
  19823. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19824. };
  19825. for (auto host_lines : accepted) {
  19826. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19827. }
  19828. const char *rejected[] = {
  19829. "Host: a.example\r\nHost: b.example\r\n",
  19830. "Host: a.example\r\nHost: a.example\r\n",
  19831. "Host: a@b.example\r\n",
  19832. "Host: a.example/b\r\n",
  19833. "Host: a.example\\b\r\n",
  19834. "Host: a.example?b\r\n",
  19835. "Host: a.example#b\r\n",
  19836. "Host: a.example b.example\r\n",
  19837. };
  19838. for (auto host_lines : rejected) {
  19839. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19840. << host_lines;
  19841. }
  19842. }
  19843. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19844. Server svr;
  19845. svr.Get("/", [](const Request &req, Response &res) {
  19846. EXPECT_EQ(2U, req.trailers.size());
  19847. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19848. // Denied
  19849. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19850. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19851. // Accepted
  19852. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19853. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19854. EXPECT_TRUE(req.has_trailer("X-World"));
  19855. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19856. res.set_content("ok", "text/plain");
  19857. });
  19858. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19859. auto se = detail::scope_exit([&] {
  19860. svr.stop();
  19861. t.join();
  19862. ASSERT_FALSE(svr.is_running());
  19863. });
  19864. svr.wait_until_ready();
  19865. const std::string req = "GET / HTTP/1.1\r\n"
  19866. "Transfer-Encoding: chunked\r\n"
  19867. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19868. "\r\n"
  19869. "0\r\n"
  19870. "Content-Length: 10\r\n"
  19871. "Host: internal.local\r\n"
  19872. "Content-Type: malicious/content\r\n"
  19873. "Cookie: any\r\n"
  19874. "Set-Cookie: any\r\n"
  19875. "X-Forwarded-For: attacker.com\r\n"
  19876. "X-Real-Ip: 1.1.1.1\r\n"
  19877. "X-Hello: hello\r\n"
  19878. "X-World: world\r\n"
  19879. "\r\n";
  19880. std::string res;
  19881. ASSERT_TRUE(send_request(1, req, &res));
  19882. }
  19883. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19884. // several field lines, and the combined value is what has to be parsed. A
  19885. // Trailer field split across lines therefore declares every name it lists;
  19886. // reading only the first line silently drops the trailers the later lines
  19887. // declare. The prohibited-trailer filter still applies to every line.
  19888. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19889. Server svr;
  19890. size_t observed_trailer_count = 0;
  19891. std::string observed_hello;
  19892. std::string observed_world;
  19893. bool observed_content_length = true;
  19894. svr.Get("/", [&](const Request &req, Response &res) {
  19895. observed_trailer_count = req.trailers.size();
  19896. observed_hello = req.get_trailer_value("X-Hello");
  19897. observed_world = req.get_trailer_value("X-World");
  19898. observed_content_length = req.has_trailer("Content-Length");
  19899. res.set_content("ok", "text/plain");
  19900. });
  19901. auto port = svr.bind_to_any_port(HOST);
  19902. thread t = thread([&]() { svr.listen_after_bind(); });
  19903. auto se = detail::scope_exit([&] {
  19904. svr.stop();
  19905. t.join();
  19906. ASSERT_FALSE(svr.is_running());
  19907. });
  19908. svr.wait_until_ready();
  19909. const std::string req = "GET / HTTP/1.1\r\n"
  19910. "Host: localhost\r\n"
  19911. "Transfer-Encoding: chunked\r\n"
  19912. "Trailer: X-Hello\r\n"
  19913. "Trailer: X-World, Content-Length\r\n"
  19914. "\r\n"
  19915. "0\r\n"
  19916. "X-Hello: hello\r\n"
  19917. "X-World: world\r\n"
  19918. "Content-Length: 10\r\n"
  19919. "\r\n";
  19920. std::string res;
  19921. ASSERT_TRUE(send_request(1, req, &res, port));
  19922. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19923. // Accepted: both field lines contribute to the declared set
  19924. EXPECT_EQ(2U, observed_trailer_count);
  19925. EXPECT_EQ(observed_hello, "hello");
  19926. EXPECT_EQ(observed_world, "world");
  19927. // Denied: a prohibited name stays prohibited on a later field line
  19928. EXPECT_FALSE(observed_content_length);
  19929. }
  19930. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19931. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19932. // unbounded run of fields that are never declared, because the counter would
  19933. // only advance for declared fields.
  19934. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19935. Server svr;
  19936. bool handler_called = false;
  19937. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19938. handler_called = true;
  19939. res.set_content("ok", "text/plain");
  19940. });
  19941. auto port = svr.bind_to_any_port(HOST);
  19942. thread t = thread([&]() { svr.listen_after_bind(); });
  19943. auto se = detail::scope_exit([&] {
  19944. svr.stop();
  19945. t.join();
  19946. ASSERT_FALSE(svr.is_running());
  19947. });
  19948. svr.wait_until_ready();
  19949. // Declare nothing, then send far more undeclared trailer fields than the
  19950. // header-count limit. Parsing must stop and reject the request rather than
  19951. // read every line.
  19952. std::string req = "GET / HTTP/1.1\r\n"
  19953. "Transfer-Encoding: chunked\r\n"
  19954. "\r\n"
  19955. "0\r\n";
  19956. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19957. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19958. }
  19959. req += "\r\n";
  19960. std::string res;
  19961. ASSERT_TRUE(send_request(1, req, &res, port));
  19962. // The request is rejected before the handler runs.
  19963. EXPECT_FALSE(handler_called);
  19964. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19965. }
  19966. // The set of declared trailer names is capped so a peer cannot grow it without
  19967. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  19968. // declared past the cap is not honored, even if the field is actually sent.
  19969. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  19970. Server svr;
  19971. // One name inside the cap and one past it, so the test tracks the cap rather
  19972. // than a fixed count.
  19973. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  19974. const std::string within_cap_name = "X-T-0";
  19975. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  19976. bool observed_within_cap = false;
  19977. bool observed_past_cap = false;
  19978. svr.Get("/", [&](const Request &req, Response &res) {
  19979. observed_within_cap = req.has_trailer(within_cap_name);
  19980. observed_past_cap = req.has_trailer(past_cap_name);
  19981. res.set_content("ok", "text/plain");
  19982. });
  19983. auto port = svr.bind_to_any_port(HOST);
  19984. thread t = thread([&]() { svr.listen_after_bind(); });
  19985. auto se = detail::scope_exit([&] {
  19986. svr.stop();
  19987. t.join();
  19988. ASSERT_FALSE(svr.is_running());
  19989. });
  19990. svr.wait_until_ready();
  19991. // Declare more trailer names than the cap in a single Trailer field, then
  19992. // actually send the first (within the cap) and the last (past it).
  19993. std::string trailer_decl = "Trailer: ";
  19994. for (int i = 0; i < declared_count; i++) {
  19995. if (i != 0) { trailer_decl += ", "; }
  19996. trailer_decl += "X-T-" + std::to_string(i);
  19997. }
  19998. trailer_decl += "\r\n";
  19999. const std::string req = "GET / HTTP/1.1\r\n"
  20000. "Host: localhost\r\n"
  20001. "Transfer-Encoding: chunked\r\n" +
  20002. trailer_decl +
  20003. "\r\n"
  20004. "0\r\n" +
  20005. within_cap_name + ": a\r\n" + past_cap_name +
  20006. ": b\r\n"
  20007. "\r\n";
  20008. std::string res;
  20009. ASSERT_TRUE(send_request(1, req, &res, port));
  20010. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  20011. // A name within the cap is honored; one declared past the cap is dropped.
  20012. EXPECT_TRUE(observed_within_cap);
  20013. EXPECT_FALSE(observed_past_cap);
  20014. }
  20015. // A direct client that is not listed in trusted_proxies must not be able to
  20016. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20017. // the peer address on the actual TCP connection determines whether the
  20018. // header is honored.
  20019. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20020. Server svr;
  20021. // Deliberately does NOT include the loopback address the test client
  20022. // actually connects from, so the direct connection is not a trusted proxy.
  20023. svr.set_trusted_proxies({"203.0.113.66"});
  20024. std::string observed_remote_addr;
  20025. svr.Get("/ip", [&](const Request &req, Response &res) {
  20026. observed_remote_addr = req.remote_addr;
  20027. res.set_content("ok", "text/plain");
  20028. });
  20029. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20030. auto se = detail::scope_exit([&] {
  20031. svr.stop();
  20032. t.join();
  20033. ASSERT_FALSE(svr.is_running());
  20034. });
  20035. svr.wait_until_ready();
  20036. Client cli(HOST, PORT);
  20037. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20039. EXPECT_EQ(StatusCode::OK_200, res->status);
  20040. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20041. // ignored entirely and the real connection-level address retained.
  20042. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20043. observed_remote_addr == "127.0.0.1");
  20044. }
  20045. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20046. Server svr;
  20047. std::string observed_remote_addr;
  20048. std::string observed_xff;
  20049. svr.Get("/ip", [&](const Request &req, Response &res) {
  20050. observed_remote_addr = req.remote_addr;
  20051. observed_xff = req.get_header_value("X-Forwarded-For");
  20052. res.set_content("ok", "text/plain");
  20053. });
  20054. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20055. auto se = detail::scope_exit([&] {
  20056. svr.stop();
  20057. t.join();
  20058. ASSERT_FALSE(svr.is_running());
  20059. });
  20060. svr.wait_until_ready();
  20061. Client cli(HOST, PORT);
  20062. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20064. EXPECT_EQ(StatusCode::OK_200, res->status);
  20065. EXPECT_EQ(observed_xff, "203.0.113.66");
  20066. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20067. observed_remote_addr == "127.0.0.1");
  20068. }
  20069. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20070. Server svr;
  20071. svr.set_trusted_proxies({"203.0.113.66"});
  20072. std::string observed_remote_addr;
  20073. std::string observed_xff;
  20074. svr.Get("/ip", [&](const Request &req, Response &res) {
  20075. observed_remote_addr = req.remote_addr;
  20076. observed_xff = req.get_header_value("X-Forwarded-For");
  20077. res.set_content("ok", "text/plain");
  20078. });
  20079. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20080. auto se = detail::scope_exit([&] {
  20081. svr.stop();
  20082. t.join();
  20083. ASSERT_FALSE(svr.is_running());
  20084. });
  20085. svr.wait_until_ready();
  20086. Client cli(HOST, PORT);
  20087. auto res = cli.Get("/ip");
  20088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20089. EXPECT_EQ(StatusCode::OK_200, res->status);
  20090. EXPECT_EQ(observed_xff, "");
  20091. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20092. observed_remote_addr == "127.0.0.1");
  20093. }
  20094. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20095. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20096. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20097. Server svr;
  20098. svr.set_trusted_proxies({"127.0.0.1"});
  20099. svr.Get("/ip", [](const Request &req, Response &res) {
  20100. res.set_content(req.remote_addr, "text/plain");
  20101. });
  20102. auto port = svr.bind_to_any_port("::");
  20103. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20104. thread t = thread([&] { svr.listen_after_bind(); });
  20105. auto se = detail::scope_exit([&] {
  20106. svr.stop();
  20107. t.join();
  20108. ASSERT_FALSE(svr.is_running());
  20109. });
  20110. svr.wait_until_ready();
  20111. Client cli("127.0.0.1", port);
  20112. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20114. EXPECT_EQ("198.51.100.23", res->body);
  20115. }
  20116. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20117. Server svr;
  20118. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20119. svr.Get("/ip", [](const Request &req, Response &res) {
  20120. res.set_content(req.remote_addr, "text/plain");
  20121. });
  20122. auto port = svr.bind_to_any_port(HOST);
  20123. ASSERT_GT(port, 0);
  20124. thread t = thread([&] { svr.listen_after_bind(); });
  20125. auto se = detail::scope_exit([&] {
  20126. svr.stop();
  20127. t.join();
  20128. ASSERT_FALSE(svr.is_running());
  20129. });
  20130. svr.wait_until_ready();
  20131. Client cli(HOST, port);
  20132. auto res = cli.Get(
  20133. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20135. EXPECT_EQ("198.51.100.23", res->body);
  20136. }
  20137. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20138. Server svr;
  20139. // Include the loopback address the test client actually connects from, so
  20140. // the direct connection itself is recognized as the trusted proxy hop.
  20141. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20142. std::string observed_remote_addr;
  20143. std::string observed_xff;
  20144. svr.Get("/ip", [&](const Request &req, Response &res) {
  20145. observed_remote_addr = req.remote_addr;
  20146. observed_xff = req.get_header_value("X-Forwarded-For");
  20147. res.set_content("ok", "text/plain");
  20148. });
  20149. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20150. auto se = detail::scope_exit([&] {
  20151. svr.stop();
  20152. t.join();
  20153. ASSERT_FALSE(svr.is_running());
  20154. });
  20155. svr.wait_until_ready();
  20156. Client cli(HOST, PORT);
  20157. auto res = cli.Get(
  20158. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20159. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20160. EXPECT_EQ(StatusCode::OK_200, res->status);
  20161. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20162. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20163. }
  20164. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20165. Server svr;
  20166. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20167. std::string observed_remote_addr;
  20168. std::string observed_xff;
  20169. svr.Get("/ip", [&](const Request &req, Response &res) {
  20170. observed_remote_addr = req.remote_addr;
  20171. observed_xff = req.get_header_value("X-Forwarded-For");
  20172. res.set_content("ok", "text/plain");
  20173. });
  20174. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20175. auto se = detail::scope_exit([&] {
  20176. svr.stop();
  20177. t.join();
  20178. ASSERT_FALSE(svr.is_running());
  20179. });
  20180. svr.wait_until_ready();
  20181. Client cli(HOST, PORT);
  20182. auto res = cli.Get(
  20183. "/ip",
  20184. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20185. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20186. EXPECT_EQ(StatusCode::OK_200, res->status);
  20187. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20188. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20189. }
  20190. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20191. Server svr;
  20192. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20193. std::string observed_remote_addr;
  20194. std::string observed_xff;
  20195. svr.Get("/ip", [&](const Request &req, Response &res) {
  20196. observed_remote_addr = req.remote_addr;
  20197. observed_xff = req.get_header_value("X-Forwarded-For");
  20198. res.set_content("ok", "text/plain");
  20199. });
  20200. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20201. auto se = detail::scope_exit([&] {
  20202. svr.stop();
  20203. t.join();
  20204. ASSERT_FALSE(svr.is_running());
  20205. });
  20206. svr.wait_until_ready();
  20207. Client cli(HOST, PORT);
  20208. auto res = cli.Get(
  20209. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20211. EXPECT_EQ(StatusCode::OK_200, res->status);
  20212. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20213. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20214. // and must not be selected.
  20215. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20216. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20217. }
  20218. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20219. Server svr;
  20220. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20221. std::string observed_remote_addr;
  20222. svr.Get("/ip", [&](const Request &req, Response &res) {
  20223. observed_remote_addr = req.remote_addr;
  20224. res.set_content("ok", "text/plain");
  20225. });
  20226. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20227. auto se = detail::scope_exit([&] {
  20228. svr.stop();
  20229. t.join();
  20230. ASSERT_FALSE(svr.is_running());
  20231. });
  20232. svr.wait_until_ready();
  20233. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20234. // a forged address and the trusted proxy's own address; the forged value must
  20235. // not win over the address the trusted proxy actually recorded.
  20236. Client cli(HOST, PORT);
  20237. auto res = cli.Get(
  20238. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20240. EXPECT_EQ(StatusCode::OK_200, res->status);
  20241. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20242. }
  20243. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20244. Server svr;
  20245. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20246. std::string observed_remote_addr;
  20247. std::string observed_xff;
  20248. svr.Get("/ip", [&](const Request &req, Response &res) {
  20249. observed_remote_addr = req.remote_addr;
  20250. observed_xff = req.get_header_value("X-Forwarded-For");
  20251. res.set_content("ok", "text/plain");
  20252. });
  20253. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20254. auto se = detail::scope_exit([&] {
  20255. svr.stop();
  20256. t.join();
  20257. ASSERT_FALSE(svr.is_running());
  20258. });
  20259. svr.wait_until_ready();
  20260. Client cli(HOST, PORT);
  20261. auto res = cli.Get(
  20262. "/ip",
  20263. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20265. EXPECT_EQ(StatusCode::OK_200, res->status);
  20266. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20267. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20268. }
  20269. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20270. Server svr;
  20271. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20272. std::string observed_remote_addr;
  20273. std::string observed_xff;
  20274. svr.Get("/ip", [&](const Request &req, Response &res) {
  20275. observed_remote_addr = req.remote_addr;
  20276. observed_xff = req.get_header_value("X-Forwarded-For");
  20277. res.set_content("ok", "text/plain");
  20278. });
  20279. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20280. auto se = detail::scope_exit([&] {
  20281. svr.stop();
  20282. t.join();
  20283. ASSERT_FALSE(svr.is_running());
  20284. });
  20285. svr.wait_until_ready();
  20286. std::string raw_req =
  20287. "GET /ip HTTP/1.1\r\n"
  20288. "Host: localhost\r\n"
  20289. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20290. "Connection: close\r\n"
  20291. "\r\n";
  20292. std::string out;
  20293. ASSERT_TRUE(send_request(5, raw_req, &out));
  20294. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20295. // Header parser trims surrounding whitespace of the header value
  20296. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20297. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20298. }
  20299. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20300. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20301. // their own X-Forwarded-For as a separate field line rather than extending the
  20302. // one the client sent, so every occurrence has to be taken into account.
  20303. // Reading only the first one hands back the address the client chose.
  20304. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20305. Server svr;
  20306. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20307. std::string observed_remote_addr;
  20308. size_t observed_xff_count = 0;
  20309. svr.Get("/ip", [&](const Request &req, Response &res) {
  20310. observed_remote_addr = req.remote_addr;
  20311. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20312. res.set_content("ok", "text/plain");
  20313. });
  20314. auto port = svr.bind_to_any_port(HOST);
  20315. thread t = thread([&]() { svr.listen_after_bind(); });
  20316. auto se = detail::scope_exit([&] {
  20317. svr.stop();
  20318. t.join();
  20319. ASSERT_FALSE(svr.is_running());
  20320. });
  20321. svr.wait_until_ready();
  20322. // The client supplies the first field line; the trusted proxy appends the
  20323. // address it observed as a second one.
  20324. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20325. "Host: localhost\r\n"
  20326. "X-Forwarded-For: 1.2.3.4\r\n"
  20327. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20328. "Connection: close\r\n"
  20329. "\r\n";
  20330. std::string out;
  20331. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20332. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20333. EXPECT_EQ(observed_xff_count, 2U);
  20334. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20335. // The same chain spread over one field line per hop derives the same client
  20336. // address, i.e. the split and the comma-joined representations agree.
  20337. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20338. "Host: localhost\r\n"
  20339. "X-Forwarded-For: 1.2.3.4\r\n"
  20340. "X-Forwarded-For: 198.51.100.23\r\n"
  20341. "X-Forwarded-For: 192.0.2.45\r\n"
  20342. "Connection: close\r\n"
  20343. "\r\n";
  20344. out.clear();
  20345. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20346. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20347. EXPECT_EQ(observed_xff_count, 3U);
  20348. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20349. }
  20350. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20351. // crash the server (it used to call front() on an empty vector inside
  20352. // get_client_ip). The connection-level remote address must be retained instead.
  20353. static void run_malformed_xff_test(const std::string &xff_value) {
  20354. Server svr;
  20355. svr.set_trusted_proxies({"192.0.2.45"});
  20356. std::string observed_remote_addr;
  20357. svr.Get("/ip", [&](const Request &req, Response &res) {
  20358. observed_remote_addr = req.remote_addr;
  20359. res.set_content("ok", "text/plain");
  20360. });
  20361. int port = 0;
  20362. thread t = thread([&]() {
  20363. port = svr.bind_to_any_port(HOST);
  20364. svr.listen_after_bind();
  20365. });
  20366. auto se = detail::scope_exit([&] {
  20367. svr.stop();
  20368. t.join();
  20369. ASSERT_FALSE(svr.is_running());
  20370. });
  20371. svr.wait_until_ready();
  20372. Client cli(HOST, port);
  20373. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20374. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20375. EXPECT_EQ(StatusCode::OK_200, res->status);
  20376. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20377. observed_remote_addr == "127.0.0.1");
  20378. }
  20379. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20380. run_malformed_xff_test("");
  20381. }
  20382. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20383. run_malformed_xff_test(",");
  20384. }
  20385. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20386. run_malformed_xff_test(", , ,");
  20387. }
  20388. // The same rule applies to Accept: a request whose acceptable types are spread
  20389. // over several field lines must be negotiated against all of them.
  20390. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20391. // case-insensitive connection options. Comparing the whole field value against
  20392. // one option misses a client that sends several of them, and misses every
  20393. // casing but the one written in the comparison.
  20394. //
  20395. // Sends req, reads the response, then reuses the same socket for a second
  20396. // request to find out whether the server kept the connection.
  20397. static void probe_connection_reuse(int port, const std::string &req,
  20398. bool *announced_close, bool *reusable) {
  20399. auto error = Error::Success;
  20400. auto sock = detail::create_client_socket(
  20401. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20402. /*connection_timeout_sec=*/5, 0,
  20403. /*read_timeout_sec=*/1, 0,
  20404. /*write_timeout_sec=*/5, 0, std::string(), error);
  20405. ASSERT_NE(sock, INVALID_SOCKET);
  20406. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20407. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20408. "Host: localhost\r\n"
  20409. "Connection: close\r\n"
  20410. "\r\n";
  20411. std::string first_response;
  20412. std::string second_response;
  20413. detail::process_client_socket(
  20414. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20415. [&](Stream &strm) {
  20416. if (strm.write(req.data(), req.size()) !=
  20417. static_cast<ssize_t>(req.size())) {
  20418. return false;
  20419. }
  20420. char buf[512];
  20421. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20422. // Headers plus the two-byte body of the handler below
  20423. while (reader.getline()) {
  20424. first_response += reader.ptr();
  20425. if (first_response.find("ok") != std::string::npos) { break; }
  20426. }
  20427. if (strm.write(second.data(), second.size()) !=
  20428. static_cast<ssize_t>(second.size())) {
  20429. return true;
  20430. }
  20431. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20432. while (reader2.getline()) {
  20433. second_response += reader2.ptr();
  20434. if (second_response.find("ok") != std::string::npos) { break; }
  20435. }
  20436. return true;
  20437. });
  20438. *announced_close =
  20439. first_response.find("Connection: close") != std::string::npos;
  20440. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20441. }
  20442. class ConnectionTokenTest : public ::testing::Test {
  20443. protected:
  20444. void SetUp() override {
  20445. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20446. res.set_content("ok", "text/plain");
  20447. });
  20448. port_ = svr_.bind_to_any_port(HOST);
  20449. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20450. svr_.wait_until_ready();
  20451. }
  20452. void TearDown() override {
  20453. svr_.stop();
  20454. if (thread_.joinable()) { thread_.join(); }
  20455. }
  20456. Server svr_;
  20457. int port_ = 0;
  20458. thread thread_;
  20459. };
  20460. // "close" alongside another option still closes the connection, and the
  20461. // response says so rather than leaving the peer to discover it.
  20462. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20463. bool announced_close = false;
  20464. bool reusable = true;
  20465. probe_connection_reuse(port_,
  20466. "GET /keepalive HTTP/1.1\r\n"
  20467. "Host: localhost\r\n"
  20468. "Connection: keep-alive, close\r\n"
  20469. "\r\n",
  20470. &announced_close, &reusable);
  20471. EXPECT_TRUE(announced_close);
  20472. EXPECT_FALSE(reusable);
  20473. }
  20474. // "close" split over two field lines is the same list, so it is honored too.
  20475. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20476. bool announced_close = false;
  20477. bool reusable = true;
  20478. probe_connection_reuse(port_,
  20479. "GET /keepalive HTTP/1.1\r\n"
  20480. "Host: localhost\r\n"
  20481. "Connection: keep-alive\r\n"
  20482. "Connection: close\r\n"
  20483. "\r\n",
  20484. &announced_close, &reusable);
  20485. EXPECT_TRUE(announced_close);
  20486. EXPECT_FALSE(reusable);
  20487. }
  20488. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20489. // keep-alive in the spelling everyone actually sends keeps its connection.
  20490. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20491. bool announced_close = false;
  20492. bool reusable = false;
  20493. probe_connection_reuse(port_,
  20494. "GET /keepalive HTTP/1.0\r\n"
  20495. "Host: localhost\r\n"
  20496. "Connection: keep-alive\r\n"
  20497. "\r\n",
  20498. &announced_close, &reusable);
  20499. EXPECT_FALSE(announced_close);
  20500. EXPECT_TRUE(reusable);
  20501. }
  20502. // A token the value merely contains is not the token itself.
  20503. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20504. bool announced_close = false;
  20505. bool reusable = false;
  20506. probe_connection_reuse(port_,
  20507. "GET /keepalive HTTP/1.1\r\n"
  20508. "Host: localhost\r\n"
  20509. "Connection: notclose\r\n"
  20510. "\r\n",
  20511. &announced_close, &reusable);
  20512. EXPECT_FALSE(announced_close);
  20513. EXPECT_TRUE(reusable);
  20514. }
  20515. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20516. Server svr;
  20517. std::vector<std::string> observed_types;
  20518. svr.Get("/", [&](const Request &req, Response &res) {
  20519. observed_types = req.accept_content_types;
  20520. res.set_content("ok", "text/plain");
  20521. });
  20522. auto port = svr.bind_to_any_port(HOST);
  20523. thread t = thread([&]() { svr.listen_after_bind(); });
  20524. auto se = detail::scope_exit([&] {
  20525. svr.stop();
  20526. t.join();
  20527. ASSERT_FALSE(svr.is_running());
  20528. });
  20529. svr.wait_until_ready();
  20530. Client cli(HOST, port);
  20531. Headers headers;
  20532. headers.emplace("Accept", "text/plain;q=0.5");
  20533. headers.emplace("Accept", "application/json");
  20534. auto res = cli.Get("/", headers);
  20535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20536. EXPECT_EQ(StatusCode::OK_200, res->status);
  20537. // Sorted by q-value, so the second field line's type comes first
  20538. ASSERT_EQ(2U, observed_types.size());
  20539. EXPECT_EQ("application/json", observed_types[0]);
  20540. EXPECT_EQ("text/plain", observed_types[1]);
  20541. }
  20542. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20543. // empty field line must not contribute a bare comma to the combined value.
  20544. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20545. Server svr;
  20546. std::vector<std::string> observed_types;
  20547. svr.Get("/", [&](const Request &req, Response &res) {
  20548. observed_types = req.accept_content_types;
  20549. res.set_content("ok", "text/plain");
  20550. });
  20551. auto port = svr.bind_to_any_port(HOST);
  20552. thread t = thread([&]() { svr.listen_after_bind(); });
  20553. auto se = detail::scope_exit([&] {
  20554. svr.stop();
  20555. t.join();
  20556. ASSERT_FALSE(svr.is_running());
  20557. });
  20558. svr.wait_until_ready();
  20559. // Empty first field line, then a real one
  20560. std::string raw_req = "GET / HTTP/1.1\r\n"
  20561. "Host: localhost\r\n"
  20562. "Accept:\r\n"
  20563. "Accept: application/json\r\n"
  20564. "Connection: close\r\n"
  20565. "\r\n";
  20566. std::string out;
  20567. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20568. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20569. ASSERT_EQ(1U, observed_types.size());
  20570. EXPECT_EQ("application/json", observed_types[0]);
  20571. }
  20572. // The skip in get_combined_header_value() is what keeps an empty field line
  20573. // from contributing a bare comma. Only a trailing empty field line exercises
  20574. // it: a leading one is already covered by the "combined is still empty" check,
  20575. // and parse_accept_header() now ignores the empty element either way, so the
  20576. // request-level test above can no longer tell the two apart.
  20577. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20578. Headers headers;
  20579. headers.emplace("Accept", "text/html");
  20580. headers.emplace("Accept", "");
  20581. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20582. headers.clear();
  20583. headers.emplace("Accept", "");
  20584. headers.emplace("Accept", "application/json");
  20585. EXPECT_EQ("application/json",
  20586. detail::get_combined_header_value(headers, "Accept"));
  20587. }
  20588. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20589. // An encoding offered on a later Accept-Encoding field line is still offered.
  20590. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20591. Server svr;
  20592. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20593. res.set_content(std::string(1024, 'x'), "text/plain");
  20594. });
  20595. auto port = svr.bind_to_any_port(HOST);
  20596. thread t = thread([&]() { svr.listen_after_bind(); });
  20597. auto se = detail::scope_exit([&] {
  20598. svr.stop();
  20599. t.join();
  20600. ASSERT_FALSE(svr.is_running());
  20601. });
  20602. svr.wait_until_ready();
  20603. Client cli(HOST, port);
  20604. cli.set_decompress(false);
  20605. Headers headers;
  20606. headers.emplace("Accept-Encoding", "identity");
  20607. headers.emplace("Accept-Encoding", "gzip");
  20608. auto res = cli.Get("/", headers);
  20609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20610. EXPECT_EQ(StatusCode::OK_200, res->status);
  20611. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20612. }
  20613. #endif
  20614. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20615. // Transfer-Encoding is not its body.
  20616. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20617. Server svr;
  20618. svr.set_payload_max_length(8);
  20619. svr.Post("/test", [](const Request &, Response &res) {
  20620. res.set_content("ok", "text/plain");
  20621. });
  20622. auto port = svr.bind_to_any_port(HOST);
  20623. ASSERT_GT(port, 0);
  20624. thread t = thread([&] { svr.listen_after_bind(); });
  20625. auto se = detail::scope_exit([&] {
  20626. svr.stop();
  20627. t.join();
  20628. ASSERT_FALSE(svr.is_running());
  20629. });
  20630. svr.wait_until_ready();
  20631. std::string resp;
  20632. ASSERT_TRUE(send_request(1,
  20633. "POST /test HTTP/1.1\r\n"
  20634. "Host: localhost\r\n"
  20635. "Connection: close\r\n"
  20636. "\r\n" +
  20637. std::string(16, 'X'),
  20638. &resp, port));
  20639. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20640. }
  20641. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20642. Server svr;
  20643. svr.Post("/post", [&](const Request &req, Response &res) {
  20644. res.set_content(req.body, "text/plain");
  20645. });
  20646. svr.Put("/put", [&](const Request &req, Response &res) {
  20647. res.set_content(req.body, "text/plain");
  20648. });
  20649. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20650. res.set_content(req.body, "text/plain");
  20651. });
  20652. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20653. res.set_content(req.body, "text/plain");
  20654. });
  20655. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20656. auto se = detail::scope_exit([&] {
  20657. svr.stop();
  20658. t.join();
  20659. ASSERT_FALSE(svr.is_running());
  20660. });
  20661. svr.wait_until_ready();
  20662. std::string resp;
  20663. // POST without Content-Length
  20664. ASSERT_TRUE(send_request(5,
  20665. "POST /post HTTP/1.1\r\n"
  20666. "Host: localhost\r\n"
  20667. "Connection: close\r\n"
  20668. "\r\n",
  20669. &resp));
  20670. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20671. // PUT without Content-Length
  20672. resp.clear();
  20673. ASSERT_TRUE(send_request(5,
  20674. "PUT /put HTTP/1.1\r\n"
  20675. "Host: localhost\r\n"
  20676. "Connection: close\r\n"
  20677. "\r\n",
  20678. &resp));
  20679. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20680. // PATCH without Content-Length
  20681. resp.clear();
  20682. ASSERT_TRUE(send_request(5,
  20683. "PATCH /patch HTTP/1.1\r\n"
  20684. "Host: localhost\r\n"
  20685. "Connection: close\r\n"
  20686. "\r\n",
  20687. &resp));
  20688. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20689. // DELETE without Content-Length
  20690. resp.clear();
  20691. ASSERT_TRUE(send_request(5,
  20692. "DELETE /delete HTTP/1.1\r\n"
  20693. "Host: localhost\r\n"
  20694. "Connection: close\r\n"
  20695. "\r\n",
  20696. &resp));
  20697. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20698. }
  20699. //==============================================================================
  20700. // open_stream() Tests
  20701. //==============================================================================
  20702. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20703. std::string result;
  20704. char buf[8192];
  20705. ssize_t n;
  20706. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20707. result.append(buf, static_cast<size_t>(n));
  20708. }
  20709. return result;
  20710. }
  20711. // Mock stream for unit tests
  20712. class MockStream : public Stream {
  20713. public:
  20714. std::string data;
  20715. size_t pos = 0;
  20716. ssize_t error_after = -1; // -1 = no error
  20717. explicit MockStream(const std::string &d, ssize_t err = -1)
  20718. : data(d), error_after(err) {}
  20719. bool is_readable() const override { return true; }
  20720. bool wait_readable() const override { return true; }
  20721. bool wait_writable() const override { return true; }
  20722. ssize_t read(char *ptr, size_t size) override {
  20723. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20724. if (pos >= data.size()) return 0;
  20725. size_t limit =
  20726. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20727. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20728. std::memcpy(ptr, data.data() + pos, to_read);
  20729. pos += to_read;
  20730. return static_cast<ssize_t>(to_read);
  20731. }
  20732. ssize_t write(const char *, size_t) override { return -1; }
  20733. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20734. ip = "127.0.0.1";
  20735. port = 0;
  20736. }
  20737. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20738. ip = "127.0.0.1";
  20739. port = 0;
  20740. }
  20741. socket_t socket() const override { return INVALID_SOCKET; }
  20742. time_t duration() const override { return 0; }
  20743. };
  20744. TEST(StreamHandleTest, Basic) {
  20745. ClientImpl::StreamHandle handle;
  20746. EXPECT_FALSE(handle.is_valid());
  20747. handle.response = detail::make_unique<Response>();
  20748. handle.error = Error::Connection;
  20749. EXPECT_FALSE(handle.is_valid());
  20750. handle.error = Error::Success;
  20751. EXPECT_TRUE(handle.is_valid());
  20752. }
  20753. TEST(BodyReaderTest, Basic) {
  20754. MockStream stream("Hello, World!");
  20755. detail::BodyReader reader;
  20756. reader.stream = &stream;
  20757. reader.content_length = 13;
  20758. char buf[32];
  20759. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20760. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20761. EXPECT_TRUE(reader.eof);
  20762. }
  20763. TEST(BodyReaderTest, NoStream) {
  20764. detail::BodyReader reader;
  20765. char buf[32];
  20766. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20767. EXPECT_EQ(Error::Connection, reader.last_error);
  20768. }
  20769. TEST(BodyReaderTest, Error) {
  20770. MockStream stream("Hello, World!", 5);
  20771. detail::BodyReader reader;
  20772. reader.stream = &stream;
  20773. reader.content_length = 13;
  20774. char buf[32];
  20775. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20776. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20777. EXPECT_EQ(Error::Read, reader.last_error);
  20778. }
  20779. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20780. // Mock-based StreamHandle tests relying on private internals are removed.
  20781. class OpenStreamTest : public ::testing::Test {
  20782. protected:
  20783. void SetUp() override {
  20784. svr_.Get("/hello", [](const Request &, Response &res) {
  20785. res.set_content("Hello World!", "text/plain");
  20786. });
  20787. svr_.Get("/large", [](const Request &, Response &res) {
  20788. res.set_content(std::string(10000, 'X'), "text/plain");
  20789. });
  20790. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20791. res.set_content("Hello World!", "image/jpeg");
  20792. res.set_header("Content-Encoding", "UTF-8");
  20793. });
  20794. svr_.Get("/chunked", [](const Request &, Response &res) {
  20795. res.set_chunked_content_provider("text/plain",
  20796. [](size_t offset, DataSink &sink) {
  20797. if (offset < 15) {
  20798. sink.write("chunk", 5);
  20799. return true;
  20800. }
  20801. sink.done();
  20802. return true;
  20803. });
  20804. });
  20805. svr_.Get("/compressible", [](const Request &, Response &res) {
  20806. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20807. DataSink &sink) {
  20808. if (offset < 100 * 1024) {
  20809. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20810. sink.write(chunk.data(), chunk.size());
  20811. return true;
  20812. }
  20813. sink.done();
  20814. return true;
  20815. });
  20816. });
  20817. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20818. [](const Request & /*req*/, Response &res) {
  20819. auto i = new int(0);
  20820. res.set_header("Trailer", "Content-Length, X-Allowed");
  20821. res.set_chunked_content_provider(
  20822. "text/plain",
  20823. [i](size_t /*offset*/, DataSink &sink) {
  20824. switch (*i) {
  20825. case 0: sink.os << "123"; break;
  20826. case 1: sink.os << "456"; break;
  20827. case 2: sink.os << "789"; break;
  20828. case 3: {
  20829. sink.done_with_trailer(
  20830. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20831. } break;
  20832. }
  20833. (*i)++;
  20834. return true;
  20835. },
  20836. [i](bool success) {
  20837. EXPECT_TRUE(success);
  20838. delete i;
  20839. });
  20840. });
  20841. // Echo headers endpoint for header-related tests
  20842. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20843. std::string body;
  20844. for (const auto &h : req.headers) {
  20845. body.append(h.first);
  20846. body.push_back(':');
  20847. body.append(h.second);
  20848. body.push_back('\n');
  20849. }
  20850. res.set_content(body, "text/plain");
  20851. });
  20852. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20853. std::string body;
  20854. for (const auto &h : req.headers) {
  20855. body.append(h.first);
  20856. body.push_back(':');
  20857. body.append(h.second);
  20858. body.push_back('\n');
  20859. }
  20860. res.set_content(body, "text/plain");
  20861. });
  20862. port_ = svr_.bind_to_any_port("127.0.0.1");
  20863. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20864. svr_.wait_until_ready();
  20865. }
  20866. void TearDown() override {
  20867. svr_.stop();
  20868. if (thread_.joinable()) thread_.join();
  20869. }
  20870. Server svr_;
  20871. std::thread thread_;
  20872. int port_ = 0;
  20873. };
  20874. TEST_F(OpenStreamTest, Basic) {
  20875. Client cli("127.0.0.1", port_);
  20876. auto handle = cli.open_stream("GET", "/hello");
  20877. EXPECT_TRUE(handle.is_valid());
  20878. EXPECT_EQ("Hello World!", read_all(handle));
  20879. }
  20880. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20881. Client cli("127.0.0.1", port_);
  20882. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20883. ASSERT_TRUE(handle.is_valid());
  20884. EXPECT_EQ("Hello World!", read_all(handle));
  20885. }
  20886. TEST_F(OpenStreamTest, SmallBuffer) {
  20887. Client cli("127.0.0.1", port_);
  20888. auto handle = cli.open_stream("GET", "/hello");
  20889. std::string result;
  20890. char buf[4];
  20891. ssize_t n;
  20892. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20893. result.append(buf, static_cast<size_t>(n));
  20894. EXPECT_EQ("Hello World!", result);
  20895. }
  20896. TEST_F(OpenStreamTest, DefaultHeaders) {
  20897. Client cli("127.0.0.1", port_);
  20898. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20899. {
  20900. auto handle = cli.open_stream("GET", "/echo-headers");
  20901. ASSERT_TRUE(handle.is_valid());
  20902. auto body = read_all(handle);
  20903. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20904. std::string::npos);
  20905. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20906. std::string::npos);
  20907. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20908. }
  20909. // open_stream POST with body and no explicit content_type should NOT add
  20910. // text/plain Content-Type (behavior differs from non-streaming path), but
  20911. // should include Content-Length
  20912. {
  20913. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20914. ASSERT_TRUE(handle.is_valid());
  20915. auto body = read_all(handle);
  20916. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20917. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20918. }
  20919. // open_stream POST with explicit Content-Type should preserve it
  20920. {
  20921. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20922. {{"Content-Type", "application/custom"}},
  20923. "{}", "application/custom");
  20924. ASSERT_TRUE(handle.is_valid());
  20925. auto body = read_all(handle);
  20926. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20927. }
  20928. // User-specified User-Agent must not be overwritten for stream API
  20929. {
  20930. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20931. {{"User-Agent", "MyAgent/1.2"}});
  20932. ASSERT_TRUE(handle.is_valid());
  20933. auto body = read_all(handle);
  20934. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20935. }
  20936. }
  20937. TEST_F(OpenStreamTest, Large) {
  20938. Client cli("127.0.0.1", port_);
  20939. auto handle = cli.open_stream("GET", "/large");
  20940. EXPECT_EQ(10000u, read_all(handle).size());
  20941. }
  20942. TEST_F(OpenStreamTest, ConnectionError) {
  20943. Client cli("127.0.0.1", 9999);
  20944. auto handle = cli.open_stream("GET", "/hello");
  20945. EXPECT_FALSE(handle.is_valid());
  20946. }
  20947. TEST_F(OpenStreamTest, Chunked) {
  20948. Client cli("127.0.0.1", port_);
  20949. auto handle = cli.open_stream("GET", "/chunked");
  20950. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20951. "Transfer-Encoding") == "chunked");
  20952. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20953. }
  20954. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20955. Client cli("127.0.0.1", port_);
  20956. auto handle =
  20957. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20958. ASSERT_TRUE(handle.is_valid());
  20959. // Consume body to allow trailers to be received/parsed
  20960. auto body = read_all(handle);
  20961. // Explicitly parse trailers (ensure trailers are available for assertion)
  20962. handle.parse_trailers_if_needed();
  20963. EXPECT_EQ(std::string("123456789"), body);
  20964. // The response should include a Trailer header declaring both names
  20965. ASSERT_TRUE(handle.response);
  20966. EXPECT_TRUE(handle.response->has_header("Trailer"));
  20967. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  20968. handle.response->get_header_value("Trailer"));
  20969. // Prohibited trailer must not be present
  20970. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  20971. // Allowed trailer should be present
  20972. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  20973. EXPECT_EQ(std::string("yes"),
  20974. handle.response->get_trailer_value("X-Allowed"));
  20975. // Verify trailers are NOT present as regular headers
  20976. EXPECT_EQ(std::string(""),
  20977. handle.response->get_header_value("Content-Length"));
  20978. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  20979. }
  20980. // Accepts one connection on an OS-assigned port, which it hands over through
  20981. // port_promise, reads the request head and sends back response. after_send,
  20982. // if given, runs on the connection before it is closed.
  20983. static std::thread
  20984. serve_single_response(std::promise<int> &port_promise,
  20985. const std::string &response,
  20986. std::function<void(socket_t)> after_send = nullptr) {
  20987. return std::thread([&port_promise, response, after_send] {
  20988. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20989. default_socket_options(srv);
  20990. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20991. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20992. sockaddr_in addr{};
  20993. addr.sin_family = AF_INET;
  20994. addr.sin_port = htons(0); // Let OS assign a free port
  20995. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20996. int opt = 1;
  20997. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  20998. #ifdef _WIN32
  20999. reinterpret_cast<const char *>(&opt),
  21000. #else
  21001. &opt,
  21002. #endif
  21003. sizeof(opt));
  21004. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21005. ::listen(srv, 1) != 0) {
  21006. port_promise.set_value(-1);
  21007. detail::close_socket(srv);
  21008. return;
  21009. }
  21010. socklen_t addr_len = sizeof(addr);
  21011. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21012. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21013. sockaddr_in cli_addr{};
  21014. socklen_t cli_len = sizeof(cli_addr);
  21015. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21016. if (cli != INVALID_SOCKET) {
  21017. // Read the complete HTTP request (until the blank line that terminates
  21018. // headers) before sending the response. If the server closes the socket
  21019. // while the client's request data is still unread in the kernel receive
  21020. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21021. // connection on both sides: it discards the client's receive buffer
  21022. // (which already holds our response) and causes any in-progress write on
  21023. // the client to fail with ECONNRESET. Reading all request data first
  21024. // ensures close() emits a graceful FIN.
  21025. {
  21026. char rbuf[256];
  21027. std::string req;
  21028. while (req.find("\r\n\r\n") == std::string::npos) {
  21029. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21030. if (n <= 0) { break; }
  21031. req.append(rbuf, static_cast<size_t>(n));
  21032. }
  21033. }
  21034. ::send(cli,
  21035. #ifdef _WIN32
  21036. static_cast<const char *>(response.c_str()),
  21037. static_cast<int>(response.size()),
  21038. #else
  21039. response.c_str(), response.size(),
  21040. #endif
  21041. 0);
  21042. if (after_send) { after_send(cli); }
  21043. detail::close_socket(cli);
  21044. }
  21045. detail::close_socket(srv);
  21046. });
  21047. }
  21048. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21049. #ifndef _WIN32
  21050. signal(SIGPIPE, SIG_IGN);
  21051. #endif
  21052. std::promise<int> port_promise;
  21053. auto port_future = port_promise.get_future();
  21054. auto server_thread =
  21055. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21056. "Content-Type: text/plain\r\n"
  21057. "Content-Length: not-a-number\r\n"
  21058. "Connection: close\r\n"
  21059. "\r\n"
  21060. "hello");
  21061. auto port = port_future.get();
  21062. ASSERT_GT(port, 0);
  21063. Client cli("127.0.0.1", port);
  21064. auto handle = cli.open_stream("GET", "/");
  21065. EXPECT_FALSE(handle.is_valid());
  21066. server_thread.join();
  21067. }
  21068. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21069. #ifndef _WIN32
  21070. signal(SIGPIPE, SIG_IGN);
  21071. #endif
  21072. std::promise<int> port_promise;
  21073. auto port_future = port_promise.get_future();
  21074. auto server_thread = serve_single_response(
  21075. port_promise, "HTTP/1.1 200 OK\r\n"
  21076. "Content-Type: text/plain\r\n"
  21077. "Content-Length: 99999999999999999999999999\r\n"
  21078. "Connection: close\r\n"
  21079. "\r\n"
  21080. "hello");
  21081. auto port = port_future.get();
  21082. ASSERT_GT(port, 0);
  21083. // Historically std::stoull would throw std::out_of_range here and crash
  21084. // the process, then parsing silently clamped to a bogus framing length and
  21085. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21086. // so the stream fails to open, matching the not-a-number case above. The
  21087. // process still must NOT terminate.
  21088. Client cli("127.0.0.1", port);
  21089. auto handle = cli.open_stream("GET", "/");
  21090. EXPECT_FALSE(handle.is_valid());
  21091. server_thread.join();
  21092. }
  21093. #ifndef _WIN32
  21094. // As above for the body of a streamed request: a send() cut short by the write
  21095. // timeout must not leave the rest of the body unsent.
  21096. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21097. signal(SIGPIPE, SIG_IGN);
  21098. Server svr;
  21099. svr.set_socket_options([](socket_t sock) {
  21100. int size = 8192;
  21101. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21102. reinterpret_cast<const char *>(&size), sizeof(size));
  21103. });
  21104. svr.Post("/size", [](const Request &, Response &res,
  21105. const ContentReader &content_reader) {
  21106. // Outlast the client's write timeout before reading the body.
  21107. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21108. size_t received = 0;
  21109. content_reader([&](const char *, size_t len) {
  21110. received += len;
  21111. return true;
  21112. });
  21113. res.set_content(std::to_string(received), "text/plain");
  21114. });
  21115. auto port = svr.bind_to_any_port(HOST);
  21116. std::thread t([&]() { svr.listen_after_bind(); });
  21117. auto se = detail::scope_exit([&] {
  21118. svr.stop();
  21119. t.join();
  21120. });
  21121. svr.wait_until_ready();
  21122. Client cli(HOST, port);
  21123. cli.set_write_timeout(0, 500000);
  21124. cli.set_socket_options([](socket_t sock) {
  21125. int size = 8192;
  21126. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21127. reinterpret_cast<const char *>(&size), sizeof(size));
  21128. });
  21129. const std::string body(4 * 1024 * 1024, 'A');
  21130. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21131. "application/octet-stream");
  21132. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21133. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21134. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21135. }
  21136. #endif
  21137. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21138. std::promise<void> slow_started;
  21139. auto slow_started_future = slow_started.get_future();
  21140. Server svr;
  21141. svr.Get("/slow", [&](const Request &, Response &res) {
  21142. slow_started.set_value();
  21143. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21144. res.set_content("slow", "text/plain");
  21145. });
  21146. svr.Get("/fast", [](const Request &, Response &res) {
  21147. res.set_content("fast", "text/plain");
  21148. });
  21149. auto port = svr.bind_to_any_port(HOST);
  21150. std::thread t([&]() { svr.listen_after_bind(); });
  21151. auto se = detail::scope_exit([&] {
  21152. svr.stop();
  21153. t.join();
  21154. });
  21155. svr.wait_until_ready();
  21156. Client cli(HOST, port);
  21157. std::string slow_body;
  21158. std::thread slow_thread([&] {
  21159. auto res = cli.Get("/slow");
  21160. if (res) { slow_body = res->body; }
  21161. });
  21162. slow_started_future.wait();
  21163. auto result = stream::Get(cli, "/fast");
  21164. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21165. slow_thread.join();
  21166. EXPECT_EQ("slow", slow_body);
  21167. EXPECT_EQ("fast", fast_body);
  21168. }
  21169. // Serves `response` to the single request `fn` makes with a fresh client.
  21170. template <typename Fn>
  21171. static void with_single_response(const std::string &response, Fn fn) {
  21172. #ifndef _WIN32
  21173. signal(SIGPIPE, SIG_IGN);
  21174. #endif
  21175. std::promise<int> port_promise;
  21176. auto port_future = port_promise.get_future();
  21177. auto server_thread = serve_single_response(port_promise, response);
  21178. auto se = detail::scope_exit([&] { server_thread.join(); });
  21179. auto port = port_future.get();
  21180. ASSERT_GT(port, 0);
  21181. Client cli("127.0.0.1", port);
  21182. fn(cli);
  21183. }
  21184. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21185. // too, also in a build without the decoder for the advertised coding.
  21186. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21187. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21188. const auto response = "HTTP/1.1 200 OK\r\n"
  21189. "Content-Encoding: gzip\r\n"
  21190. "Content-Length: " +
  21191. std::to_string(gzipped.size()) +
  21192. "\r\n"
  21193. "Connection: close\r\n\r\n" +
  21194. gzipped;
  21195. with_single_response(response, [&](Client &cli) {
  21196. cli.set_decompress(false);
  21197. auto handle = cli.open_stream("GET", "/");
  21198. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21199. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21200. EXPECT_EQ(gzipped, read_all(handle));
  21201. EXPECT_FALSE(handle.has_read_error());
  21202. });
  21203. with_single_response(response, [&](Client &cli) {
  21204. cli.set_decompress(false);
  21205. auto res = stream::Get(cli, "/", 7);
  21206. ASSERT_TRUE(res) << to_string(res.error());
  21207. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21208. EXPECT_EQ(gzipped, res.read_all());
  21209. EXPECT_FALSE(res.has_read_error());
  21210. });
  21211. }
  21212. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21213. // Neither Content-Length nor chunked: the body ends at the close
  21214. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21215. "Connection: close\r\n"
  21216. "\r\n"
  21217. "hello";
  21218. with_single_response(close_delimited, [](Client &cli) {
  21219. auto handle = cli.open_stream("GET", "/");
  21220. ASSERT_TRUE(handle.is_valid());
  21221. EXPECT_EQ("hello", read_all(handle));
  21222. EXPECT_FALSE(handle.has_read_error());
  21223. });
  21224. // A close before the end of the Content-Length is still an error
  21225. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21226. "Content-Length: 10\r\n"
  21227. "\r\n"
  21228. "hello";
  21229. with_single_response(short_content_length, [](Client &cli) {
  21230. auto handle = cli.open_stream("GET", "/");
  21231. ASSERT_TRUE(handle.is_valid());
  21232. read_all(handle);
  21233. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21234. });
  21235. // So is a close before the last chunk
  21236. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21237. "Transfer-Encoding: chunked\r\n"
  21238. "\r\n"
  21239. "5\r\nhello\r\n";
  21240. with_single_response(short_chunked, [](Client &cli) {
  21241. auto handle = cli.open_stream("GET", "/");
  21242. ASSERT_TRUE(handle.is_valid());
  21243. read_all(handle);
  21244. EXPECT_TRUE(handle.has_read_error());
  21245. });
  21246. }
  21247. #ifdef CPPHTTPLIB_SSL_ENABLED
  21248. // Serves `response` to one request, then closes with or without a close_notify
  21249. template <typename Fn>
  21250. static void with_single_tls_response(const std::string &response,
  21251. bool close_notify, Fn fn) {
  21252. #ifndef _WIN32
  21253. signal(SIGPIPE, SIG_IGN);
  21254. #endif
  21255. std::promise<int> port_promise;
  21256. auto port_future = port_promise.get_future();
  21257. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21258. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21259. default_socket_options(srv);
  21260. sockaddr_in addr{};
  21261. addr.sin_family = AF_INET;
  21262. addr.sin_port = htons(0);
  21263. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21264. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21265. ::listen(srv, 1) != 0) {
  21266. port_promise.set_value(-1);
  21267. detail::close_socket(srv);
  21268. return;
  21269. }
  21270. socklen_t addr_len = sizeof(addr);
  21271. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21272. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21273. auto cli = ::accept(srv, nullptr, nullptr);
  21274. if (cli != INVALID_SOCKET) {
  21275. auto ctx = tls::create_server_context();
  21276. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21277. nullptr);
  21278. auto session = tls::create_session(ctx, cli);
  21279. tls::TlsError err;
  21280. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21281. // The request head first, so that closing the socket sends a FIN
  21282. // rather than an RST for the unread bytes.
  21283. std::string req;
  21284. char buf[256];
  21285. while (req.find("\r\n\r\n") == std::string::npos) {
  21286. auto n = tls::read(session, buf, sizeof(buf), err);
  21287. if (n <= 0) { break; }
  21288. req.append(buf, static_cast<size_t>(n));
  21289. }
  21290. size_t sent = 0;
  21291. while (sent < response.size()) {
  21292. auto n = tls::write(session, response.data() + sent,
  21293. response.size() - sent, err);
  21294. if (n <= 0) { break; }
  21295. sent += static_cast<size_t>(n);
  21296. }
  21297. if (close_notify) { tls::shutdown(session, true); }
  21298. }
  21299. tls::free_session(session);
  21300. detail::close_socket(cli);
  21301. tls::free_context(ctx);
  21302. }
  21303. detail::close_socket(srv);
  21304. });
  21305. auto se = detail::scope_exit([&] { server_thread.join(); });
  21306. auto port = port_future.get();
  21307. ASSERT_GT(port, 0);
  21308. SSLClient cli("127.0.0.1", port);
  21309. cli.enable_server_certificate_verification(false);
  21310. fn(cli);
  21311. }
  21312. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21313. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21314. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21315. "Connection: close\r\n"
  21316. "\r\n"
  21317. "hello";
  21318. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21319. auto res = cli.Get("/");
  21320. ASSERT_TRUE(res) << to_string(res.error());
  21321. EXPECT_EQ("hello", res->body);
  21322. });
  21323. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21324. auto res = cli.Get("/");
  21325. ASSERT_FALSE(res);
  21326. EXPECT_EQ(Error::Read, res.error());
  21327. });
  21328. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21329. auto handle = cli.open_stream("GET", "/");
  21330. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21331. read_all(handle);
  21332. EXPECT_TRUE(handle.has_read_error());
  21333. });
  21334. // A framed body ends where its framing says, with or without the alert
  21335. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21336. "Content-Length: 5\r\n"
  21337. "Connection: close\r\n"
  21338. "\r\n"
  21339. "hello";
  21340. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21341. auto res = cli.Get("/");
  21342. ASSERT_TRUE(res) << to_string(res.error());
  21343. EXPECT_EQ("hello", res->body);
  21344. });
  21345. }
  21346. #endif
  21347. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21348. const char *responses[] = {
  21349. "HTTP/1.1 103 Early Hints\r\n"
  21350. "Link: </style.css>; rel=preload\r\n"
  21351. "\r\n"
  21352. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21353. "HTTP/1.1 100 Continue\r\n"
  21354. "X-Note: interim\r\n"
  21355. "\r\n"
  21356. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21357. };
  21358. for (auto response : responses) {
  21359. with_single_response(response, [](Client &cli) {
  21360. auto res = cli.Get("/");
  21361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21362. EXPECT_EQ(StatusCode::OK_200, res->status);
  21363. EXPECT_EQ("ok", res->body);
  21364. });
  21365. }
  21366. }
  21367. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21368. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21369. const std::string final_response =
  21370. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21371. std::string interims;
  21372. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21373. interims += interim;
  21374. }
  21375. with_single_response(interims + final_response, [](Client &cli) {
  21376. auto res = cli.Get("/");
  21377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21378. EXPECT_EQ("ok", res->body);
  21379. });
  21380. with_single_response(interims + interim + final_response, [](Client &cli) {
  21381. auto res = cli.Get("/");
  21382. ASSERT_FALSE(res);
  21383. EXPECT_EQ(Error::Read, res.error());
  21384. });
  21385. }
  21386. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21387. #ifndef _WIN32
  21388. signal(SIGPIPE, SIG_IGN);
  21389. #endif
  21390. // The server answers the head without asking for the body. Bytes it then
  21391. // reads on the connection would be taken for the body the request declared.
  21392. auto closed_by_client = false;
  21393. std::promise<int> port_promise;
  21394. auto server_thread = serve_single_response(
  21395. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21396. [&](socket_t sock) {
  21397. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21398. char buf[256];
  21399. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21400. });
  21401. Client cli("127.0.0.1", port_promise.get_future().get());
  21402. cli.set_keep_alive(true);
  21403. cli.set_read_timeout(1, 0);
  21404. // Long enough for the client to send Expect: 100-continue.
  21405. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21407. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21408. cli.Get("/second");
  21409. server_thread.join();
  21410. EXPECT_TRUE(closed_by_client);
  21411. }
  21412. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21413. // Long enough for the client to send Expect: 100-continue
  21414. with_single_response(
  21415. "HTTP/1.1 103 Early Hints\r\n"
  21416. "Link: </style.css>; rel=preload\r\n"
  21417. "\r\n"
  21418. "HTTP/1.1 401 Unauthorized\r\n"
  21419. "Content-Length: 0\r\n\r\n",
  21420. [](Client &cli) {
  21421. cli.set_read_timeout(2, 0);
  21422. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21424. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21425. });
  21426. }
  21427. #ifdef CPPHTTPLIB_SSL_ENABLED
  21428. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21429. #ifndef _WIN32
  21430. signal(SIGPIPE, SIG_IGN);
  21431. #endif
  21432. auto reused = false;
  21433. std::promise<int> port_promise;
  21434. auto server_thread = serve_single_response(
  21435. port_promise,
  21436. "HTTP/1.1 401 Unauthorized\r\n"
  21437. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21438. "Content-Length: 0\r\n\r\n",
  21439. [&](socket_t sock) {
  21440. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21441. char buf[256];
  21442. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21443. });
  21444. Client cli("127.0.0.1", port_promise.get_future().get());
  21445. cli.set_keep_alive(true);
  21446. cli.set_digest_auth("user", "pass");
  21447. cli.set_read_timeout(1, 0);
  21448. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21449. server_thread.join();
  21450. EXPECT_FALSE(reused);
  21451. }
  21452. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21453. // Any other answer to CONNECT would read as the origin's response.
  21454. struct {
  21455. const char *response;
  21456. bool passed_on;
  21457. } cases[] = {
  21458. {"HTTP/1.1 201 Created\r\n"
  21459. "Set-Cookie: session=from-proxy\r\n"
  21460. "Content-Length: 0\r\n\r\n",
  21461. false},
  21462. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21463. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21464. "Content-Length: 0\r\n\r\n",
  21465. true},
  21466. };
  21467. for (const auto &c : cases) {
  21468. std::promise<int> port_promise;
  21469. auto server_thread = serve_single_response(port_promise, c.response);
  21470. SSLClient cli("example.com", 443);
  21471. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21472. auto res = cli.Get("/");
  21473. server_thread.join();
  21474. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21475. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21476. if (res) {
  21477. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21478. }
  21479. }
  21480. }
  21481. #endif
  21482. // Records the client's error logger calls as "error METHOD path", or
  21483. // "error null" for a call without a request
  21484. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21485. return [&log](const Error &err, const Request *req) {
  21486. log.push_back(to_string(err) + " " +
  21487. (req ? req->method + " " + req->path : "null"));
  21488. };
  21489. }
  21490. // A failed request is reported once, with the request the caller made
  21491. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21492. Server svr;
  21493. svr.Get("/big", [](const Request &, Response &res) {
  21494. res.set_content(std::string(100000, 'b'), "text/plain");
  21495. });
  21496. auto port = svr.bind_to_any_port(HOST);
  21497. std::thread t([&]() { svr.listen_after_bind(); });
  21498. auto se = detail::scope_exit([&] {
  21499. svr.stop();
  21500. t.join();
  21501. });
  21502. svr.wait_until_ready();
  21503. Client cli(HOST, port);
  21504. std::vector<std::string> log;
  21505. cli.set_error_logger(record_errors(log));
  21506. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21507. cli.Get("/big", [](const char *, size_t) { return false; });
  21508. EXPECT_EQ(expected, log);
  21509. log.clear();
  21510. cli.Get("/big", [](size_t, size_t) { return false; });
  21511. EXPECT_EQ(expected, log);
  21512. }
  21513. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21514. // Fails while the body is read
  21515. auto broken = [](const Request &, Response &res) {
  21516. res.set_content_provider(10, "text/plain",
  21517. [](size_t, size_t, DataSink &) { return false; });
  21518. };
  21519. Server other;
  21520. other.Get("/broken", broken);
  21521. auto other_port = other.bind_to_any_port(HOST);
  21522. std::thread other_t([&]() { other.listen_after_bind(); });
  21523. auto other_se = detail::scope_exit([&] {
  21524. other.stop();
  21525. other_t.join();
  21526. });
  21527. other.wait_until_ready();
  21528. Server svr;
  21529. svr.Get("/broken", broken);
  21530. svr.Get("/same-origin",
  21531. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21532. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21533. res.set_redirect("http://" + std::string(HOST) + ":" +
  21534. std::to_string(other_port) + "/broken");
  21535. });
  21536. auto port = svr.bind_to_any_port(HOST);
  21537. std::thread t([&]() { svr.listen_after_bind(); });
  21538. auto se = detail::scope_exit([&] {
  21539. svr.stop();
  21540. t.join();
  21541. });
  21542. svr.wait_until_ready();
  21543. Client cli(HOST, port);
  21544. cli.set_follow_location(true);
  21545. std::vector<std::string> log;
  21546. cli.set_error_logger(record_errors(log));
  21547. for (auto path : {"/same-origin", "/cross-origin"}) {
  21548. log.clear();
  21549. auto res = cli.Get(path);
  21550. ASSERT_FALSE(res);
  21551. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21552. log);
  21553. }
  21554. }
  21555. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21556. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21557. std::vector<std::string> log;
  21558. cli.set_error_logger(record_errors(log));
  21559. auto handle = cli.open_stream("GET", "/x");
  21560. EXPECT_FALSE(handle.is_valid());
  21561. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21562. log);
  21563. });
  21564. }
  21565. #ifdef CPPHTTPLIB_SSL_ENABLED
  21566. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21567. // Not a TLS server, so the handshake fails. It waits for a request line in
  21568. // the handshake bytes, so a short read timeout lets it close quickly.
  21569. Server svr;
  21570. svr.set_read_timeout(0, 100000);
  21571. svr.Get("/x", [](const Request &, Response &res) {
  21572. res.set_content("x", "text/plain");
  21573. });
  21574. auto port = svr.bind_to_any_port(HOST);
  21575. std::thread t([&]() { svr.listen_after_bind(); });
  21576. auto se = detail::scope_exit([&] {
  21577. svr.stop();
  21578. t.join();
  21579. });
  21580. svr.wait_until_ready();
  21581. std::vector<std::string> log;
  21582. SSLClient cli(HOST, port);
  21583. cli.enable_server_certificate_verification(false);
  21584. cli.set_error_logger(record_errors(log));
  21585. auto res = cli.Get("/x");
  21586. ASSERT_FALSE(res);
  21587. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21588. log.clear();
  21589. auto handle = cli.open_stream("GET", "/x");
  21590. EXPECT_FALSE(handle.is_valid());
  21591. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21592. log.clear();
  21593. SSLClient no_ca(HOST, port);
  21594. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21595. no_ca.set_error_logger(record_errors(log));
  21596. res = no_ca.Get("/x");
  21597. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21598. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21599. }
  21600. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21601. #ifndef _WIN32
  21602. signal(SIGPIPE, SIG_IGN);
  21603. #endif
  21604. // Refused, answered with a challenge, or closed without an answer
  21605. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21606. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21607. "Content-Length: 0\r\n\r\n",
  21608. ""}) {
  21609. std::promise<int> port_promise;
  21610. auto server_thread = serve_single_response(port_promise, response);
  21611. SSLClient cli("example.com", 443);
  21612. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21613. std::vector<std::string> log;
  21614. cli.set_error_logger(record_errors(log));
  21615. auto res = cli.Get("/");
  21616. server_thread.join();
  21617. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21618. << response;
  21619. }
  21620. }
  21621. #endif
  21622. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21623. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21624. // the chunked coding and drop Content-Length, so a front-end that trusts
  21625. // Content-Length would disagree about where the body ends (response
  21626. // smuggling). The client must reject such a response.
  21627. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21628. for (const char *te : {"chunked", "gzip, chunked"}) {
  21629. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21630. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21631. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21632. "5\r\nhello\r\n0\r\n\r\n";
  21633. with_single_response(response, [&](Client &cli) {
  21634. auto res = cli.Get("/");
  21635. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21636. EXPECT_EQ(Error::Read, res.error()) << te;
  21637. });
  21638. with_single_response(response, [&](Client &cli) {
  21639. auto handle = cli.open_stream("GET", "/");
  21640. EXPECT_FALSE(handle.is_valid()) << te;
  21641. EXPECT_EQ(Error::Read, handle.error) << te;
  21642. });
  21643. }
  21644. }
  21645. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21646. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21647. // closing the connection (unlike a request, which must be rejected).
  21648. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21649. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21650. "Transfer-Encoding: chunked\r\n"
  21651. "Connection: close\r\n"
  21652. "\r\n"
  21653. "5\r\nhello\r\n0\r\n\r\n",
  21654. "HTTP/1.1 200 OK\r\n"
  21655. "Transfer-Encoding: gzip\r\n"
  21656. "Connection: close\r\n"
  21657. "\r\n"
  21658. "hello"}) {
  21659. with_single_response(response, [&](Client &cli) {
  21660. auto res = cli.Get("/");
  21661. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21662. EXPECT_EQ("hello", res->body);
  21663. });
  21664. with_single_response(response, [&](Client &cli) {
  21665. auto handle = cli.open_stream("GET", "/");
  21666. ASSERT_TRUE(handle.is_valid()) << response;
  21667. EXPECT_EQ("hello", read_all(handle));
  21668. });
  21669. }
  21670. }
  21671. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21672. // framing headers describe nothing to read and must not be rejected.
  21673. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21674. const std::string framing = "Content-Length: 5\r\n"
  21675. "Transfer-Encoding: chunked\r\n"
  21676. "Connection: close\r\n"
  21677. "\r\n";
  21678. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21679. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21680. });
  21681. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21682. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21683. });
  21684. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21685. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21686. with_single_response(response, [&](Client &cli) {
  21687. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21688. });
  21689. with_single_response(response, [&](Client &cli) {
  21690. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21691. });
  21692. }
  21693. }
  21694. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21695. // header section, so a stream opened on one has nothing to read, whatever
  21696. // framing or coding headers it carries.
  21697. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21698. struct Case {
  21699. const char *method;
  21700. const char *status;
  21701. };
  21702. // A reader of the declared body reports an early close when nothing
  21703. // follows, and hands back what does.
  21704. struct Framing {
  21705. const char *headers;
  21706. const char *after;
  21707. };
  21708. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21709. Case{"GET", "304 Not Modified"}}) {
  21710. for (const auto &f :
  21711. {Framing{"Content-Length: 5\r\n", ""},
  21712. Framing{"Content-Length: 5\r\n", "hello"},
  21713. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21714. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21715. // Not decoded, so a build without Brotli opens it too
  21716. Framing{"Content-Encoding: br\r\n", ""}}) {
  21717. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21718. "Connection: close\r\n"
  21719. "\r\n" +
  21720. f.after;
  21721. with_single_response(response, [&](Client &cli) {
  21722. auto handle = cli.open_stream(c.method, "/");
  21723. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21724. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21725. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21726. });
  21727. }
  21728. }
  21729. }
  21730. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21731. // response, is faulty framing, so the connection is not reused after it.
  21732. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21733. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21734. "Content-Length: 0\r\n"
  21735. "Transfer-Encoding: chunked\r\n"
  21736. "\r\n"
  21737. "5\r\nhello\r\n0\r\n\r\n",
  21738. "HTTP/1.0 200 Connection established\r\n"
  21739. "Connection: keep-alive\r\n"
  21740. "Transfer-Encoding: chunked\r\n"
  21741. "\r\n"
  21742. "5\r\nhello\r\n0\r\n\r\n"}) {
  21743. with_single_response(response, [&](Client &cli) {
  21744. cli.set_keep_alive(true);
  21745. auto res = cli.Get("/");
  21746. ASSERT_TRUE(res) << response;
  21747. EXPECT_EQ("hello", res->body);
  21748. EXPECT_FALSE(cli.is_socket_open()) << response;
  21749. });
  21750. }
  21751. }
  21752. // A payload max length of 0 means no limit, however the body is framed.
  21753. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21754. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21755. "Transfer-Encoding: chunked\r\n"
  21756. "\r\n"
  21757. "5\r\nhello\r\n0\r\n\r\n",
  21758. "HTTP/1.1 200 OK\r\n"
  21759. "Connection: close\r\n"
  21760. "\r\n"
  21761. "hello"}) {
  21762. with_single_response(response, [&](Client &cli) {
  21763. cli.set_payload_max_length(0);
  21764. auto res = cli.Get("/");
  21765. ASSERT_TRUE(res) << response;
  21766. EXPECT_EQ("hello", res->body) << response;
  21767. });
  21768. }
  21769. }
  21770. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21771. Server svr;
  21772. svr.set_payload_max_length(0);
  21773. svr.Post("/echo", [](const Request &req, Response &res) {
  21774. res.set_content(req.body, "text/plain");
  21775. });
  21776. auto port = svr.bind_to_any_port(HOST);
  21777. thread t = thread([&] { svr.listen_after_bind(); });
  21778. auto se = detail::scope_exit([&] {
  21779. svr.stop();
  21780. t.join();
  21781. ASSERT_FALSE(svr.is_running());
  21782. });
  21783. svr.wait_until_ready();
  21784. Client cli(HOST, port);
  21785. auto res = cli.Post(
  21786. "/echo",
  21787. [](size_t /*offset*/, DataSink &sink) {
  21788. sink.write("hello", 5);
  21789. sink.done();
  21790. return true;
  21791. },
  21792. "text/plain");
  21793. ASSERT_TRUE(res);
  21794. EXPECT_EQ(StatusCode::OK_200, res->status);
  21795. EXPECT_EQ("hello", res->body);
  21796. }
  21797. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21798. TEST_F(OpenStreamTest, Gzip) {
  21799. Client cli("127.0.0.1", port_);
  21800. auto handle = cli.open_stream("GET", "/compressible", {},
  21801. {{"Accept-Encoding", "gzip"}});
  21802. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21803. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21804. }
  21805. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21806. Client cli("127.0.0.1", port_);
  21807. auto handle =
  21808. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21809. {{"Accept-Encoding", "gzip"}});
  21810. ASSERT_TRUE(handle.is_valid());
  21811. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21812. EXPECT_EQ("123456789", read_all(handle));
  21813. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21814. }
  21815. #endif
  21816. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21817. TEST_F(OpenStreamTest, Brotli) {
  21818. Client cli("127.0.0.1", port_);
  21819. auto handle =
  21820. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21821. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21822. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21823. }
  21824. #endif
  21825. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21826. TEST_F(OpenStreamTest, Zstd) {
  21827. Client cli("127.0.0.1", port_);
  21828. auto handle = cli.open_stream("GET", "/compressible", {},
  21829. {{"Accept-Encoding", "zstd"}});
  21830. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21831. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21832. }
  21833. #endif
  21834. #ifdef CPPHTTPLIB_SSL_ENABLED
  21835. class SSLOpenStreamTest : public ::testing::Test {
  21836. protected:
  21837. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21838. void SetUp() override {
  21839. svr_.Get("/hello", [](const Request &, Response &res) {
  21840. res.set_content("Hello SSL World!", "text/plain");
  21841. });
  21842. svr_.Get("/chunked", [](const Request &, Response &res) {
  21843. res.set_chunked_content_provider("text/plain",
  21844. [](size_t offset, DataSink &sink) {
  21845. if (offset < 15) {
  21846. sink.write("chunk", 5);
  21847. return true;
  21848. }
  21849. sink.done();
  21850. return true;
  21851. });
  21852. });
  21853. svr_.Post("/echo", [](const Request &req, Response &res) {
  21854. res.set_content(req.body, req.get_header_value("Content-Type"));
  21855. });
  21856. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21857. std::string body = req.body;
  21858. res.set_chunked_content_provider(
  21859. "text/plain", [body](size_t offset, DataSink &sink) {
  21860. if (offset < body.size()) {
  21861. sink.write(body.data() + offset, body.size() - offset);
  21862. }
  21863. sink.done();
  21864. return true;
  21865. });
  21866. });
  21867. port_ = svr_.bind_to_any_port("127.0.0.1");
  21868. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21869. svr_.wait_until_ready();
  21870. }
  21871. void TearDown() override {
  21872. svr_.stop();
  21873. if (thread_.joinable()) thread_.join();
  21874. }
  21875. SSLServer svr_;
  21876. std::thread thread_;
  21877. int port_ = 0;
  21878. };
  21879. TEST_F(SSLOpenStreamTest, Basic) {
  21880. SSLClient cli("127.0.0.1", port_);
  21881. cli.enable_server_certificate_verification(false);
  21882. auto handle = cli.open_stream("GET", "/hello");
  21883. ASSERT_TRUE(handle.is_valid());
  21884. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21885. }
  21886. TEST_F(SSLOpenStreamTest, Chunked) {
  21887. SSLClient cli("127.0.0.1", port_);
  21888. cli.enable_server_certificate_verification(false);
  21889. auto handle = cli.open_stream("GET", "/chunked");
  21890. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21891. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21892. "Transfer-Encoding") == "chunked");
  21893. auto body = read_all(handle);
  21894. EXPECT_EQ("chunkchunkchunk", body);
  21895. }
  21896. TEST_F(SSLOpenStreamTest, Post) {
  21897. SSLClient cli("127.0.0.1", port_);
  21898. cli.enable_server_certificate_verification(false);
  21899. auto handle =
  21900. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21901. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21902. EXPECT_EQ(200, handle.response->status);
  21903. auto body = read_all(handle);
  21904. EXPECT_EQ("Hello SSL POST", body);
  21905. }
  21906. TEST_F(SSLOpenStreamTest, PostChunked) {
  21907. SSLClient cli("127.0.0.1", port_);
  21908. cli.enable_server_certificate_verification(false);
  21909. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21910. "Chunked SSL Data", "text/plain");
  21911. ASSERT_TRUE(handle.is_valid());
  21912. EXPECT_EQ(200, handle.response->status);
  21913. auto body = read_all(handle);
  21914. EXPECT_EQ("Chunked SSL Data", body);
  21915. }
  21916. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21917. // Content-Length is terminated by the server closing the connection. When the
  21918. // SSL peer sends a close_notify after the body, the client must treat it as a
  21919. // clean EOF and return a successful response rather than an error.
  21920. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21921. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21922. ASSERT_TRUE(svr.is_valid());
  21923. svr.set_keep_alive_max_count(1);
  21924. const std::string expected_body = "Hello from connection-close response!";
  21925. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21926. res.set_content_provider("text/plain",
  21927. [&](size_t offset, DataSink &sink) -> bool {
  21928. if (offset < expected_body.size()) {
  21929. sink.write(expected_body.data() + offset,
  21930. expected_body.size() - offset);
  21931. }
  21932. sink.done();
  21933. return true;
  21934. });
  21935. });
  21936. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21937. auto se = detail::scope_exit([&] {
  21938. svr.stop();
  21939. listen_thread.join();
  21940. ASSERT_FALSE(svr.is_running());
  21941. });
  21942. svr.wait_until_ready();
  21943. SSLClient cli(HOST, PORT);
  21944. cli.enable_server_certificate_verification(false);
  21945. auto res = cli.Get("/no-content-length");
  21946. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21947. EXPECT_EQ(StatusCode::OK_200, res->status);
  21948. EXPECT_EQ(expected_body, res->body);
  21949. }
  21950. // Without Content-Length, the full buffer size reaches tls::read().
  21951. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21952. if (sizeof(size_t) <= sizeof(int)) {
  21953. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21954. }
  21955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21956. ASSERT_TRUE(svr.is_valid());
  21957. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21958. res.set_content_provider("text/plain",
  21959. [&](size_t offset, DataSink &sink) -> bool {
  21960. if (offset == 0) { sink.write("Hello", 5); }
  21961. sink.done();
  21962. return true;
  21963. });
  21964. });
  21965. auto port = svr.bind_to_any_port(HOST);
  21966. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  21967. auto se = detail::scope_exit([&] {
  21968. svr.stop();
  21969. listen_thread.join();
  21970. });
  21971. svr.wait_until_ready();
  21972. SSLClient cli(HOST, port);
  21973. cli.enable_server_certificate_verification(false);
  21974. auto handle = cli.open_stream("GET", "/no-content-length");
  21975. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21976. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  21977. std::unique_ptr<char[]> buf(new char[len]);
  21978. std::string body;
  21979. ssize_t n;
  21980. while ((n = handle.read(buf.get(), len)) > 0) {
  21981. body.append(buf.get(), static_cast<size_t>(n));
  21982. }
  21983. EXPECT_EQ(0, n);
  21984. EXPECT_EQ("Hello", body);
  21985. }
  21986. #endif // CPPHTTPLIB_SSL_ENABLED
  21987. //==============================================================================
  21988. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  21989. // results for various scenarios.
  21990. //==============================================================================
  21991. TEST(ParityTest, GetVsOpenStream) {
  21992. Server svr;
  21993. const std::string path = "/parity";
  21994. const std::string content = "Parity test content: hello world";
  21995. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  21996. res.set_content(content, "text/plain");
  21997. });
  21998. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21999. auto se = detail::scope_exit([&] {
  22000. svr.stop();
  22001. t.join();
  22002. ASSERT_FALSE(svr.is_running());
  22003. });
  22004. svr.wait_until_ready();
  22005. Client cli(HOST, PORT);
  22006. // Non-stream path
  22007. auto r1 = cli.Get(path);
  22008. ASSERT_TRUE(r1);
  22009. EXPECT_EQ(StatusCode::OK_200, r1->status);
  22010. // Stream path
  22011. auto h = cli.open_stream("GET", path);
  22012. ASSERT_TRUE(h.is_valid());
  22013. EXPECT_EQ(r1->body, read_all(h));
  22014. }
  22015. // Helper to compress data with provided compressor type T
  22016. template <typename Compressor>
  22017. static std::string compress_payload_for_parity(const std::string &in) {
  22018. std::string out;
  22019. Compressor compressor;
  22020. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22021. [&](const char *data, size_t n) {
  22022. out.append(data, n);
  22023. return true;
  22024. });
  22025. EXPECT_TRUE(ok);
  22026. return out;
  22027. }
  22028. // Helper function for compression parity tests
  22029. template <typename Compressor>
  22030. static void test_compression_parity(const std::string &original,
  22031. const std::string &path,
  22032. const std::string &encoding) {
  22033. const std::string compressed =
  22034. compress_payload_for_parity<Compressor>(original);
  22035. Server svr;
  22036. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22037. res.set_content(compressed, "application/octet-stream");
  22038. res.set_header("Content-Encoding", encoding);
  22039. });
  22040. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22041. auto se = detail::scope_exit([&] {
  22042. svr.stop();
  22043. t.join();
  22044. ASSERT_FALSE(svr.is_running());
  22045. });
  22046. svr.wait_until_ready();
  22047. Client cli(HOST, PORT);
  22048. // Non-streaming
  22049. {
  22050. auto res = cli.Get(path);
  22051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22052. EXPECT_EQ(StatusCode::OK_200, res->status);
  22053. EXPECT_EQ(original, res->body);
  22054. }
  22055. // Streaming
  22056. {
  22057. auto h = cli.open_stream("GET", path);
  22058. ASSERT_TRUE(h.is_valid());
  22059. EXPECT_EQ(original, read_all(h));
  22060. }
  22061. }
  22062. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22063. TEST(ParityTest, Gzip) {
  22064. test_compression_parity<detail::gzip_compressor>(
  22065. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22066. }
  22067. #endif
  22068. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22069. TEST(ParityTest, Brotli) {
  22070. test_compression_parity<detail::brotli_compressor>(
  22071. "Hello, brotli parity test payload", "/parity-br", "br");
  22072. }
  22073. #endif
  22074. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22075. TEST(ParityTest, Zstd) {
  22076. test_compression_parity<detail::zstd_compressor>(
  22077. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22078. }
  22079. #endif
  22080. //==============================================================================
  22081. // New Stream API Tests
  22082. //==============================================================================
  22083. inline std::string read_body(httplib::stream::Result &result) {
  22084. std::string body;
  22085. while (result.next()) {
  22086. body.append(result.data(), result.size());
  22087. }
  22088. return body;
  22089. }
  22090. TEST(ClientConnectionTest, Basic) {
  22091. httplib::ClientConnection conn;
  22092. EXPECT_FALSE(conn.is_open());
  22093. conn.sock = 1;
  22094. EXPECT_TRUE(conn.is_open());
  22095. httplib::ClientConnection conn2(std::move(conn));
  22096. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22097. conn2.sock = INVALID_SOCKET;
  22098. }
  22099. // Unified test server for all stream::* tests
  22100. class StreamApiTest : public ::testing::Test {
  22101. protected:
  22102. void SetUp() override {
  22103. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22104. res.set_content("Hello World!", "text/plain");
  22105. });
  22106. svr_.Get("/echo-params",
  22107. [](const httplib::Request &req, httplib::Response &res) {
  22108. std::string r;
  22109. for (const auto &p : req.params) {
  22110. if (!r.empty()) r += "&";
  22111. r += p.first + "=" + p.second;
  22112. }
  22113. res.set_content(r, "text/plain");
  22114. });
  22115. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22116. res.set_content(req.body, req.get_header_value("Content-Type"));
  22117. });
  22118. svr_.Post("/echo-headers",
  22119. [](const httplib::Request &req, httplib::Response &res) {
  22120. std::string r;
  22121. for (const auto &h : req.headers)
  22122. r += h.first + ": " + h.second + "\n";
  22123. res.set_content(r, "text/plain");
  22124. });
  22125. svr_.Post("/echo-params",
  22126. [](const httplib::Request &req, httplib::Response &res) {
  22127. std::string r = "params:";
  22128. for (const auto &p : req.params)
  22129. r += p.first + "=" + p.second + ";";
  22130. res.set_content(r + " body:" + req.body, "text/plain");
  22131. });
  22132. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22133. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22134. });
  22135. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22136. res.set_content("PUT:" + req.body, "text/plain");
  22137. });
  22138. svr_.Patch("/echo",
  22139. [](const httplib::Request &req, httplib::Response &res) {
  22140. res.set_content("PATCH:" + req.body, "text/plain");
  22141. });
  22142. svr_.Delete(
  22143. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22144. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22145. "text/plain");
  22146. });
  22147. svr_.Get("/head-test",
  22148. [](const httplib::Request &, httplib::Response &res) {
  22149. res.set_content("body for HEAD", "text/plain");
  22150. });
  22151. svr_.Options("/options",
  22152. [](const httplib::Request &, httplib::Response &res) {
  22153. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22154. });
  22155. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22156. svr_.wait_until_ready();
  22157. }
  22158. void TearDown() override {
  22159. svr_.stop();
  22160. if (thread_.joinable()) thread_.join();
  22161. }
  22162. httplib::Server svr_;
  22163. std::thread thread_;
  22164. };
  22165. // stream::Get tests
  22166. TEST_F(StreamApiTest, GetBasic) {
  22167. httplib::Client cli(HOST, PORT);
  22168. auto result = httplib::stream::Get(cli, "/hello");
  22169. ASSERT_TRUE(result.is_valid());
  22170. EXPECT_EQ(200, result.status());
  22171. EXPECT_EQ("Hello World!", read_body(result));
  22172. }
  22173. TEST_F(StreamApiTest, GetWithParams) {
  22174. httplib::Client cli(HOST, PORT);
  22175. httplib::Params params{{"foo", "bar"}};
  22176. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22177. ASSERT_TRUE(result.is_valid());
  22178. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22179. }
  22180. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22181. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22182. httplib::Client cli(HOST, PORT);
  22183. cli.set_payload_max_length(0);
  22184. auto result = httplib::stream::Get(cli, "/hello");
  22185. ASSERT_TRUE(result.is_valid());
  22186. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22187. EXPECT_EQ("Hello World!", read_body(result));
  22188. }
  22189. #endif
  22190. TEST_F(StreamApiTest, GetConnectionError) {
  22191. httplib::Client cli(HOST, 9999);
  22192. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22193. }
  22194. TEST_F(StreamApiTest, Get404) {
  22195. httplib::Client cli(HOST, PORT);
  22196. auto result = httplib::stream::Get(cli, "/nonexistent");
  22197. EXPECT_TRUE(result.is_valid());
  22198. EXPECT_EQ(404, result.status());
  22199. }
  22200. // stream::Post tests
  22201. TEST_F(StreamApiTest, PostBasic) {
  22202. httplib::Client cli(HOST, PORT);
  22203. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22204. "application/json");
  22205. ASSERT_TRUE(result.is_valid());
  22206. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22207. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22208. }
  22209. TEST_F(StreamApiTest, PostWithHeaders) {
  22210. httplib::Client cli(HOST, PORT);
  22211. httplib::Headers headers{{"X-Custom", "value"}};
  22212. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22213. "text/plain");
  22214. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22215. }
  22216. TEST_F(StreamApiTest, PostWithParams) {
  22217. httplib::Client cli(HOST, PORT);
  22218. httplib::Params params{{"k", "v"}};
  22219. auto result =
  22220. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22221. auto body = read_body(result);
  22222. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22223. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22224. }
  22225. TEST_F(StreamApiTest, PostLarge) {
  22226. httplib::Client cli(HOST, PORT);
  22227. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22228. size_t total = 0;
  22229. while (result.next()) {
  22230. total += result.size();
  22231. }
  22232. EXPECT_EQ(100u * 1024u, total);
  22233. }
  22234. // stream::Put/Patch tests
  22235. TEST_F(StreamApiTest, PutAndPatch) {
  22236. httplib::Client cli(HOST, PORT);
  22237. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22238. EXPECT_EQ("PUT:test", read_body(put));
  22239. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22240. EXPECT_EQ("PATCH:test", read_body(patch));
  22241. }
  22242. // stream::Delete tests
  22243. TEST_F(StreamApiTest, Delete) {
  22244. httplib::Client cli(HOST, PORT);
  22245. auto del1 = httplib::stream::Delete(cli, "/resource");
  22246. EXPECT_EQ("Deleted", read_body(del1));
  22247. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22248. EXPECT_EQ("Deleted:data", read_body(del2));
  22249. }
  22250. // stream::Head/Options tests
  22251. TEST_F(StreamApiTest, HeadAndOptions) {
  22252. httplib::Client cli(HOST, PORT);
  22253. auto head = httplib::stream::Head(cli, "/head-test");
  22254. EXPECT_TRUE(head.is_valid());
  22255. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22256. auto opts = httplib::stream::Options(cli, "/options");
  22257. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22258. }
  22259. // SSL stream::* tests
  22260. #ifdef CPPHTTPLIB_SSL_ENABLED
  22261. class SSLStreamApiTest : public ::testing::Test {
  22262. protected:
  22263. void SetUp() override {
  22264. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22265. res.set_content("Hello SSL!", "text/plain");
  22266. });
  22267. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22268. res.set_content(req.body, "text/plain");
  22269. });
  22270. port_ = svr_.bind_to_any_port("127.0.0.1");
  22271. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22272. svr_.wait_until_ready();
  22273. }
  22274. void TearDown() override {
  22275. svr_.stop();
  22276. if (thread_.joinable()) thread_.join();
  22277. }
  22278. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22279. std::thread thread_;
  22280. int port_ = 0;
  22281. };
  22282. TEST_F(SSLStreamApiTest, GetAndPost) {
  22283. httplib::SSLClient cli("127.0.0.1", port_);
  22284. cli.enable_server_certificate_verification(false);
  22285. auto get = httplib::stream::Get(cli, "/hello");
  22286. EXPECT_EQ("Hello SSL!", read_body(get));
  22287. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22288. EXPECT_EQ("test", read_body(post));
  22289. }
  22290. #endif
  22291. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22292. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22293. // BodyReader
  22294. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22295. // Test that read timeout during streaming is detected
  22296. // Use a large content-length response where server delays mid-stream
  22297. Server svr;
  22298. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22299. // Send a large response with delay in the middle
  22300. res.set_content_provider(
  22301. 1000, // content_length
  22302. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22303. if (offset < 100) {
  22304. // Send first 100 bytes immediately
  22305. std::string data(100, 'A');
  22306. sink.write(data.c_str(), data.size());
  22307. return true;
  22308. }
  22309. // Then delay longer than client timeout
  22310. std::this_thread::sleep_for(std::chrono::seconds(3));
  22311. std::string data(900, 'B');
  22312. sink.write(data.c_str(), data.size());
  22313. return true;
  22314. });
  22315. });
  22316. auto port = 8091;
  22317. std::thread t([&]() { svr.listen("localhost", port); });
  22318. svr.wait_until_ready();
  22319. Client cli("localhost", port);
  22320. cli.set_read_timeout(1, 0); // 1 second timeout
  22321. auto handle = cli.open_stream("GET", "/slow-stream");
  22322. ASSERT_TRUE(handle.is_valid());
  22323. char buf[256];
  22324. ssize_t total = 0;
  22325. ssize_t n;
  22326. bool got_error = false;
  22327. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22328. total += n;
  22329. }
  22330. if (n < 0) {
  22331. got_error = true;
  22332. // Should be timeout or read error
  22333. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22334. handle.get_read_error() == Error::Read)
  22335. << "Actual error: " << to_string(handle.get_read_error());
  22336. }
  22337. // Either we got an error, or we got less data than expected
  22338. EXPECT_TRUE(got_error || total < 1000)
  22339. << "Expected timeout but got all " << total << " bytes";
  22340. svr.stop();
  22341. t.join();
  22342. }
  22343. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22344. // Test connection closed detection via BodyReader
  22345. Server svr;
  22346. std::atomic<bool> close_now{false};
  22347. svr.Get("/will-close", [&](const Request &, Response &res) {
  22348. res.set_content_provider(
  22349. 10000, // Large content_length that we won't fully send
  22350. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22351. if (offset < 100) {
  22352. std::string data(100, 'X');
  22353. sink.write(data.c_str(), data.size());
  22354. return true;
  22355. }
  22356. // Wait for signal then abort
  22357. while (!close_now) {
  22358. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22359. }
  22360. return false; // Abort - server will close connection
  22361. });
  22362. });
  22363. auto port = 8092;
  22364. std::thread t([&]() { svr.listen("localhost", port); });
  22365. svr.wait_until_ready();
  22366. Client cli("localhost", port);
  22367. auto handle = cli.open_stream("GET", "/will-close");
  22368. ASSERT_TRUE(handle.is_valid());
  22369. char buf[256];
  22370. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22371. EXPECT_GT(n, 0) << "First read should succeed";
  22372. // Signal server to close
  22373. close_now = true;
  22374. // Keep reading until error or EOF
  22375. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22376. // Keep reading
  22377. }
  22378. // Should get an error since content_length wasn't satisfied
  22379. if (n < 0) {
  22380. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22381. handle.get_read_error() == Error::Read)
  22382. << "Actual error: " << to_string(handle.get_read_error());
  22383. }
  22384. svr.stop();
  22385. t.join();
  22386. }
  22387. #ifdef CPPHTTPLIB_SSL_ENABLED
  22388. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22389. // Test that read timeout during SSL streaming is detected
  22390. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22391. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22392. res.set_content_provider(
  22393. 1000, "text/plain",
  22394. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22395. if (offset < 100) {
  22396. std::string data(100, 'A');
  22397. sink.write(data.c_str(), data.size());
  22398. return true;
  22399. }
  22400. std::this_thread::sleep_for(std::chrono::seconds(3));
  22401. std::string data(900, 'B');
  22402. sink.write(data.c_str(), data.size());
  22403. return true;
  22404. });
  22405. });
  22406. auto port = 8093;
  22407. std::thread t([&]() { svr.listen("localhost", port); });
  22408. svr.wait_until_ready();
  22409. SSLClient cli("localhost", port);
  22410. cli.enable_server_certificate_verification(false);
  22411. cli.set_read_timeout(1, 0); // 1 second timeout
  22412. auto handle = cli.open_stream("GET", "/slow-stream");
  22413. ASSERT_TRUE(handle.is_valid());
  22414. char buf[256];
  22415. ssize_t total = 0;
  22416. ssize_t n;
  22417. bool got_error = false;
  22418. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22419. total += n;
  22420. }
  22421. if (n < 0) {
  22422. got_error = true;
  22423. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22424. handle.get_read_error() == Error::Read)
  22425. << "Actual error: " << to_string(handle.get_read_error());
  22426. }
  22427. EXPECT_TRUE(got_error || total < 1000)
  22428. << "Expected timeout but got all " << total << " bytes";
  22429. svr.stop();
  22430. t.join();
  22431. }
  22432. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22433. // Test SSL connection closed detection
  22434. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22435. std::atomic<bool> close_now{false};
  22436. svr.Get("/will-close", [&](const Request &, Response &res) {
  22437. res.set_content_provider(
  22438. 10000, "text/plain",
  22439. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22440. if (offset < 100) {
  22441. std::string data(100, 'X');
  22442. sink.write(data.c_str(), data.size());
  22443. return true;
  22444. }
  22445. while (!close_now) {
  22446. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22447. }
  22448. return false;
  22449. });
  22450. });
  22451. auto port = 8094;
  22452. std::thread t([&]() { svr.listen("localhost", port); });
  22453. svr.wait_until_ready();
  22454. SSLClient cli("localhost", port);
  22455. cli.enable_server_certificate_verification(false);
  22456. auto handle = cli.open_stream("GET", "/will-close");
  22457. ASSERT_TRUE(handle.is_valid());
  22458. char buf[256];
  22459. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22460. EXPECT_GT(n, 0);
  22461. // Signal server to close
  22462. close_now = true;
  22463. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22464. // Keep reading
  22465. }
  22466. if (n < 0) {
  22467. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22468. handle.get_read_error() == Error::Read)
  22469. << "Actual error: " << to_string(handle.get_read_error());
  22470. }
  22471. svr.stop();
  22472. t.join();
  22473. }
  22474. #endif
  22475. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22476. using namespace httplib;
  22477. // Create a test file
  22478. const char *fname = "etag_testfile.txt";
  22479. const char *content = "etag-content";
  22480. {
  22481. std::ofstream ofs(fname);
  22482. ofs << content;
  22483. ASSERT_TRUE(ofs.good());
  22484. }
  22485. Server svr;
  22486. svr.set_mount_point("/static", ".");
  22487. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22488. svr.wait_until_ready();
  22489. Client cli(HOST, PORT);
  22490. // First request: should get 200 with ETag header
  22491. auto res1 = cli.Get("/static/etag_testfile.txt");
  22492. ASSERT_TRUE(res1);
  22493. ASSERT_EQ(200, res1->status);
  22494. ASSERT_TRUE(res1->has_header("ETag"));
  22495. std::string etag = res1->get_header_value("ETag");
  22496. EXPECT_FALSE(etag.empty());
  22497. // Verify ETag format: W/"hex-hex"
  22498. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22499. EXPECT_EQ('W', etag[0]);
  22500. EXPECT_EQ('/', etag[1]);
  22501. EXPECT_EQ('"', etag[2]);
  22502. EXPECT_EQ('"', etag.back());
  22503. // Exact match: expect 304 Not Modified
  22504. Headers h2 = {{"If-None-Match", etag}};
  22505. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22506. ASSERT_TRUE(res2);
  22507. EXPECT_EQ(304, res2->status);
  22508. // Wildcard match: expect 304 Not Modified
  22509. Headers h3 = {{"If-None-Match", "*"}};
  22510. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22511. ASSERT_TRUE(res3);
  22512. EXPECT_EQ(304, res3->status);
  22513. // Non-matching ETag: expect 200
  22514. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22515. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22516. ASSERT_TRUE(res4);
  22517. EXPECT_EQ(200, res4->status);
  22518. // Multiple ETags with one matching: expect 304
  22519. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22520. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22521. ASSERT_TRUE(res5);
  22522. EXPECT_EQ(304, res5->status);
  22523. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22524. // that equivalent to the single comma-separated list above, so the match on
  22525. // the second line must still be found.
  22526. Headers h6;
  22527. h6.emplace("If-None-Match", "W/\"other\"");
  22528. h6.emplace("If-None-Match", etag);
  22529. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22530. ASSERT_TRUE(res6);
  22531. EXPECT_EQ(304, res6->status);
  22532. svr.stop();
  22533. t.join();
  22534. std::remove(fname);
  22535. }
  22536. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22537. using namespace httplib;
  22538. Server svr;
  22539. svr.set_mount_point("/static", ".");
  22540. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22541. svr.wait_until_ready();
  22542. Client cli(HOST, PORT);
  22543. // Send If-None-Match: * to a non-existent file
  22544. Headers h = {{"If-None-Match", "*"}};
  22545. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22547. EXPECT_EQ(404, res->status);
  22548. svr.stop();
  22549. t.join();
  22550. }
  22551. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22552. using namespace httplib;
  22553. // Create a test file
  22554. const char *fname = "etag_boundary_testfile.txt";
  22555. const char *content = "boundary-test";
  22556. {
  22557. std::ofstream ofs(fname);
  22558. ofs << content;
  22559. ASSERT_TRUE(ofs.good());
  22560. }
  22561. Server svr;
  22562. svr.set_mount_point("/static", ".");
  22563. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22564. svr.wait_until_ready();
  22565. Client cli(HOST, PORT);
  22566. // Get the actual ETag
  22567. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22568. ASSERT_TRUE(res1);
  22569. ASSERT_EQ(200, res1->status);
  22570. ASSERT_TRUE(res1->has_header("ETag"));
  22571. std::string etag = res1->get_header_value("ETag");
  22572. // Test 1: Very long ETag value (longer than actual ETag)
  22573. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22574. Headers h1 = {{"If-None-Match", "W/"
  22575. "\"very-long-etag-value-that-is-much-longer-"
  22576. "than-the-actual-etag-value\""}};
  22577. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22578. ASSERT_TRUE(res2);
  22579. EXPECT_EQ(200, res2->status); // Should not match
  22580. // Test 2: Long string followed by wildcard
  22581. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22582. // string)
  22583. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22584. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22585. ASSERT_TRUE(res3);
  22586. EXPECT_EQ(304, res3->status); // Should match on "*"
  22587. // Test 3: Wildcard followed by long string
  22588. // Should match on "*" immediately and return 304
  22589. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22590. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22591. ASSERT_TRUE(res4);
  22592. EXPECT_EQ(304, res4->status); // Should match on "*"
  22593. // Test 4: Multiple long non-matching values
  22594. // Should NOT match and return 200 (test that all comparisons are safe)
  22595. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22596. "W/\"second-long-non-matching-value\", "
  22597. "W/\"third-long-non-matching-value\""}};
  22598. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22599. ASSERT_TRUE(res5);
  22600. EXPECT_EQ(200, res5->status); // Should not match
  22601. // Test 5: Single character that is not "*" (edge case)
  22602. Headers h5 = {{"If-None-Match", "X"}};
  22603. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22604. ASSERT_TRUE(res6);
  22605. EXPECT_EQ(200, res6->status); // Should not match
  22606. svr.stop();
  22607. t.join();
  22608. std::remove(fname);
  22609. }
  22610. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22611. using namespace httplib;
  22612. // Create a test file
  22613. const char *fname = "ims_testfile.txt";
  22614. const char *content = "if-modified-since-test";
  22615. {
  22616. std::ofstream ofs(fname);
  22617. ofs << content;
  22618. ASSERT_TRUE(ofs.good());
  22619. }
  22620. Server svr;
  22621. svr.set_mount_point("/static", ".");
  22622. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22623. svr.wait_until_ready();
  22624. Client cli(HOST, PORT);
  22625. // First request: should get 200 with Last-Modified header
  22626. auto res1 = cli.Get("/static/ims_testfile.txt");
  22627. ASSERT_TRUE(res1);
  22628. ASSERT_EQ(200, res1->status);
  22629. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22630. std::string last_modified = res1->get_header_value("Last-Modified");
  22631. EXPECT_FALSE(last_modified.empty());
  22632. // If-Modified-Since with same time: expect 304
  22633. Headers h2 = {{"If-Modified-Since", last_modified}};
  22634. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22635. ASSERT_TRUE(res2);
  22636. EXPECT_EQ(304, res2->status);
  22637. // If-Modified-Since with future time: expect 304
  22638. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22639. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22640. ASSERT_TRUE(res3);
  22641. EXPECT_EQ(304, res3->status);
  22642. // If-Modified-Since with past time: expect 200
  22643. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22644. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22645. ASSERT_TRUE(res4);
  22646. EXPECT_EQ(200, res4->status);
  22647. // If-None-Match takes precedence over If-Modified-Since
  22648. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22649. ASSERT_TRUE(res1->has_header("ETag"));
  22650. std::string etag = res1->get_header_value("ETag");
  22651. Headers h5 = {{"If-None-Match", etag},
  22652. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22653. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22654. ASSERT_TRUE(res5);
  22655. EXPECT_EQ(304, res5->status);
  22656. svr.stop();
  22657. t.join();
  22658. std::remove(fname);
  22659. }
  22660. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22661. using namespace httplib;
  22662. Server svr;
  22663. // Endpoint that returns compressible content
  22664. svr.Get("/compressible", [](const Request &, Response &res) {
  22665. // Return a large enough body to trigger compression
  22666. std::string body(1000, 'a');
  22667. res.set_content(body, "text/plain");
  22668. });
  22669. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22670. svr.wait_until_ready();
  22671. Client cli(HOST, PORT);
  22672. // Request with gzip support: should get Vary header when compressed
  22673. cli.set_compress(true);
  22674. auto res1 = cli.Get("/compressible");
  22675. ASSERT_TRUE(res1);
  22676. EXPECT_EQ(200, res1->status);
  22677. // If Content-Encoding is set, Vary should also be set
  22678. if (res1->has_header("Content-Encoding")) {
  22679. EXPECT_TRUE(res1->has_header("Vary"));
  22680. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22681. }
  22682. // Request without Accept-Encoding header: should not have compression
  22683. Headers h_no_compress;
  22684. auto res2 = cli.Get("/compressible", h_no_compress);
  22685. ASSERT_TRUE(res2);
  22686. EXPECT_EQ(200, res2->status);
  22687. // Verify Vary header is present when compression is applied
  22688. // (the exact behavior depends on server configuration)
  22689. svr.stop();
  22690. t.join();
  22691. }
  22692. TEST(ETagTest, IfRangeWithETag) {
  22693. using namespace httplib;
  22694. // Create a test file with known content
  22695. const char *fname = "if_range_testfile.txt";
  22696. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22697. {
  22698. std::ofstream ofs(fname);
  22699. ofs << content;
  22700. ASSERT_TRUE(ofs.good());
  22701. }
  22702. Server svr;
  22703. svr.set_mount_point("/static", ".");
  22704. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22705. svr.wait_until_ready();
  22706. Client cli(HOST, PORT);
  22707. // First request: get ETag
  22708. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22709. ASSERT_TRUE(res1);
  22710. ASSERT_EQ(200, res1->status);
  22711. ASSERT_TRUE(res1->has_header("ETag"));
  22712. std::string etag = res1->get_header_value("ETag");
  22713. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22714. // Since our server generates weak ETags (W/"..."), If-Range with our
  22715. // ETag should NOT result in partial content - it should return full content.
  22716. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22717. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22718. ASSERT_TRUE(res2);
  22719. // Weak ETag in If-Range -> full content (200), not partial (206)
  22720. EXPECT_EQ(200, res2->status);
  22721. EXPECT_EQ(content, res2->body);
  22722. EXPECT_FALSE(res2->has_header("Content-Range"));
  22723. // Range request with non-matching If-Range (ETag): should get 200 (full
  22724. // content)
  22725. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22726. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22727. ASSERT_TRUE(res3);
  22728. EXPECT_EQ(200, res3->status);
  22729. EXPECT_EQ(content, res3->body);
  22730. EXPECT_FALSE(res3->has_header("Content-Range"));
  22731. // Range request with strong ETag (hypothetical - our server doesn't generate
  22732. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22733. // should return full content)
  22734. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22735. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22736. ASSERT_TRUE(res4);
  22737. EXPECT_EQ(200, res4->status);
  22738. EXPECT_EQ(content, res4->body);
  22739. EXPECT_FALSE(res4->has_header("Content-Range"));
  22740. svr.stop();
  22741. t.join();
  22742. std::remove(fname);
  22743. }
  22744. TEST(ETagTest, IfRangeWithDate) {
  22745. using namespace httplib;
  22746. // Create a test file
  22747. const char *fname = "if_range_date_testfile.txt";
  22748. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22749. {
  22750. std::ofstream ofs(fname);
  22751. ofs << content;
  22752. ASSERT_TRUE(ofs.good());
  22753. }
  22754. Server svr;
  22755. svr.set_mount_point("/static", ".");
  22756. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22757. svr.wait_until_ready();
  22758. Client cli(HOST, PORT);
  22759. // First request: get Last-Modified
  22760. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22761. ASSERT_TRUE(res1);
  22762. ASSERT_EQ(200, res1->status);
  22763. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22764. std::string last_modified = res1->get_header_value("Last-Modified");
  22765. // Range request with matching If-Range (date): should get 206
  22766. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22767. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22768. ASSERT_TRUE(res2);
  22769. EXPECT_EQ(206, res2->status);
  22770. EXPECT_EQ("FGHIJ", res2->body);
  22771. // Range request with old If-Range date: should get 200 (full content)
  22772. Headers h3 = {{"Range", "bytes=5-9"},
  22773. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22774. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22775. ASSERT_TRUE(res3);
  22776. EXPECT_EQ(200, res3->status);
  22777. EXPECT_EQ(content, res3->body);
  22778. // Range request with future If-Range date: should get 206
  22779. Headers h4 = {{"Range", "bytes=0-4"},
  22780. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22781. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22782. ASSERT_TRUE(res4);
  22783. EXPECT_EQ(206, res4->status);
  22784. EXPECT_EQ("ABCDE", res4->body);
  22785. svr.stop();
  22786. t.join();
  22787. std::remove(fname);
  22788. }
  22789. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22790. using namespace httplib;
  22791. const char *fname = "etag_malformed.txt";
  22792. const char *content = "malformed-etag";
  22793. {
  22794. std::ofstream ofs(fname);
  22795. ofs << content;
  22796. ASSERT_TRUE(ofs.good());
  22797. }
  22798. Server svr;
  22799. svr.set_mount_point("/static", ".");
  22800. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22801. svr.wait_until_ready();
  22802. Client cli(HOST, PORT);
  22803. // baseline: should get 200 and an ETag
  22804. auto res1 = cli.Get("/static/etag_malformed.txt");
  22805. ASSERT_TRUE(res1);
  22806. ASSERT_EQ(200, res1->status);
  22807. ASSERT_TRUE(res1->has_header("ETag"));
  22808. // Malformed ETag value (missing quotes) should be treated as non-matching
  22809. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22810. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22811. ASSERT_TRUE(res_bad);
  22812. EXPECT_EQ(200, res_bad->status);
  22813. // Whitespace-only header value should be considered invalid / non-matching
  22814. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22815. "Host: localhost\r\n"
  22816. "If-None-Match: \r\n"
  22817. "Connection: close\r\n"
  22818. "\r\n";
  22819. std::string out;
  22820. ASSERT_TRUE(send_request(5, raw_req, &out));
  22821. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22822. svr.stop();
  22823. t.join();
  22824. std::remove(fname);
  22825. }
  22826. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22827. using namespace httplib;
  22828. const char *fname = "ims_invalid_format.txt";
  22829. const char *content = "ims-bad-format";
  22830. {
  22831. std::ofstream ofs(fname);
  22832. ofs << content;
  22833. ASSERT_TRUE(ofs.good());
  22834. }
  22835. Server svr;
  22836. svr.set_mount_point("/static", ".");
  22837. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22838. svr.wait_until_ready();
  22839. Client cli(HOST, PORT);
  22840. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22841. ASSERT_TRUE(res1);
  22842. ASSERT_EQ(200, res1->status);
  22843. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22844. // If-Modified-Since with invalid format should not result in 304
  22845. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22846. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22847. ASSERT_TRUE(res_bad);
  22848. EXPECT_EQ(200, res_bad->status);
  22849. // If-Range with invalid date format should be treated as mismatch -> full
  22850. // content (200)
  22851. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22852. {"If-Range", "invalid-date"}};
  22853. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22854. ASSERT_TRUE(res_ifrange);
  22855. EXPECT_EQ(200, res_ifrange->status);
  22856. svr.stop();
  22857. t.join();
  22858. std::remove(fname);
  22859. }
  22860. TEST(ETagTest, IfRangeWithMalformedETag) {
  22861. using namespace httplib;
  22862. const char *fname = "ifrange_malformed.txt";
  22863. const std::string content = "0123456789";
  22864. {
  22865. std::ofstream ofs(fname);
  22866. ofs << content;
  22867. ASSERT_TRUE(ofs.good());
  22868. }
  22869. Server svr;
  22870. svr.set_mount_point("/static", ".");
  22871. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22872. svr.wait_until_ready();
  22873. Client cli(HOST, PORT);
  22874. // First request: get ETag
  22875. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22876. ASSERT_TRUE(res1);
  22877. ASSERT_EQ(200, res1->status);
  22878. ASSERT_TRUE(res1->has_header("ETag"));
  22879. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22880. // full content (200)
  22881. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22882. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22883. ASSERT_TRUE(res2);
  22884. EXPECT_EQ(200, res2->status);
  22885. EXPECT_EQ(content, res2->body);
  22886. svr.stop();
  22887. t.join();
  22888. std::remove(fname);
  22889. }
  22890. TEST(ETagTest, ExtremeLargeDateValues) {
  22891. using namespace httplib;
  22892. const char *fname = "ims_extreme_date.txt";
  22893. const char *content = "ims-extreme-date";
  22894. {
  22895. std::ofstream ofs(fname);
  22896. ofs << content;
  22897. ASSERT_TRUE(ofs.good());
  22898. }
  22899. Server svr;
  22900. svr.set_mount_point("/static", ".");
  22901. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22902. svr.wait_until_ready();
  22903. Client cli(HOST, PORT);
  22904. auto res1 = cli.Get(std::string("/static/") + fname);
  22905. ASSERT_TRUE(res1);
  22906. ASSERT_EQ(200, res1->status);
  22907. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22908. // Extremely large year that may overflow date parsing routines.
  22909. Headers h_large_date = {
  22910. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22911. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22912. ASSERT_TRUE(res_bad);
  22913. // Expect server to treat this as invalid/mismatch and return full content
  22914. EXPECT_EQ(200, res_bad->status);
  22915. // If-Range with extremely large date should be treated as mismatch -> full
  22916. // content (200)
  22917. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22918. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22919. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22920. ASSERT_TRUE(res_ifrange);
  22921. EXPECT_EQ(200, res_ifrange->status);
  22922. svr.stop();
  22923. t.join();
  22924. std::remove(fname);
  22925. }
  22926. TEST(ETagTest, NegativeFileModificationTime) {
  22927. using namespace httplib;
  22928. const char *fname = "ims_negative_mtime.txt";
  22929. const std::string content = "negative-mtime";
  22930. {
  22931. std::ofstream ofs(fname);
  22932. ofs << content;
  22933. ASSERT_TRUE(ofs.good());
  22934. }
  22935. // Try to set file mtime to a negative value. This may fail on some
  22936. // platforms/filesystems; if it fails, the test will still verify server
  22937. // behaves safely by performing a regular conditional request.
  22938. #if defined(__APPLE__) || defined(__linux__)
  22939. bool set_negative = false;
  22940. do {
  22941. struct timeval times[2];
  22942. // access time: now
  22943. times[0].tv_sec = time(nullptr);
  22944. times[0].tv_usec = 0;
  22945. // modification time: negative (e.g., -1)
  22946. times[1].tv_sec = -1;
  22947. times[1].tv_usec = 0;
  22948. if (utimes(fname, times) == 0) { set_negative = true; }
  22949. } while (0);
  22950. #else
  22951. bool set_negative = false;
  22952. #endif
  22953. Server svr;
  22954. svr.set_mount_point("/static", ".");
  22955. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22956. svr.wait_until_ready();
  22957. Client cli(HOST, PORT);
  22958. auto res1 = cli.Get(std::string("/static/") + fname);
  22959. ASSERT_TRUE(res1);
  22960. ASSERT_EQ(200, res1->status);
  22961. bool has_last_modified = res1->has_header("Last-Modified");
  22962. std::string last_modified;
  22963. if (has_last_modified) {
  22964. last_modified = res1->get_header_value("Last-Modified");
  22965. }
  22966. if (set_negative) {
  22967. // If we successfully set a negative mtime, ensure server returns a
  22968. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  22969. // with an old date and ensure server handles it without crash.
  22970. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  22971. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  22972. ASSERT_TRUE(res2);
  22973. // Behavior may vary; at minimum ensure server responds (200 or 304).
  22974. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  22975. } else {
  22976. // Could not set negative mtime on this platform; fall back to verifying
  22977. // that normal invalid/malformed dates are treated safely (non-304).
  22978. Headers h_bad_date = {
  22979. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22980. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  22981. ASSERT_TRUE(res_bad);
  22982. EXPECT_EQ(200, res_bad->status);
  22983. }
  22984. svr.stop();
  22985. t.join();
  22986. std::remove(fname);
  22987. }
  22988. //==============================================================================
  22989. // Integration Tests with Server
  22990. //==============================================================================
  22991. class SSEIntegrationTest : public ::testing::Test {
  22992. protected:
  22993. void SetUp() override {
  22994. stop_server_.store(false);
  22995. events_.clear();
  22996. server_ = httplib::detail::make_unique<Server>();
  22997. setup_server();
  22998. start_server();
  22999. }
  23000. void TearDown() override {
  23001. stop_server_.store(true);
  23002. event_cv_.notify_all();
  23003. server_->stop();
  23004. if (server_thread_.joinable()) { server_thread_.join(); }
  23005. }
  23006. void setup_server() {
  23007. // Simple SSE endpoint
  23008. server_->Get("/events", [this](const Request &req, Response &res) {
  23009. auto last_id = req.get_header_value("Last-Event-ID");
  23010. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  23011. res.set_chunked_content_provider(
  23012. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23013. std::unique_lock<std::mutex> lock(event_mutex_);
  23014. if (event_cv_.wait_for(
  23015. lock, std::chrono::milliseconds(200), [this] {
  23016. return !events_.empty() || stop_server_.load();
  23017. })) {
  23018. if (stop_server_.load()) { return false; }
  23019. if (!events_.empty()) {
  23020. std::string event = events_.front();
  23021. events_.erase(events_.begin());
  23022. sink.write(event.data(), event.size());
  23023. return true;
  23024. }
  23025. }
  23026. return !stop_server_.load();
  23027. });
  23028. });
  23029. // Endpoint that returns error
  23030. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23031. res.status = 500;
  23032. res.set_content("Internal Server Error", "text/plain");
  23033. });
  23034. // Endpoint for custom event types
  23035. server_->Get("/custom-events", [](const Request &, Response &res) {
  23036. res.set_chunked_content_provider(
  23037. "text/event-stream", [](size_t offset, DataSink &sink) {
  23038. if (offset == 0) {
  23039. std::string event = "event: update\ndata: updated\n\n"
  23040. "event: delete\ndata: deleted\n\n";
  23041. sink.write(event.data(), event.size());
  23042. }
  23043. return false; // End stream after sending
  23044. });
  23045. });
  23046. }
  23047. void start_server() {
  23048. port_ = server_->bind_to_any_port(HOST);
  23049. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23050. // Wait for server to start
  23051. while (!server_->is_running()) {
  23052. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23053. }
  23054. }
  23055. int get_port() const { return port_; }
  23056. void send_event(const std::string &event) {
  23057. std::lock_guard<std::mutex> lock(event_mutex_);
  23058. events_.push_back(event);
  23059. event_cv_.notify_all();
  23060. }
  23061. std::unique_ptr<Server> server_;
  23062. std::thread server_thread_;
  23063. std::mutex event_mutex_;
  23064. std::condition_variable event_cv_;
  23065. std::vector<std::string> events_;
  23066. std::atomic<bool> stop_server_{false};
  23067. std::string last_received_event_id_;
  23068. int port_ = 0;
  23069. };
  23070. //==============================================================================
  23071. // SSE Parser Tests
  23072. //==============================================================================
  23073. struct SSEParseResult {
  23074. std::vector<sse::SSEMessage> events;
  23075. std::vector<std::string> ids;
  23076. std::vector<int> retries;
  23077. bool ok = true;
  23078. std::string trace; // Every handler call in order
  23079. };
  23080. static SSEParseResult
  23081. sse_parse(const std::vector<std::string> &chunks,
  23082. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23083. SSEParseResult r;
  23084. detail::SSEParser parser(
  23085. [&](const sse::SSEMessage &msg) {
  23086. r.events.push_back(msg);
  23087. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23088. },
  23089. [&](const std::string &id) {
  23090. r.ids.push_back(id);
  23091. r.trace += "id[" + id + "]";
  23092. },
  23093. [&](int retry_ms) {
  23094. r.retries.push_back(retry_ms);
  23095. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23096. },
  23097. max_event_length);
  23098. for (const auto &chunk : chunks) {
  23099. if (!parser.parse(chunk.data(), chunk.size())) {
  23100. r.ok = false;
  23101. break;
  23102. }
  23103. }
  23104. return r;
  23105. }
  23106. static SSEParseResult sse_parse(const std::string &stream) {
  23107. return sse_parse(std::vector<std::string>{stream});
  23108. }
  23109. TEST(SSEParserTest, SingleLineData) {
  23110. auto r = sse_parse("data: hello\n\n");
  23111. ASSERT_EQ(r.events.size(), 1u);
  23112. EXPECT_EQ(r.events[0].data, "hello");
  23113. EXPECT_EQ(r.events[0].event, "message");
  23114. }
  23115. TEST(SSEParserTest, MultiLineData) {
  23116. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23117. ASSERT_EQ(r.events.size(), 1u);
  23118. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23119. }
  23120. TEST(SSEParserTest, CustomEventType) {
  23121. auto r = sse_parse("event: update\ndata: payload\n\n");
  23122. ASSERT_EQ(r.events.size(), 1u);
  23123. EXPECT_EQ(r.events[0].event, "update");
  23124. EXPECT_EQ(r.events[0].data, "payload");
  23125. }
  23126. TEST(SSEParserTest, EventIdHandling) {
  23127. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23128. ASSERT_EQ(r.events.size(), 1u);
  23129. EXPECT_EQ(r.events[0].id, "12345");
  23130. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23131. }
  23132. TEST(SSEParserTest, EmptyEventId) {
  23133. auto r = sse_parse("id:\ndata: test\n\n");
  23134. ASSERT_EQ(r.events.size(), 1u);
  23135. EXPECT_EQ(r.events[0].id, "");
  23136. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23137. }
  23138. TEST(SSEParserTest, CommentsIgnored) {
  23139. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23140. ASSERT_EQ(r.events.size(), 1u);
  23141. EXPECT_EQ(r.events[0].data, "hello");
  23142. EXPECT_EQ(r.events[0].event, "message");
  23143. }
  23144. TEST(SSEParserTest, ColonInValue) {
  23145. auto r = sse_parse("data: hello:world:test\n\n");
  23146. ASSERT_EQ(r.events.size(), 1u);
  23147. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23148. }
  23149. TEST(SSEParserTest, FieldNameOnly) {
  23150. // A line without a colon is a field name with an empty value
  23151. auto r = sse_parse("data\n\n");
  23152. ASSERT_EQ(r.events.size(), 1u);
  23153. EXPECT_EQ(r.events[0].data, "");
  23154. }
  23155. TEST(SSEParserTest, TrailingCarriageReturn) {
  23156. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23157. ASSERT_EQ(r.events.size(), 1u);
  23158. EXPECT_EQ(r.events[0].event, "update");
  23159. EXPECT_EQ(r.events[0].data, "hello");
  23160. }
  23161. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23162. auto r = sse_parse("data\r\n\r\n");
  23163. ASSERT_EQ(r.events.size(), 1u);
  23164. EXPECT_EQ(r.events[0].data, "");
  23165. }
  23166. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23167. auto r = sse_parse("event: update\rdata: hello\r\r");
  23168. ASSERT_EQ(r.events.size(), 1u);
  23169. EXPECT_EQ(r.events[0].event, "update");
  23170. EXPECT_EQ(r.events[0].data, "hello");
  23171. }
  23172. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23173. // Chunk boundaries fall inside every \r\n and right before the first one
  23174. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23175. "\ndata: hello\r", "\n\r", "\n"});
  23176. ASSERT_EQ(r.events.size(), 1u);
  23177. EXPECT_EQ(r.events[0].event, "update");
  23178. EXPECT_EQ(r.events[0].data, "hello");
  23179. }
  23180. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23181. // Only a BOM at the start of the stream is ignored
  23182. auto r = sse_parse("\xEF\xBB\xBF"
  23183. "data: first\n\n"
  23184. "\xEF\xBB\xBF"
  23185. "data: second\n\n");
  23186. ASSERT_EQ(r.events.size(), 1u);
  23187. EXPECT_EQ(r.events[0].data, "first");
  23188. }
  23189. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23190. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23191. ASSERT_EQ(r.events.size(), 1u);
  23192. EXPECT_EQ(r.events[0].data, "hello");
  23193. EXPECT_EQ(r.events[0].event, "message");
  23194. }
  23195. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23196. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23197. ASSERT_EQ(r.events.size(), 2u);
  23198. EXPECT_EQ(r.events[0].data, "hello");
  23199. EXPECT_EQ(r.events[1].data, "hello");
  23200. }
  23201. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23202. // An event without data is not dispatched, and its type must not leak
  23203. // into the next event
  23204. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23205. ASSERT_EQ(r.events.size(), 1u);
  23206. EXPECT_EQ(r.events[0].event, "message");
  23207. EXPECT_EQ(r.events[0].data, "hello");
  23208. }
  23209. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23210. // Also when the empty field replaces an earlier type
  23211. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23212. ASSERT_EQ(r.events.size(), 2u);
  23213. EXPECT_EQ(r.events[0].event, "message");
  23214. EXPECT_EQ(r.events[1].event, "message");
  23215. }
  23216. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23217. auto r = sse_parse("id: 42\n\n");
  23218. EXPECT_TRUE(r.events.empty());
  23219. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23220. }
  23221. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23222. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23223. ASSERT_EQ(r.events.size(), 2u);
  23224. EXPECT_EQ(r.events[0].id, "1");
  23225. EXPECT_EQ(r.events[1].id, "");
  23226. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23227. }
  23228. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23229. // Ids that cannot be carried in a Last-Event-ID header
  23230. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23231. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23232. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23233. }
  23234. TEST(SSEParserTest, RetryDigitsOnly) {
  23235. auto r = sse_parse("retry: 1000\n");
  23236. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23237. // A value that is not all ASCII digits, or does not fit, is ignored
  23238. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23239. EXPECT_TRUE(r.retries.empty());
  23240. }
  23241. TEST(SSEParserTest, CompleteEventParsing) {
  23242. auto r = sse_parse("event: notification\nid: evt-42\n"
  23243. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23244. ASSERT_EQ(r.events.size(), 1u);
  23245. EXPECT_EQ(r.events[0].event, "notification");
  23246. EXPECT_EQ(r.events[0].id, "evt-42");
  23247. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23248. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23249. }
  23250. TEST(SSEParserTest, IncompleteEventNotReported) {
  23251. // An event still waiting for its blank line when the stream ends is
  23252. // discarded per the SSE spec
  23253. auto r = sse_parse("id: 1\ndata: x\n");
  23254. EXPECT_TRUE(r.events.empty());
  23255. EXPECT_TRUE(r.ids.empty());
  23256. }
  23257. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23258. const std::vector<std::string> streams = {
  23259. "\xEF\xBB\xBF"
  23260. "data: bom\r\n\r\n",
  23261. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23262. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23263. };
  23264. for (const auto &stream : streams) {
  23265. auto expected = sse_parse(stream).trace;
  23266. ASSERT_FALSE(expected.empty());
  23267. for (size_t i = 0; i <= stream.size(); i++) {
  23268. auto r = sse_parse(
  23269. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23270. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23271. }
  23272. std::vector<std::string> bytes;
  23273. for (auto c : stream) {
  23274. bytes.emplace_back(1, c);
  23275. }
  23276. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23277. }
  23278. }
  23279. TEST(SSEParserTest, MaxEventLength) {
  23280. // A line still waiting for its end
  23281. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23282. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23283. // Data accumulated over the lines of one event
  23284. EXPECT_TRUE(
  23285. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23286. EXPECT_FALSE(
  23287. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23288. // 0 means no limit
  23289. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23290. // Events completed in the same chunk are still reported
  23291. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23292. EXPECT_FALSE(r.ok);
  23293. ASSERT_EQ(r.events.size(), 1u);
  23294. EXPECT_EQ(r.events[0].data, "a");
  23295. }
  23296. TEST(SSEMessageTest, Clear) {
  23297. sse::SSEMessage msg;
  23298. msg.event = "custom";
  23299. msg.data = "some data";
  23300. msg.id = "123";
  23301. msg.clear();
  23302. EXPECT_EQ(msg.event, "message");
  23303. EXPECT_EQ(msg.data, "");
  23304. EXPECT_EQ(msg.id, "");
  23305. }
  23306. //==============================================================================
  23307. // SSE Integration Tests
  23308. //==============================================================================
  23309. // Test: Successful connection and on_open callback
  23310. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23311. // Add a simple endpoint that sends one event and closes
  23312. server_->Get("/simple-event", [](const Request &, Response &res) {
  23313. res.set_chunked_content_provider(
  23314. "text/event-stream", [](size_t offset, DataSink &sink) {
  23315. if (offset == 0) {
  23316. std::string event = "data: hello\n\n";
  23317. sink.write(event.data(), event.size());
  23318. }
  23319. return false; // Close stream after sending
  23320. });
  23321. });
  23322. Client client("localhost", get_port());
  23323. sse::SSEClient sse(client, "/simple-event");
  23324. std::atomic<bool> open_called{false};
  23325. std::atomic<bool> message_received{false};
  23326. sse.on_open([&open_called]() { open_called.store(true); });
  23327. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23328. if (msg.data == "hello") { message_received.store(true); }
  23329. });
  23330. sse.set_reconnect_interval(100);
  23331. sse.set_max_reconnect_attempts(1);
  23332. // Start async
  23333. sse.start_async();
  23334. // Wait for message to be processed
  23335. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23336. sse.stop();
  23337. EXPECT_TRUE(open_called.load());
  23338. EXPECT_TRUE(message_received.load());
  23339. }
  23340. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23341. // A data line that never ends.
  23342. server_->Get("/endless-line", [](const Request &, Response &res) {
  23343. res.set_chunked_content_provider(
  23344. "text/event-stream", [](size_t offset, DataSink &sink) {
  23345. if (offset == 0) { sink.write("data: ", 6); }
  23346. std::string chunk(64 * 1024, 'A');
  23347. return sink.write(chunk.data(), chunk.size());
  23348. });
  23349. });
  23350. Client client("localhost", get_port());
  23351. sse::SSEClient sse(client, "/endless-line");
  23352. std::atomic<bool> too_long{false};
  23353. sse.on_error([&](Error err) {
  23354. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23355. });
  23356. sse.set_max_reconnect_attempts(1);
  23357. sse.start_async();
  23358. for (int i = 0; i < 500 && !too_long; i++) {
  23359. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23360. }
  23361. sse.stop();
  23362. EXPECT_TRUE(too_long);
  23363. }
  23364. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23365. // Far more in all than the client's payload limit below.
  23366. server_->Get("/many-events", [](const Request &, Response &res) {
  23367. res.set_chunked_content_provider(
  23368. "text/event-stream", [](size_t offset, DataSink &sink) {
  23369. if (offset == 0) {
  23370. std::string events;
  23371. for (int i = 0; i < 1000; i++) {
  23372. events += "data: message\n\n";
  23373. }
  23374. sink.write(events.data(), events.size());
  23375. }
  23376. return false;
  23377. });
  23378. });
  23379. Client client("localhost", get_port());
  23380. client.set_payload_max_length(1024);
  23381. sse::SSEClient sse(client, "/many-events");
  23382. std::atomic<int> messages{0};
  23383. std::atomic<bool> too_large{false};
  23384. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23385. sse.on_error([&](Error err) {
  23386. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23387. });
  23388. sse.set_max_reconnect_attempts(1);
  23389. sse.start_async();
  23390. for (int i = 0; i < 500 && messages < 1000; i++) {
  23391. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23392. }
  23393. sse.stop();
  23394. EXPECT_GE(messages.load(), 1000);
  23395. EXPECT_FALSE(too_large);
  23396. }
  23397. // Test: on_message callback
  23398. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23399. // Endpoint that sends multiple events then closes
  23400. server_->Get("/multi-event", [](const Request &, Response &res) {
  23401. res.set_chunked_content_provider(
  23402. "text/event-stream", [](size_t offset, DataSink &sink) {
  23403. if (offset == 0) {
  23404. std::string events = "data: message1\n\ndata: message2\n\n";
  23405. sink.write(events.data(), events.size());
  23406. }
  23407. return false;
  23408. });
  23409. });
  23410. Client client("localhost", get_port());
  23411. sse::SSEClient sse(client, "/multi-event");
  23412. std::vector<std::string> received_messages;
  23413. std::mutex messages_mutex;
  23414. sse.on_message([&](const sse::SSEMessage &msg) {
  23415. std::lock_guard<std::mutex> lock(messages_mutex);
  23416. received_messages.push_back(msg.data);
  23417. });
  23418. sse.set_reconnect_interval(100);
  23419. sse.set_max_reconnect_attempts(1);
  23420. sse.start_async();
  23421. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23422. sse.stop();
  23423. std::lock_guard<std::mutex> lock(messages_mutex);
  23424. EXPECT_GE(received_messages.size(), 2u);
  23425. if (received_messages.size() >= 2) {
  23426. EXPECT_EQ(received_messages[0], "message1");
  23427. EXPECT_EQ(received_messages[1], "message2");
  23428. }
  23429. }
  23430. // Test: on_event for specific types
  23431. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23432. Client client("localhost", get_port());
  23433. sse::SSEClient sse(client, "/custom-events");
  23434. std::atomic<bool> update_received{false};
  23435. std::atomic<bool> delete_received{false};
  23436. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23437. if (msg.data == "updated") { update_received.store(true); }
  23438. });
  23439. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23440. if (msg.data == "deleted") { delete_received.store(true); }
  23441. });
  23442. sse.set_max_reconnect_attempts(1);
  23443. sse.start_async();
  23444. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23445. sse.stop();
  23446. EXPECT_TRUE(update_received.load());
  23447. EXPECT_TRUE(delete_received.load());
  23448. }
  23449. // Test: on_error callback on connection failure
  23450. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23451. // Connect to a non-existent port
  23452. Client client("localhost", 59999);
  23453. sse::SSEClient sse(client, "/events");
  23454. std::atomic<bool> error_called{false};
  23455. Error received_error = Error::Success;
  23456. sse.on_error([&](Error err) {
  23457. error_called.store(true);
  23458. received_error = err;
  23459. });
  23460. sse.set_reconnect_interval(50);
  23461. sse.set_max_reconnect_attempts(1);
  23462. sse.start_async();
  23463. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23464. sse.stop();
  23465. EXPECT_TRUE(error_called.load());
  23466. EXPECT_NE(received_error, Error::Success);
  23467. }
  23468. // Test: Last-Event-ID header sent on reconnect
  23469. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23470. // Endpoint that sends event with ID
  23471. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23472. res.set_chunked_content_provider(
  23473. "text/event-stream", [](size_t offset, DataSink &sink) {
  23474. if (offset == 0) {
  23475. std::string event = "id: evt-123\ndata: test\n\n";
  23476. sink.write(event.data(), event.size());
  23477. }
  23478. return false;
  23479. });
  23480. });
  23481. Client client("localhost", get_port());
  23482. sse::SSEClient sse(client, "/event-with-id");
  23483. std::atomic<bool> id_received{false};
  23484. sse.on_message([&](const sse::SSEMessage &msg) {
  23485. if (!msg.id.empty()) { id_received.store(true); }
  23486. });
  23487. sse.set_reconnect_interval(100);
  23488. sse.set_max_reconnect_attempts(1);
  23489. sse.start_async();
  23490. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23491. sse.stop();
  23492. EXPECT_TRUE(id_received.load());
  23493. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23494. }
  23495. // Test: last_event_id() read from another thread while start_async() runs
  23496. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23497. // Ids of every length up to 200, so the stored id keeps changing size
  23498. server_->Get("/many-ids", [](const Request &, Response &res) {
  23499. res.set_chunked_content_provider(
  23500. "text/event-stream", [](size_t offset, DataSink &sink) {
  23501. if (offset == 0) {
  23502. std::string events;
  23503. for (size_t i = 0; i < 2000; i++) {
  23504. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23505. events += "data: x\n\n";
  23506. }
  23507. events += "id: end\ndata: x\n\n";
  23508. sink.write(events.data(), events.size());
  23509. }
  23510. return false;
  23511. });
  23512. });
  23513. Client client("localhost", get_port());
  23514. sse::SSEClient sse(client, "/many-ids");
  23515. // Wait out the rest of the test rather than replay the stream
  23516. sse.set_reconnect_interval(10000);
  23517. sse.set_max_reconnect_attempts(1);
  23518. sse.start_async();
  23519. auto well_formed = true;
  23520. std::string id;
  23521. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23522. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23523. id = sse.last_event_id();
  23524. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23525. well_formed = false;
  23526. }
  23527. }
  23528. sse.stop();
  23529. EXPECT_TRUE(well_formed);
  23530. EXPECT_EQ(sse.last_event_id(), "end");
  23531. }
  23532. // Test: Manual stop
  23533. TEST_F(SSEIntegrationTest, ManualStop) {
  23534. // Endpoint that sends one event and stays open briefly. The server outlives
  23535. // this test body, so the provider uses the fixture's flag, not a local.
  23536. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23537. res.set_chunked_content_provider(
  23538. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23539. if (offset == 0) {
  23540. std::string event = "data: connected\n\n";
  23541. sink.write(event.data(), event.size());
  23542. }
  23543. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23544. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23545. }
  23546. return false;
  23547. });
  23548. });
  23549. Client client("localhost", get_port());
  23550. sse::SSEClient sse(client, "/stay-open");
  23551. std::atomic<bool> connected{false};
  23552. sse.on_open([&connected]() { connected.store(true); });
  23553. sse.set_reconnect_interval(100);
  23554. sse.set_max_reconnect_attempts(1);
  23555. sse.start_async();
  23556. // Wait for connection to establish
  23557. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23558. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23559. }
  23560. EXPECT_TRUE(connected.load());
  23561. EXPECT_TRUE(sse.is_connected());
  23562. // Signal handler to stop
  23563. stop_server_.store(true);
  23564. // Stop SSE client
  23565. sse.stop();
  23566. EXPECT_FALSE(sse.is_connected());
  23567. }
  23568. // Sends one event, then nothing until stop is set
  23569. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23570. return [&stop](const Request &, Response &res) {
  23571. res.set_chunked_content_provider(
  23572. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23573. if (offset == 0) {
  23574. std::string event = "data: hello\n\n";
  23575. sink.write(event.data(), event.size());
  23576. }
  23577. while (!stop.load()) {
  23578. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23579. }
  23580. return false;
  23581. });
  23582. };
  23583. }
  23584. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23585. static void check_stop_interrupts_blocked_read(Client &client) {
  23586. client.set_read_timeout(30, 0);
  23587. for (auto by_destructor : {false, true}) {
  23588. std::atomic<bool> received{false};
  23589. std::chrono::steady_clock::time_point start;
  23590. {
  23591. sse::SSEClient sse(client, "/idle-stream");
  23592. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23593. sse.start_async();
  23594. for (int i = 0; i < 500 && !received.load(); ++i) {
  23595. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23596. }
  23597. ASSERT_TRUE(received.load());
  23598. // Let the client block in the next read
  23599. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23600. start = std::chrono::steady_clock::now();
  23601. if (!by_destructor) { sse.stop(); }
  23602. }
  23603. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23604. std::chrono::seconds(2));
  23605. }
  23606. }
  23607. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23608. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23609. Client client("localhost", get_port());
  23610. check_stop_interrupts_blocked_read(client);
  23611. }
  23612. #ifdef CPPHTTPLIB_SSL_ENABLED
  23613. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23614. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23615. std::atomic<bool> done{false};
  23616. svr.Get("/idle-stream", idle_event_stream(done));
  23617. auto port = svr.bind_to_any_port(HOST);
  23618. std::thread t([&] { svr.listen_after_bind(); });
  23619. auto se = detail::scope_exit([&] {
  23620. done.store(true);
  23621. svr.stop();
  23622. t.join();
  23623. });
  23624. svr.wait_until_ready();
  23625. Client client("https://localhost:" + std::to_string(port));
  23626. client.enable_server_certificate_verification(false);
  23627. check_stop_interrupts_blocked_read(client);
  23628. }
  23629. #endif
  23630. // Test: SSEClient with custom headers
  23631. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23632. // Setup a server endpoint that checks for custom header
  23633. std::atomic<bool> header_received{false};
  23634. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23635. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23636. header_received.store(true);
  23637. }
  23638. res.set_chunked_content_provider("text/event-stream",
  23639. [](size_t, DataSink &) { return false; });
  23640. });
  23641. Client client("localhost", get_port());
  23642. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23643. sse::SSEClient sse(client, "/header-check", headers);
  23644. sse.set_max_reconnect_attempts(1);
  23645. sse.start_async();
  23646. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23647. sse.stop();
  23648. EXPECT_TRUE(header_received.load());
  23649. }
  23650. // Test: Reconnect interval configuration
  23651. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23652. Client client("localhost", get_port());
  23653. sse::SSEClient sse(client, "/events");
  23654. auto &result = sse.set_reconnect_interval(500);
  23655. // Builder pattern should return reference to self
  23656. EXPECT_EQ(&result, &sse);
  23657. }
  23658. // Test: Max reconnect attempts
  23659. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23660. // Connect to non-existent port to force reconnects
  23661. Client client("localhost", 59998);
  23662. sse::SSEClient sse(client, "/events");
  23663. std::atomic<int> error_count{0};
  23664. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23665. sse.set_reconnect_interval(50);
  23666. sse.set_max_reconnect_attempts(2);
  23667. auto start = std::chrono::steady_clock::now();
  23668. sse.start(); // Blocking call
  23669. auto end = std::chrono::steady_clock::now();
  23670. // Should have stopped after 2 failed attempts
  23671. EXPECT_GE(error_count.load(), 2);
  23672. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23673. auto duration =
  23674. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23675. #ifdef _WIN32
  23676. // Windows is much slower for socket connection failures
  23677. EXPECT_LT(duration.count(), 7000);
  23678. #else
  23679. EXPECT_LT(duration.count(), 1000);
  23680. #endif
  23681. }
  23682. // Test: Multi-line data in integration
  23683. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23684. // Endpoint with multi-line data
  23685. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23686. res.set_chunked_content_provider(
  23687. "text/event-stream", [](size_t offset, DataSink &sink) {
  23688. if (offset == 0) {
  23689. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23690. sink.write(event.data(), event.size());
  23691. }
  23692. return false;
  23693. });
  23694. });
  23695. Client client("localhost", get_port());
  23696. sse::SSEClient sse(client, "/multiline-data");
  23697. std::string received_data;
  23698. std::mutex data_mutex;
  23699. sse.on_message([&](const sse::SSEMessage &msg) {
  23700. std::lock_guard<std::mutex> lock(data_mutex);
  23701. received_data = msg.data;
  23702. });
  23703. sse.set_reconnect_interval(100);
  23704. sse.set_max_reconnect_attempts(1);
  23705. sse.start_async();
  23706. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23707. sse.stop();
  23708. std::lock_guard<std::mutex> lock(data_mutex);
  23709. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23710. }
  23711. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23712. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23713. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23714. DataSink &sink) {
  23715. if (offset == 0) {
  23716. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23717. sink.write(events.data(), events.size());
  23718. }
  23719. return false;
  23720. });
  23721. });
  23722. Client client("localhost", get_port());
  23723. sse::SSEClient sse(client, "/empty-data-lines");
  23724. std::mutex mutex;
  23725. std::condition_variable cv;
  23726. std::vector<std::string> received;
  23727. sse.on_message([&](const sse::SSEMessage &msg) {
  23728. std::lock_guard<std::mutex> lock(mutex);
  23729. received.push_back(msg.data);
  23730. cv.notify_all();
  23731. });
  23732. sse.set_max_reconnect_attempts(1);
  23733. sse.start_async();
  23734. {
  23735. std::unique_lock<std::mutex> lock(mutex);
  23736. cv.wait_for(lock, std::chrono::seconds(2),
  23737. [&] { return received.size() >= 3; });
  23738. }
  23739. sse.stop();
  23740. ASSERT_GE(received.size(), 3u);
  23741. EXPECT_EQ(received[0], "");
  23742. EXPECT_EQ(received[1], "\nhello");
  23743. EXPECT_EQ(received[2], "");
  23744. }
  23745. // Test: Auto-reconnect after server disconnection
  23746. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23747. std::atomic<int> connection_count{0};
  23748. std::atomic<int> message_count{0};
  23749. // Endpoint that sends one event and closes, forcing reconnect
  23750. server_->Get("/reconnect-test",
  23751. [&connection_count](const Request &, Response &res) {
  23752. connection_count.fetch_add(1);
  23753. res.set_chunked_content_provider(
  23754. "text/event-stream", [](size_t offset, DataSink &sink) {
  23755. if (offset == 0) {
  23756. std::string event = "data: hello\n\n";
  23757. sink.write(event.data(), event.size());
  23758. }
  23759. return false; // Close connection after sending
  23760. });
  23761. });
  23762. Client client("localhost", get_port());
  23763. sse::SSEClient sse(client, "/reconnect-test");
  23764. sse.on_message([&message_count](const sse::SSEMessage &) {
  23765. message_count.fetch_add(1);
  23766. });
  23767. sse.set_reconnect_interval(100);
  23768. sse.set_max_reconnect_attempts(3);
  23769. sse.start_async();
  23770. // Wait long enough for multiple reconnects
  23771. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23772. sse.stop();
  23773. // Should have connected multiple times (initial + reconnects)
  23774. EXPECT_GE(connection_count.load(), 2);
  23775. // Should have received messages from multiple connections
  23776. EXPECT_GE(message_count.load(), 2);
  23777. }
  23778. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23779. std::atomic<int> connection_count{0};
  23780. // Neither Content-Length nor chunked: the close ends the stream
  23781. server_->Get("/close-delimited",
  23782. [&connection_count](const Request &, Response &res) {
  23783. connection_count.fetch_add(1);
  23784. res.set_content_provider(
  23785. "text/event-stream", [](size_t offset, DataSink &sink) {
  23786. if (offset == 0) {
  23787. std::string event = "data: hello\n\n";
  23788. sink.write(event.data(), event.size());
  23789. } else {
  23790. sink.done();
  23791. }
  23792. return true;
  23793. });
  23794. });
  23795. Client client("localhost", get_port());
  23796. sse::SSEClient sse(client, "/close-delimited");
  23797. std::atomic<int> error_count{0};
  23798. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23799. sse.set_reconnect_interval(100);
  23800. sse.start_async();
  23801. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23802. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23803. }
  23804. sse.stop();
  23805. // Reconnects as after any end of the stream, but reports no error
  23806. EXPECT_GE(connection_count.load(), 2);
  23807. EXPECT_EQ(0, error_count.load());
  23808. }
  23809. // Test: A retry field of all ASCII digits sets the reconnection time
  23810. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23811. std::mutex mutex;
  23812. std::condition_variable cv;
  23813. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23814. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23815. {
  23816. std::lock_guard<std::mutex> lock(mutex);
  23817. connected_at.push_back(std::chrono::steady_clock::now());
  23818. cv.notify_all();
  23819. }
  23820. res.set_chunked_content_provider(
  23821. "text/event-stream", [](size_t offset, DataSink &sink) {
  23822. if (offset == 0) {
  23823. std::string event = "retry: 0\ndata: hello\n\n";
  23824. sink.write(event.data(), event.size());
  23825. }
  23826. return false;
  23827. });
  23828. });
  23829. Client client("localhost", get_port());
  23830. sse::SSEClient sse(client, "/zero-retry");
  23831. sse.set_reconnect_interval(10000);
  23832. sse.start_async();
  23833. {
  23834. std::unique_lock<std::mutex> lock(mutex);
  23835. cv.wait_for(lock, std::chrono::seconds(5),
  23836. [&] { return connected_at.size() >= 2; });
  23837. }
  23838. sse.stop();
  23839. // The server-supplied interval is applied, but never below 100ms, so
  23840. // "retry: 0" does not cause a busy reconnect loop
  23841. std::lock_guard<std::mutex> lock(mutex);
  23842. ASSERT_GE(connected_at.size(), 2u);
  23843. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23844. connected_at[1] - connected_at[0])
  23845. .count();
  23846. EXPECT_GE(interval_ms, 100);
  23847. }
  23848. // Test: Last-Event-ID sent on reconnect
  23849. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23850. std::atomic<int> connection_count{0};
  23851. std::vector<std::string> received_last_event_ids;
  23852. std::mutex id_mutex;
  23853. // Endpoint that checks Last-Event-ID header and sends event with ID
  23854. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23855. int conn = connection_count.fetch_add(1);
  23856. // Capture the Last-Event-ID header from each connection
  23857. {
  23858. std::lock_guard<std::mutex> lock(id_mutex);
  23859. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23860. }
  23861. res.set_chunked_content_provider(
  23862. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23863. if (offset == 0) {
  23864. std::string event =
  23865. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23866. sink.write(event.data(), event.size());
  23867. }
  23868. return false;
  23869. });
  23870. });
  23871. Client client("localhost", get_port());
  23872. sse::SSEClient sse(client, "/reconnect-with-id");
  23873. sse.set_reconnect_interval(100);
  23874. sse.set_max_reconnect_attempts(3);
  23875. sse.start_async();
  23876. // Wait for at least 2 connections
  23877. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23878. sse.stop();
  23879. // Verify behavior
  23880. std::lock_guard<std::mutex> lock(id_mutex);
  23881. EXPECT_GE(received_last_event_ids.size(), 2u);
  23882. // First connection should have no Last-Event-ID
  23883. if (!received_last_event_ids.empty()) {
  23884. EXPECT_EQ(received_last_event_ids[0], "");
  23885. }
  23886. // Second connection should have Last-Event-ID from first connection
  23887. if (received_last_event_ids.size() >= 2) {
  23888. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23889. }
  23890. }
  23891. // Test: set_headers updates headers used on reconnect
  23892. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23893. std::vector<std::string> received_tokens;
  23894. std::mutex token_mutex;
  23895. // Endpoint that captures Authorization header
  23896. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23897. {
  23898. std::lock_guard<std::mutex> lock(token_mutex);
  23899. received_tokens.push_back(req.get_header_value("Authorization"));
  23900. }
  23901. res.set_chunked_content_provider(
  23902. "text/event-stream", [](size_t offset, DataSink &sink) {
  23903. if (offset == 0) {
  23904. std::string event = "data: hello\n\n";
  23905. sink.write(event.data(), event.size());
  23906. }
  23907. return false; // Close connection to trigger reconnect
  23908. });
  23909. });
  23910. Client client("localhost", get_port());
  23911. Headers headers = {{"Authorization", "Bearer old-token"}};
  23912. sse::SSEClient sse(client, "/auth-check", headers);
  23913. // Update headers on each successful connection
  23914. sse.on_open(
  23915. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23916. sse.set_reconnect_interval(100);
  23917. sse.set_max_reconnect_attempts(3);
  23918. sse.start_async();
  23919. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23920. sse.stop();
  23921. std::lock_guard<std::mutex> lock(token_mutex);
  23922. ASSERT_GE(received_tokens.size(), 2u);
  23923. // First connection uses original header
  23924. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23925. // Second connection uses updated header from set_headers
  23926. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23927. }
  23928. // Test: 401 allows reconnection (so on_error can refresh headers)
  23929. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23930. std::atomic<int> connection_count{0};
  23931. // Endpoint: returns 401 on first attempt, 200 on second
  23932. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23933. int conn = connection_count.fetch_add(1);
  23934. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23935. res.status = StatusCode::Unauthorized_401;
  23936. res.set_content("Unauthorized", "text/plain");
  23937. return;
  23938. }
  23939. res.set_chunked_content_provider(
  23940. "text/event-stream", [](size_t offset, DataSink &sink) {
  23941. if (offset == 0) {
  23942. std::string event = "data: authenticated\n\n";
  23943. sink.write(event.data(), event.size());
  23944. }
  23945. return false;
  23946. });
  23947. });
  23948. Client client("localhost", get_port());
  23949. Headers headers = {{"Authorization", "Bearer expired"}};
  23950. sse::SSEClient sse(client, "/auth-retry", headers);
  23951. std::atomic<bool> message_received{false};
  23952. // Refresh token on error
  23953. sse.on_error(
  23954. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23955. sse.on_message([&](const sse::SSEMessage &msg) {
  23956. if (msg.data == "authenticated") { message_received.store(true); }
  23957. });
  23958. sse.set_reconnect_interval(100);
  23959. sse.set_max_reconnect_attempts(3);
  23960. sse.start_async();
  23961. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23962. sse.stop();
  23963. // Should have reconnected after 401 and succeeded with new token
  23964. EXPECT_GE(connection_count.load(), 2);
  23965. EXPECT_TRUE(message_received.load());
  23966. }
  23967. TEST(Issue2318Test, EmptyHostString) {
  23968. {
  23969. httplib::Client cli_empty("", PORT);
  23970. auto res = cli_empty.Get("/");
  23971. ASSERT_FALSE(res);
  23972. EXPECT_EQ(httplib::Error::Connection, res.error());
  23973. }
  23974. {
  23975. httplib::Client cli(" ", PORT);
  23976. auto res = cli.Get("/");
  23977. ASSERT_FALSE(res);
  23978. EXPECT_EQ(httplib::Error::Connection, res.error());
  23979. }
  23980. }
  23981. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  23982. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  23983. Server svr;
  23984. // Set a small payload limit (1KB)
  23985. svr.set_payload_max_length(1024);
  23986. svr.Post("/test", [&](const Request &req, Response &res) {
  23987. res.set_content("Body size: " + std::to_string(req.body.size()),
  23988. "text/plain");
  23989. });
  23990. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  23991. auto se = detail::scope_exit([&] {
  23992. svr.stop();
  23993. listen_thread.join();
  23994. });
  23995. svr.wait_until_ready();
  23996. // Create data that compresses well but exceeds limit when decompressed
  23997. // 8KB of repeated null bytes compresses to a very small size
  23998. std::string original_data(8 * 1024, '\0');
  23999. // Compress the data using gzip
  24000. std::string compressed_data;
  24001. detail::gzip_compressor compressor;
  24002. compressor.compress(original_data.data(), original_data.size(), true,
  24003. [&](const char *data, size_t size) {
  24004. compressed_data.append(data, size);
  24005. return true;
  24006. });
  24007. // Verify compression worked (compressed should be much smaller)
  24008. ASSERT_LT(compressed_data.size(), original_data.size());
  24009. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  24010. // Send compressed data with Content-Encoding: gzip
  24011. Client cli(HOST, PORT);
  24012. Headers headers = {{"Content-Encoding", "gzip"}};
  24013. auto res =
  24014. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24015. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24017. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24018. }
  24019. #endif
  24020. // ============================================================================
  24021. // OpenSSL-Specific Tests
  24022. // ============================================================================
  24023. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24024. X509 *readCertificate(const std::string &strFileName) {
  24025. std::ifstream inStream(strFileName);
  24026. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24027. std::istreambuf_iterator<char>());
  24028. if (strCertPEM.empty()) return (nullptr);
  24029. BIO *pbCert = BIO_new(BIO_s_mem());
  24030. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24031. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24032. BIO_free(pbCert);
  24033. return (pCert);
  24034. }
  24035. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24036. std::ifstream inStream(strFileName);
  24037. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24038. std::istreambuf_iterator<char>());
  24039. if (strPrivateKeyPEM.empty()) return (nullptr);
  24040. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24041. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24042. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24043. BIO_free(pbPrivKey);
  24044. return (pPrivateKey);
  24045. }
  24046. TEST(BindServerTest, UpdateCerts) {
  24047. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24048. int port = svr.bind_to_any_port("0.0.0.0");
  24049. ASSERT_TRUE(svr.is_valid());
  24050. ASSERT_TRUE(port > 0);
  24051. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24052. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24053. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24054. ASSERT_TRUE(cert != nullptr);
  24055. ASSERT_TRUE(ca_cert != nullptr);
  24056. ASSERT_TRUE(key != nullptr);
  24057. X509_STORE *cert_store = X509_STORE_new();
  24058. X509_STORE_add_cert(cert_store, ca_cert);
  24059. // svr.update_certs(cert, key, cert_store); // deprecated
  24060. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24061. CLIENT_CA_CERT_FILE);
  24062. ASSERT_TRUE(svr.is_valid());
  24063. svr.stop();
  24064. X509_STORE_free(cert_store);
  24065. X509_free(cert);
  24066. X509_free(ca_cert);
  24067. EVP_PKEY_free(key);
  24068. }
  24069. // Test that update_certs() updates client CA list correctly
  24070. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24071. // Start with file-based constructor
  24072. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24073. ASSERT_TRUE(svr.is_valid());
  24074. // Initially no client CA list should be set
  24075. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24076. ASSERT_TRUE(ssl_ctx != nullptr);
  24077. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24078. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24079. // Now update with client CA (PEM string)
  24080. std::string cert_pem, key_pem, ca_pem;
  24081. read_file(SERVER_CERT_FILE, cert_pem);
  24082. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24083. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24084. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24085. ASSERT_TRUE(svr.is_valid());
  24086. // Now client CA list should be set
  24087. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24088. ASSERT_TRUE(ca_list_after != nullptr);
  24089. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24090. }
  24091. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24092. // Test that the file-path SSLServer constructor properly sets the client CA
  24093. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24094. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24095. ASSERT_TRUE(svr.is_valid());
  24096. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24097. ASSERT_TRUE(ssl_ctx != nullptr);
  24098. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24099. ASSERT_TRUE(ca_list != nullptr);
  24100. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24101. }
  24102. #endif
  24103. // ============================================================================
  24104. // MbedTLS-Specific Tests
  24105. // ============================================================================
  24106. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24107. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24108. using namespace httplib::tls;
  24109. // Track if callback was invoked
  24110. bool callback_invoked = false;
  24111. // The callback receives void* ctx which is actually MbedTlsContext*
  24112. // We can access the mbedtls_ssl_config via the context
  24113. auto setup_callback = [&callback_invoked](void *ctx) {
  24114. callback_invoked = true;
  24115. // Cast to MbedTlsContext* to access the ssl config
  24116. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24117. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24118. // Use static variables to hold certificate data (simplified for test)
  24119. static mbedtls_x509_crt own_cert;
  24120. static mbedtls_pk_context own_key;
  24121. static mbedtls_x509_crt ca_chain;
  24122. static bool initialized = false;
  24123. if (!initialized) {
  24124. mbedtls_x509_crt_init(&own_cert);
  24125. mbedtls_pk_init(&own_key);
  24126. mbedtls_x509_crt_init(&ca_chain);
  24127. // Load server certificate
  24128. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24129. return false;
  24130. }
  24131. // Load server private key.
  24132. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24133. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24134. #if MBEDTLS_VERSION_MAJOR == 3
  24135. ,
  24136. mbedtls_ctr_drbg_random, nullptr
  24137. #endif
  24138. ) != 0) {
  24139. return false;
  24140. }
  24141. // Load CA chain for client verification
  24142. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24143. return false;
  24144. }
  24145. initialized = true;
  24146. }
  24147. // Configure the SSL config
  24148. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24149. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24150. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24151. // Set minimum TLS version using mbedTLS native API
  24152. #if MBEDTLS_VERSION_MAJOR >= 3
  24153. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24154. #else
  24155. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24156. MBEDTLS_SSL_MINOR_VERSION_3);
  24157. #endif
  24158. return true;
  24159. };
  24160. SSLServer svr(setup_callback);
  24161. ASSERT_TRUE(svr.is_valid());
  24162. ASSERT_TRUE(callback_invoked);
  24163. svr.Get("/test", [&](const Request &req, Response &res) {
  24164. res.set_content("test", "text/plain");
  24165. auto cert = req.peer_cert();
  24166. ASSERT_TRUE(static_cast<bool>(cert));
  24167. auto common_name = cert.subject_cn();
  24168. EXPECT_EQ("Common Name", common_name);
  24169. });
  24170. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24171. auto se = detail::scope_exit([&] {
  24172. svr.stop();
  24173. t.join();
  24174. ASSERT_FALSE(svr.is_running());
  24175. });
  24176. svr.wait_until_ready();
  24177. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24178. cli.enable_server_certificate_verification(false);
  24179. cli.set_connection_timeout(30);
  24180. auto res = cli.Get("/test");
  24181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24182. ASSERT_EQ(StatusCode::OK_200, res->status);
  24183. }
  24184. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24185. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24186. // keep-alive SSL session, which reads through that config in
  24187. // mbedtls_ssl_close_notify.
  24188. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24189. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24190. ASSERT_TRUE(svr.is_valid());
  24191. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24192. res.set_content("test", "text/plain");
  24193. });
  24194. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24195. auto se = detail::scope_exit([&] {
  24196. svr.stop();
  24197. t.join();
  24198. ASSERT_FALSE(svr.is_running());
  24199. });
  24200. svr.wait_until_ready();
  24201. {
  24202. SSLClient cli(HOST, PORT);
  24203. cli.enable_server_certificate_verification(false);
  24204. cli.set_keep_alive(true);
  24205. auto res = cli.Get("/test");
  24206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24207. ASSERT_EQ(StatusCode::OK_200, res->status);
  24208. // cli is destructed here with the keep-alive SSL session still open.
  24209. }
  24210. }
  24211. #endif
  24212. // WebSocket Tests
  24213. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24214. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24215. // defining the meaning of these bits has been negotiated.
  24216. auto make_frame = [](uint8_t first_byte) {
  24217. std::string frame;
  24218. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24219. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24220. frame += "Hello";
  24221. return frame;
  24222. };
  24223. // RSV1 set (0x40)
  24224. {
  24225. detail::BufferStream strm;
  24226. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24227. ws::Opcode opcode;
  24228. std::string payload;
  24229. bool fin;
  24230. EXPECT_EQ(
  24231. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24232. ws::impl::FrameRead::ProtocolError);
  24233. }
  24234. // RSV2 set (0x20)
  24235. {
  24236. detail::BufferStream strm;
  24237. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24238. ws::Opcode opcode;
  24239. std::string payload;
  24240. bool fin;
  24241. EXPECT_EQ(
  24242. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24243. ws::impl::FrameRead::ProtocolError);
  24244. }
  24245. // RSV3 set (0x10)
  24246. {
  24247. detail::BufferStream strm;
  24248. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24249. ws::Opcode opcode;
  24250. std::string payload;
  24251. bool fin;
  24252. EXPECT_EQ(
  24253. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24254. ws::impl::FrameRead::ProtocolError);
  24255. }
  24256. // No RSV bits set - should succeed
  24257. {
  24258. detail::BufferStream strm;
  24259. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24260. ws::Opcode opcode;
  24261. std::string payload;
  24262. bool fin;
  24263. EXPECT_EQ(
  24264. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24265. ws::impl::FrameRead::Ok);
  24266. EXPECT_EQ(ws::Opcode::Text, opcode);
  24267. EXPECT_EQ("Hello", payload);
  24268. EXPECT_TRUE(fin);
  24269. }
  24270. }
  24271. TEST(WebSocketTest, ControlFrameValidation) {
  24272. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24273. // payload length <= 125.
  24274. // Ping with FIN=0 - must be rejected
  24275. {
  24276. detail::BufferStream strm;
  24277. std::string frame;
  24278. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24279. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24280. strm.write(frame.data(), frame.size());
  24281. ws::Opcode opcode;
  24282. std::string payload;
  24283. bool fin;
  24284. EXPECT_EQ(
  24285. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24286. ws::impl::FrameRead::ProtocolError);
  24287. }
  24288. // Close with FIN=0 - must be rejected
  24289. {
  24290. detail::BufferStream strm;
  24291. std::string frame;
  24292. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24293. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24294. strm.write(frame.data(), frame.size());
  24295. ws::Opcode opcode;
  24296. std::string payload;
  24297. bool fin;
  24298. EXPECT_EQ(
  24299. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24300. ws::impl::FrameRead::ProtocolError);
  24301. }
  24302. // Ping with payload_len=126 (extended length) - must be rejected
  24303. {
  24304. detail::BufferStream strm;
  24305. std::string frame;
  24306. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24307. frame += static_cast<char>(126); // payload_len=126 (>125)
  24308. frame += static_cast<char>(0x00); // extended length high byte
  24309. frame += static_cast<char>(126); // extended length low byte
  24310. frame += std::string(126, 'x');
  24311. strm.write(frame.data(), frame.size());
  24312. ws::Opcode opcode;
  24313. std::string payload;
  24314. bool fin;
  24315. EXPECT_EQ(
  24316. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24317. ws::impl::FrameRead::ProtocolError);
  24318. }
  24319. // Ping with FIN=1 and payload_len=125 - should succeed
  24320. {
  24321. detail::BufferStream strm;
  24322. std::string frame;
  24323. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24324. frame += static_cast<char>(125); // payload_len=125
  24325. frame += std::string(125, 'x');
  24326. strm.write(frame.data(), frame.size());
  24327. ws::Opcode opcode;
  24328. std::string payload;
  24329. bool fin;
  24330. EXPECT_EQ(
  24331. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24332. ws::impl::FrameRead::Ok);
  24333. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24334. EXPECT_EQ(125u, payload.size());
  24335. EXPECT_TRUE(fin);
  24336. }
  24337. }
  24338. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24339. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24340. // length MUST be 0.
  24341. // MSB set - must be rejected
  24342. {
  24343. detail::BufferStream strm;
  24344. std::string frame;
  24345. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24346. frame += static_cast<char>(127); // 64-bit extended length
  24347. frame += static_cast<char>(0x80); // MSB set (invalid)
  24348. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24349. strm.write(frame.data(), frame.size());
  24350. ws::Opcode opcode;
  24351. std::string payload;
  24352. bool fin;
  24353. EXPECT_EQ(
  24354. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24355. ws::impl::FrameRead::ProtocolError);
  24356. }
  24357. // MSB clear - should pass length parsing (will be rejected by max_len,
  24358. // but that's a different check; use a small length to verify)
  24359. {
  24360. detail::BufferStream strm;
  24361. std::string frame;
  24362. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24363. frame += static_cast<char>(127); // 64-bit extended length
  24364. frame += std::string(7, '\0'); // high bytes = 0
  24365. frame += static_cast<char>(0x03); // length = 3
  24366. frame += "abc";
  24367. strm.write(frame.data(), frame.size());
  24368. ws::Opcode opcode;
  24369. std::string payload;
  24370. bool fin;
  24371. EXPECT_EQ(
  24372. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24373. ws::impl::FrameRead::Ok);
  24374. EXPECT_EQ(ws::Opcode::Text, opcode);
  24375. EXPECT_EQ("abc", payload);
  24376. }
  24377. }
  24378. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24379. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24380. // Valid UTF-8
  24381. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24382. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24383. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24384. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24385. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24386. // Invalid UTF-8
  24387. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24388. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24389. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24390. EXPECT_FALSE(
  24391. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24392. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24393. }
  24394. TEST(WebSocketTest, ConnectAndDisconnect) {
  24395. Server svr;
  24396. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24397. std::string msg;
  24398. while (ws.read(msg)) {}
  24399. });
  24400. auto port = svr.bind_to_any_port(HOST);
  24401. std::thread t([&]() { svr.listen_after_bind(); });
  24402. svr.wait_until_ready();
  24403. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24404. auto res = client.connect();
  24405. ASSERT_TRUE(res);
  24406. EXPECT_EQ(Error::Success, res.error());
  24407. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24408. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24409. EXPECT_TRUE(client.is_open());
  24410. client.close();
  24411. EXPECT_FALSE(client.is_open());
  24412. svr.stop();
  24413. t.join();
  24414. }
  24415. TEST(WebSocketTest, ValidURL) {
  24416. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24417. EXPECT_TRUE(ws1.is_valid());
  24418. ws::WebSocketClient ws2("ws://example.com/path");
  24419. EXPECT_TRUE(ws2.is_valid());
  24420. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24421. EXPECT_TRUE(ws3.is_valid());
  24422. #ifdef CPPHTTPLIB_SSL_ENABLED
  24423. ws::WebSocketClient wss1("wss://example.com/path");
  24424. EXPECT_TRUE(wss1.is_valid());
  24425. ws::WebSocketClient wss2("wss://example.com:443/path");
  24426. EXPECT_TRUE(wss2.is_valid());
  24427. #endif
  24428. }
  24429. TEST(WebSocketTest, InvalidURL) {
  24430. // No scheme
  24431. ws::WebSocketClient ws1("localhost:8080/path");
  24432. EXPECT_FALSE(ws1.is_valid());
  24433. // No path
  24434. ws::WebSocketClient ws2("ws://localhost:8080");
  24435. EXPECT_FALSE(ws2.is_valid());
  24436. // Empty string
  24437. ws::WebSocketClient ws3("");
  24438. EXPECT_FALSE(ws3.is_valid());
  24439. // Missing host
  24440. ws::WebSocketClient ws4("ws://:8080/path");
  24441. EXPECT_FALSE(ws4.is_valid());
  24442. // Port number overflow — should not crash
  24443. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24444. EXPECT_FALSE(ws5.is_valid());
  24445. // Port out of range
  24446. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24447. EXPECT_FALSE(ws6.is_valid());
  24448. }
  24449. TEST(WebSocketTest, UnsupportedScheme) {
  24450. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24451. ws::WebSocketClient ws1("http://localhost:8080/path");
  24452. EXPECT_FALSE(ws1.is_valid());
  24453. ws::WebSocketClient ws2("https://localhost:8080/path");
  24454. EXPECT_FALSE(ws2.is_valid());
  24455. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24456. EXPECT_FALSE(ws3.is_valid());
  24457. #else
  24458. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24459. std::invalid_argument);
  24460. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24461. std::invalid_argument);
  24462. #endif
  24463. }
  24464. TEST(WebSocketTest, ConnectWhenInvalid) {
  24465. ws::WebSocketClient ws("not a valid url");
  24466. EXPECT_FALSE(ws.is_valid());
  24467. auto res = ws.connect();
  24468. EXPECT_FALSE(res);
  24469. EXPECT_EQ(Error::Connection, res.error());
  24470. EXPECT_EQ(-1, res.status());
  24471. }
  24472. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24473. // Grab a port that is free, then close it again so nothing listens there
  24474. Server svr;
  24475. auto port = svr.bind_to_any_port(HOST);
  24476. svr.stop();
  24477. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24478. auto res = client.connect();
  24479. ASSERT_FALSE(res);
  24480. EXPECT_EQ(Error::Connection, res.error());
  24481. EXPECT_EQ(-1, res.status());
  24482. }
  24483. TEST(WebSocketTest, DefaultPort) {
  24484. ws::WebSocketClient ws1("ws://example.com/path");
  24485. EXPECT_TRUE(ws1.is_valid());
  24486. // ws:// defaults to port 80 (verified by successful parse)
  24487. #ifdef CPPHTTPLIB_SSL_ENABLED
  24488. ws::WebSocketClient ws2("wss://example.com/path");
  24489. EXPECT_TRUE(ws2.is_valid());
  24490. // wss:// defaults to port 443 (verified by successful parse)
  24491. #endif
  24492. }
  24493. TEST(WebSocketTest, IPv6LiteralAddress) {
  24494. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24495. EXPECT_TRUE(ws1.is_valid());
  24496. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24497. EXPECT_TRUE(ws2.is_valid());
  24498. }
  24499. TEST(WebSocketTest, ComplexPath) {
  24500. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24501. EXPECT_TRUE(ws1.is_valid());
  24502. ws::WebSocketClient ws2("ws://localhost:8080/");
  24503. EXPECT_TRUE(ws2.is_valid());
  24504. }
  24505. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24506. Server svr;
  24507. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24508. std::string msg;
  24509. while (ws.read(msg)) {}
  24510. });
  24511. auto port = svr.bind_to_any_port(HOST);
  24512. std::thread t([&]() { svr.listen_after_bind(); });
  24513. svr.wait_until_ready();
  24514. auto another_host = "example.com";
  24515. auto wrong_ip = "192.0.2.1";
  24516. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24517. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24518. ASSERT_TRUE(client.connect());
  24519. EXPECT_TRUE(client.is_open());
  24520. client.close();
  24521. svr.stop();
  24522. t.join();
  24523. }
  24524. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24525. Server svr;
  24526. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24527. std::string msg;
  24528. while (ws.read(msg)) {}
  24529. });
  24530. auto port = svr.bind_to_any_port(HOST);
  24531. std::thread t([&]() { svr.listen_after_bind(); });
  24532. svr.wait_until_ready();
  24533. auto wrong_ip = "192.0.2.1";
  24534. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24535. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24536. client.set_connection_timeout(1);
  24537. client.set_read_timeout(1);
  24538. client.set_write_timeout(1);
  24539. EXPECT_FALSE(client.connect());
  24540. EXPECT_FALSE(client.is_open());
  24541. svr.stop();
  24542. t.join();
  24543. }
  24544. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24545. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24546. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24547. // (RFC 6761) is only a map key and the Host header value.
  24548. auto host = "target.invalid";
  24549. Server svr;
  24550. std::string received_host;
  24551. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24552. received_host = req.get_header_value("Host");
  24553. std::string msg;
  24554. while (ws.read(msg)) {}
  24555. });
  24556. auto port = svr.bind_to_any_port(HOST);
  24557. std::thread t([&]() { svr.listen_after_bind(); });
  24558. // ASSERT_* below returns from the test body, which would leave t joinable
  24559. // and make ~thread call std::terminate.
  24560. auto se = detail::scope_exit([&] {
  24561. svr.stop();
  24562. if (t.joinable()) { t.join(); }
  24563. });
  24564. svr.wait_until_ready();
  24565. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24566. std::to_string(port) + "/ws");
  24567. client.set_direct_hostname_addr_map({{host, HOST}});
  24568. ASSERT_TRUE(client.connect());
  24569. EXPECT_TRUE(client.is_open());
  24570. client.close();
  24571. svr.stop();
  24572. t.join();
  24573. // The mapping only redirects the connection; the identity stays host_.
  24574. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24575. }
  24576. class WebSocketIntegrationTest : public ::testing::Test {
  24577. protected:
  24578. void SetUp() override {
  24579. server_ = httplib::detail::make_unique<Server>();
  24580. setup_server();
  24581. start_server();
  24582. }
  24583. void TearDown() override {
  24584. server_->stop();
  24585. if (server_thread_.joinable()) { server_thread_.join(); }
  24586. }
  24587. void setup_server() {
  24588. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24589. std::string msg;
  24590. ws::ReadResult ret;
  24591. while ((ret = ws.read(msg))) {
  24592. if (ret == ws::Binary) {
  24593. ws.send(msg.data(), msg.size());
  24594. } else {
  24595. ws.send(msg);
  24596. }
  24597. }
  24598. });
  24599. server_->WebSocket("/ws-echo-string",
  24600. [](const Request &, ws::WebSocket &ws) {
  24601. std::string msg;
  24602. while (ws.read(msg)) {
  24603. ws.send("echo: " + msg);
  24604. }
  24605. });
  24606. server_->WebSocket(
  24607. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24608. // Echo back request metadata
  24609. ws.send("path:" + req.path);
  24610. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24611. std::string msg;
  24612. while (ws.read(msg)) {}
  24613. });
  24614. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24615. std::string msg;
  24616. ws.read(msg); // wait for a message
  24617. ws.close();
  24618. });
  24619. server_->WebSocket("/ws-close-status",
  24620. [](const Request &, ws::WebSocket &ws) {
  24621. std::string msg;
  24622. ws.read(msg); // wait for a message
  24623. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24624. });
  24625. server_->WebSocket(
  24626. "/ws-subprotocol",
  24627. [](const Request &, ws::WebSocket &ws) {
  24628. std::string msg;
  24629. while (ws.read(msg)) {
  24630. ws.send(msg);
  24631. }
  24632. },
  24633. [](const std::vector<std::string> &protocols) -> std::string {
  24634. for (const auto &p : protocols) {
  24635. if (p == "graphql-ws") { return p; }
  24636. }
  24637. return "";
  24638. });
  24639. server_->WebSocket(
  24640. "/ws-subprotocol-unoffered",
  24641. [](const Request &, ws::WebSocket &ws) {
  24642. std::string msg;
  24643. while (ws.read(msg)) {
  24644. ws.send(msg);
  24645. }
  24646. },
  24647. [](const std::vector<std::string> &) -> std::string {
  24648. return "admin";
  24649. });
  24650. }
  24651. void start_server() {
  24652. port_ = server_->bind_to_any_port(HOST);
  24653. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24654. server_->wait_until_ready();
  24655. }
  24656. std::unique_ptr<Server> server_;
  24657. std::thread server_thread_;
  24658. int port_ = 0;
  24659. };
  24660. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24661. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24662. "/ws-echo");
  24663. ASSERT_TRUE(client.connect());
  24664. ASSERT_TRUE(client.is_open());
  24665. ASSERT_TRUE(client.send("Hello WebSocket"));
  24666. std::string msg;
  24667. EXPECT_EQ(ws::Text, client.read(msg));
  24668. EXPECT_EQ("Hello WebSocket", msg);
  24669. client.close();
  24670. }
  24671. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24672. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24673. "/ws-echo");
  24674. ASSERT_TRUE(client.connect());
  24675. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24676. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24677. std::string msg;
  24678. EXPECT_EQ(ws::Binary, client.read(msg));
  24679. EXPECT_EQ(binary_data, msg);
  24680. client.close();
  24681. }
  24682. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24683. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24684. "/ws-echo");
  24685. ASSERT_TRUE(client.connect());
  24686. for (int i = 0; i < 10; i++) {
  24687. auto text = "message " + std::to_string(i);
  24688. ASSERT_TRUE(client.send(text));
  24689. std::string msg;
  24690. ASSERT_TRUE(client.read(msg));
  24691. EXPECT_EQ(text, msg);
  24692. }
  24693. client.close();
  24694. }
  24695. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24696. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24697. "/ws-close");
  24698. ASSERT_TRUE(client.connect());
  24699. // Send a message to trigger the server to close
  24700. ASSERT_TRUE(client.send("trigger close"));
  24701. // The server will close, so read should return false
  24702. std::string msg;
  24703. EXPECT_FALSE(client.read(msg));
  24704. EXPECT_FALSE(client.is_open());
  24705. EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
  24706. EXPECT_EQ("", client.close_reason());
  24707. }
  24708. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24709. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24710. "/ws-echo");
  24711. ASSERT_TRUE(client.connect());
  24712. // 128KB message
  24713. std::string large_data(128 * 1024, 'X');
  24714. ASSERT_TRUE(client.send(large_data));
  24715. std::string msg;
  24716. ASSERT_TRUE(client.read(msg));
  24717. EXPECT_EQ(large_data, msg);
  24718. client.close();
  24719. }
  24720. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24721. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24722. "/ws-echo");
  24723. ASSERT_TRUE(client.connect());
  24724. const int num_threads = 4;
  24725. std::vector<std::thread> threads;
  24726. std::atomic<int> send_count{0};
  24727. for (int t = 0; t < num_threads; t++) {
  24728. threads.emplace_back([&client, &send_count, t]() {
  24729. for (int i = 0; i < 5; i++) {
  24730. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24731. if (client.send(text)) { send_count++; }
  24732. }
  24733. });
  24734. }
  24735. for (auto &th : threads) {
  24736. th.join();
  24737. }
  24738. int received = 0;
  24739. std::string msg;
  24740. while (received < send_count.load()) {
  24741. if (!client.read(msg)) { break; }
  24742. received++;
  24743. }
  24744. EXPECT_EQ(send_count.load(), received);
  24745. client.close();
  24746. }
  24747. TEST_F(WebSocketIntegrationTest, ReadString) {
  24748. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24749. "/ws-echo-string");
  24750. ASSERT_TRUE(client.connect());
  24751. ASSERT_TRUE(client.send("hello"));
  24752. std::string msg;
  24753. ASSERT_TRUE(client.read(msg));
  24754. EXPECT_EQ("echo: hello", msg);
  24755. ASSERT_TRUE(client.send("world"));
  24756. ASSERT_TRUE(client.read(msg));
  24757. EXPECT_EQ("echo: world", msg);
  24758. client.close();
  24759. }
  24760. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24761. Headers headers = {{"X-Test-Header", "test-value"}};
  24762. ws::WebSocketClient client(
  24763. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24764. ASSERT_TRUE(client.connect());
  24765. std::string msg;
  24766. ASSERT_TRUE(client.read(msg));
  24767. EXPECT_EQ("path:/ws-request-info", msg);
  24768. ASSERT_TRUE(client.read(msg));
  24769. EXPECT_EQ("header:test-value", msg);
  24770. client.close();
  24771. }
  24772. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24773. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24774. "/ws-echo");
  24775. client.set_read_timeout(1, 0); // 1 second
  24776. ASSERT_TRUE(client.connect());
  24777. // Don't send anything — server echo handler waits for a message, so read()
  24778. // should time out. The connection survives it: nothing was consumed.
  24779. std::string msg;
  24780. EXPECT_EQ(client.read(msg), ws::Timeout);
  24781. EXPECT_TRUE(client.is_open());
  24782. // And it is still usable afterwards.
  24783. EXPECT_TRUE(client.send("after timeout"));
  24784. EXPECT_EQ(client.read(msg), ws::Text);
  24785. EXPECT_EQ(msg, "after timeout");
  24786. }
  24787. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24789. "/ws-echo");
  24790. client.set_read_timeout(1, 0);
  24791. ASSERT_TRUE(client.connect());
  24792. ASSERT_TRUE(client.send("first"));
  24793. std::string msg;
  24794. ASSERT_EQ(client.read(msg), ws::Text);
  24795. ASSERT_EQ(msg, "first");
  24796. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24797. // not be used with a read timeout: it would reprocess the previous message.
  24798. EXPECT_EQ(client.read(msg), ws::Timeout);
  24799. EXPECT_EQ(msg, "first");
  24800. }
  24801. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24802. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24803. "/ws-echo");
  24804. ASSERT_TRUE(client.connect());
  24805. // Setting it once the connection is open reaches the live stream, not just
  24806. // the seed for the next connect().
  24807. client.set_read_timeout(1, 0);
  24808. std::string msg;
  24809. EXPECT_EQ(client.read(msg), ws::Timeout);
  24810. EXPECT_TRUE(client.is_open());
  24811. }
  24812. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24814. "/nonexistent");
  24815. auto res = client.connect();
  24816. EXPECT_FALSE(res);
  24817. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24818. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24819. EXPECT_FALSE(client.is_open());
  24820. }
  24821. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24823. "/ws-echo");
  24824. ASSERT_TRUE(client.connect());
  24825. ASSERT_TRUE(client.send(""));
  24826. std::string msg;
  24827. EXPECT_EQ(ws::Text, client.read(msg));
  24828. EXPECT_EQ("", msg);
  24829. client.close();
  24830. }
  24831. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24832. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24833. "/ws-echo");
  24834. // First connection
  24835. ASSERT_TRUE(client.connect());
  24836. ASSERT_TRUE(client.send("first"));
  24837. std::string msg;
  24838. ASSERT_TRUE(client.read(msg));
  24839. EXPECT_EQ("first", msg);
  24840. client.close();
  24841. EXPECT_FALSE(client.is_open());
  24842. // Reconnect using the same client object
  24843. ASSERT_TRUE(client.connect());
  24844. ASSERT_TRUE(client.is_open());
  24845. ASSERT_TRUE(client.send("second"));
  24846. ASSERT_TRUE(client.read(msg));
  24847. EXPECT_EQ("second", msg);
  24848. client.close();
  24849. }
  24850. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24851. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24852. "/ws-close-status");
  24853. ASSERT_TRUE(client.connect());
  24854. // Trigger the server to close with GoingAway status
  24855. ASSERT_TRUE(client.send("trigger"));
  24856. // read() should return false after receiving the close frame
  24857. std::string msg;
  24858. EXPECT_FALSE(client.read(msg));
  24859. EXPECT_FALSE(client.is_open());
  24860. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  24861. EXPECT_EQ("shutting down", client.close_reason());
  24862. // A copy, so it outlives a reconnect that replaces the connection
  24863. static_assert(
  24864. std::is_same<decltype(client.close_reason()), std::string>::value, "");
  24865. }
  24866. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24868. "/ws-echo");
  24869. EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
  24870. ASSERT_TRUE(client.connect());
  24871. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24872. EXPECT_FALSE(client.is_open());
  24873. // The server echoes the Close it receives
  24874. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  24875. EXPECT_EQ("client leaving", client.close_reason());
  24876. }
  24877. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24878. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24879. ws::WebSocketClient client(
  24880. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24881. ASSERT_TRUE(client.connect());
  24882. // Server should have selected graphql-ws
  24883. EXPECT_EQ("graphql-ws", client.subprotocol());
  24884. client.close();
  24885. }
  24886. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24887. Headers headers;
  24888. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24889. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24890. ws::WebSocketClient client(
  24891. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24892. ASSERT_TRUE(client.connect());
  24893. // The offer on the second field line counts too, so graphql-ws is selected
  24894. EXPECT_EQ("graphql-ws", client.subprotocol());
  24895. client.close();
  24896. }
  24897. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24898. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24899. ws::WebSocketClient client(
  24900. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24901. ASSERT_TRUE(client.connect());
  24902. // Server should not have selected any subprotocol
  24903. EXPECT_TRUE(client.subprotocol().empty());
  24904. client.close();
  24905. }
  24906. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24907. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24908. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24909. "/ws-subprotocol-unoffered",
  24910. headers);
  24911. ASSERT_TRUE(client.connect());
  24912. EXPECT_TRUE(client.subprotocol().empty());
  24913. client.close();
  24914. }
  24915. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24916. // Connect without requesting any subprotocol
  24917. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24918. "/ws-subprotocol");
  24919. ASSERT_TRUE(client.connect());
  24920. EXPECT_TRUE(client.subprotocol().empty());
  24921. client.close();
  24922. }
  24923. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24924. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24925. "/ws-echo");
  24926. client.set_tcp_nodelay(true);
  24927. client.set_connection_timeout(3, 0);
  24928. bool socket_options_called = false;
  24929. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24930. ASSERT_TRUE(client.connect());
  24931. ASSERT_TRUE(client.is_open());
  24932. EXPECT_TRUE(socket_options_called);
  24933. ASSERT_TRUE(client.send("hello"));
  24934. std::string msg;
  24935. auto result = client.read(msg);
  24936. EXPECT_EQ(result, ws::ReadResult::Text);
  24937. EXPECT_EQ(msg, "hello");
  24938. client.close();
  24939. }
  24940. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24941. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24942. "/ws-echo");
  24943. client.set_connection_timeout(std::chrono::seconds(3));
  24944. client.set_write_timeout(std::chrono::seconds(3));
  24945. // A sub-second remainder exercises the seconds/microseconds split.
  24946. client.set_read_timeout(std::chrono::milliseconds(1500));
  24947. ASSERT_TRUE(client.connect());
  24948. auto start = std::chrono::steady_clock::now();
  24949. std::string msg;
  24950. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24951. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24952. std::chrono::steady_clock::now() - start)
  24953. .count();
  24954. // Above 1s so that dropping the microseconds half of the split fails here.
  24955. // Ignoring the setter altogether would not reach this line at all: a client
  24956. // waits forever by default.
  24957. EXPECT_GE(elapsed, 1400);
  24958. EXPECT_LT(elapsed, 30000);
  24959. }
  24960. #ifndef _WIN32
  24961. // A send() that times out after part of the data went out returns the count
  24962. // written so far. Every byte of the frame must still be sent, or the peer reads
  24963. // the next frame's header and payload as the rest of this one.
  24964. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24965. signal(SIGPIPE, SIG_IGN);
  24966. const std::string large(4 * 1024 * 1024, 'A');
  24967. std::atomic<bool> large_sent{false};
  24968. std::atomic<bool> small_sent{false};
  24969. Server svr;
  24970. svr.set_write_timeout(0, 500000);
  24971. svr.set_socket_options([](socket_t sock) {
  24972. int size = 8192;
  24973. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  24974. reinterpret_cast<const char *>(&size), sizeof(size));
  24975. });
  24976. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24977. large_sent = ws.send(large.data(), large.size());
  24978. small_sent = ws.send("after");
  24979. std::string msg;
  24980. while (ws.read(msg)) {}
  24981. });
  24982. auto port = svr.bind_to_any_port(HOST);
  24983. std::thread t([&]() { svr.listen_after_bind(); });
  24984. auto se = detail::scope_exit([&] {
  24985. svr.stop();
  24986. t.join();
  24987. });
  24988. svr.wait_until_ready();
  24989. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  24990. std::to_string(port) + "/ws");
  24991. client.set_read_timeout(5);
  24992. client.set_socket_options([](socket_t sock) {
  24993. int size = 8192;
  24994. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  24995. reinterpret_cast<const char *>(&size), sizeof(size));
  24996. });
  24997. ASSERT_TRUE(client.connect());
  24998. // Outlast the server's write timeout, then drain.
  24999. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25000. std::string msg;
  25001. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25002. EXPECT_TRUE(msg == large);
  25003. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25004. EXPECT_EQ("after", msg);
  25005. EXPECT_TRUE(large_sent);
  25006. EXPECT_TRUE(small_sent);
  25007. client.close();
  25008. }
  25009. // A send() that fails partway leaves a frame on the wire whose header announces
  25010. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25011. // as the rest of it and a later payload's bytes as a frame of their own.
  25012. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25013. signal(SIGPIPE, SIG_IGN);
  25014. const std::string large(4 * 1024 * 1024, 'A');
  25015. std::atomic<bool> large_sent{true};
  25016. std::atomic<bool> open_after_failure{true};
  25017. std::atomic<bool> handler_done{false};
  25018. Server svr;
  25019. svr.set_write_timeout(0, 200000);
  25020. svr.set_socket_options([](socket_t sock) {
  25021. int size = 8192;
  25022. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25023. reinterpret_cast<const char *>(&size), sizeof(size));
  25024. });
  25025. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25026. large_sent = ws.send(large.data(), large.size());
  25027. open_after_failure = ws.is_open();
  25028. handler_done = true;
  25029. });
  25030. auto port = svr.bind_to_any_port(HOST);
  25031. std::thread t([&]() { svr.listen_after_bind(); });
  25032. auto se = detail::scope_exit([&] {
  25033. svr.stop();
  25034. t.join();
  25035. });
  25036. svr.wait_until_ready();
  25037. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25038. std::to_string(port) + "/ws");
  25039. client.set_socket_options([](socket_t sock) {
  25040. int size = 8192;
  25041. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25042. reinterpret_cast<const char *>(&size), sizeof(size));
  25043. });
  25044. ASSERT_TRUE(client.connect());
  25045. // Read nothing, so the server's write times out partway through the frame.
  25046. for (int i = 0; i < 100 && !handler_done; i++) {
  25047. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25048. }
  25049. ASSERT_TRUE(handler_done);
  25050. ASSERT_FALSE(large_sent);
  25051. EXPECT_FALSE(open_after_failure);
  25052. client.close();
  25053. }
  25054. #endif
  25055. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25056. Server svr;
  25057. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25058. if (!req.has_header("Authorization")) {
  25059. res.status = StatusCode::Unauthorized_401;
  25060. res.set_content("Unauthorized", "text/plain");
  25061. return Server::HandlerResponse::Handled;
  25062. }
  25063. return Server::HandlerResponse::Unhandled;
  25064. });
  25065. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25066. std::string msg;
  25067. while (ws.read(msg)) {
  25068. ws.send(msg);
  25069. }
  25070. });
  25071. auto port = svr.bind_to_any_port("localhost");
  25072. std::thread t([&]() { svr.listen_after_bind(); });
  25073. svr.wait_until_ready();
  25074. // Without Authorization header - should be rejected before upgrade
  25075. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25076. EXPECT_FALSE(client1.connect());
  25077. // The rejection is framed like any other HTTP response
  25078. {
  25079. Client cli("localhost", port);
  25080. Headers headers = {{"Upgrade", "websocket"},
  25081. {"Connection", "Upgrade"},
  25082. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25083. {"Sec-WebSocket-Version", "13"}};
  25084. auto res = cli.Get("/ws", headers);
  25085. ASSERT_TRUE(res);
  25086. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25087. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25088. EXPECT_EQ("Unauthorized", res->body);
  25089. }
  25090. // With Authorization header - should succeed
  25091. Headers headers = {{"Authorization", "Bearer token123"}};
  25092. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25093. headers);
  25094. ASSERT_TRUE(client2.connect());
  25095. ASSERT_TRUE(client2.send("hello"));
  25096. std::string msg;
  25097. ASSERT_TRUE(client2.read(msg));
  25098. EXPECT_EQ("hello", msg);
  25099. client2.close();
  25100. svr.stop();
  25101. t.join();
  25102. }
  25103. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25104. Server svr;
  25105. std::atomic<int> pre_routing_calls{0};
  25106. std::atomic<int> pre_request_calls{0};
  25107. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25108. pre_routing_calls++;
  25109. if (req.path == "/handled") {
  25110. res.set_content("handled", "text/plain");
  25111. return Server::HandlerResponse::Handled;
  25112. }
  25113. return Server::HandlerResponse::Unhandled;
  25114. });
  25115. svr.set_pre_request_handler([&](const Request &, Response &) {
  25116. pre_request_calls++;
  25117. return Server::HandlerResponse::Unhandled;
  25118. });
  25119. svr.Get("/http", [](const Request &, Response &res) {
  25120. res.set_content("http", "text/plain");
  25121. });
  25122. svr.WebSocket("/ws",
  25123. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25124. auto port = svr.bind_to_any_port("localhost");
  25125. std::thread t([&]() { svr.listen_after_bind(); });
  25126. auto se = detail::scope_exit([&] {
  25127. svr.stop();
  25128. t.join();
  25129. });
  25130. svr.wait_until_ready();
  25131. Headers upgrade = {{"Upgrade", "websocket"},
  25132. {"Connection", "Upgrade"},
  25133. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25134. {"Sec-WebSocket-Version", "13"}};
  25135. auto get = [&](const char *path) {
  25136. pre_routing_calls = 0;
  25137. return Client("localhost", port).Get(path, upgrade);
  25138. };
  25139. // No WebSocket route, but an HTTP one
  25140. auto res = get("/http");
  25141. ASSERT_TRUE(res);
  25142. EXPECT_EQ(StatusCode::OK_200, res->status);
  25143. EXPECT_EQ("http", res->body);
  25144. EXPECT_EQ(1, pre_routing_calls);
  25145. EXPECT_EQ(1, pre_request_calls);
  25146. // No route at all
  25147. res = get("/none");
  25148. ASSERT_TRUE(res);
  25149. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25150. EXPECT_EQ(1, pre_routing_calls);
  25151. // Answered by the pre-routing handler
  25152. res = get("/handled");
  25153. ASSERT_TRUE(res);
  25154. EXPECT_EQ(StatusCode::OK_200, res->status);
  25155. EXPECT_EQ("handled", res->body);
  25156. EXPECT_EQ(1, pre_routing_calls);
  25157. // A WebSocket route
  25158. pre_routing_calls = 0;
  25159. pre_request_calls = 0;
  25160. {
  25161. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25162. "/ws");
  25163. ASSERT_TRUE(client.connect());
  25164. std::string msg;
  25165. ASSERT_TRUE(client.read(msg));
  25166. EXPECT_EQ("ws", msg);
  25167. client.close();
  25168. }
  25169. EXPECT_EQ(1, pre_routing_calls);
  25170. EXPECT_EQ(1, pre_request_calls);
  25171. }
  25172. // An upgrade request answered by a hook leaves its body unread, so that body
  25173. // must not be served as the next request on the connection.
  25174. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25175. Server svr;
  25176. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25177. if (req.path == "/pre-routing") {
  25178. res.set_content("pre-routing", "text/plain");
  25179. return Server::HandlerResponse::Handled;
  25180. }
  25181. return Server::HandlerResponse::Unhandled;
  25182. });
  25183. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25184. if (req.matched_route == "/pre-request") {
  25185. res.set_content("pre-request", "text/plain");
  25186. return Server::HandlerResponse::Handled;
  25187. }
  25188. return Server::HandlerResponse::Unhandled;
  25189. });
  25190. svr.Get("/smuggled", [](const Request &, Response &res) {
  25191. res.set_content("smuggled", "text/plain");
  25192. });
  25193. svr.WebSocket("/pre-request",
  25194. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25195. auto port = svr.bind_to_any_port(HOST);
  25196. std::thread t([&]() { svr.listen_after_bind(); });
  25197. auto se = detail::scope_exit([&] {
  25198. svr.stop();
  25199. t.join();
  25200. });
  25201. svr.wait_until_ready();
  25202. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25203. for (auto path : {"/pre-routing", "/pre-request"}) {
  25204. std::string req = std::string("GET ") + path +
  25205. " HTTP/1.1\r\n"
  25206. "Host: localhost\r\n"
  25207. "Upgrade: websocket\r\n"
  25208. "Connection: Upgrade\r\n"
  25209. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25210. "Sec-WebSocket-Version: 13\r\n"
  25211. "Content-Length: " +
  25212. std::to_string(body.size()) + "\r\n\r\n" + body;
  25213. std::string res;
  25214. ASSERT_TRUE(send_request(5, req, &res, port));
  25215. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25216. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25217. // Only one response, and the body was not served as a request
  25218. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25219. }
  25220. }
  25221. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25222. Server svr;
  25223. std::atomic<int> pre_request_calls{0};
  25224. std::atomic<bool> route_matched{false};
  25225. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25226. pre_request_calls++;
  25227. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25228. if (req.get_header_value("Authorization") != "Bearer token123") {
  25229. res.status = StatusCode::Unauthorized_401;
  25230. res.set_content("Unauthorized", "text/plain");
  25231. return Server::HandlerResponse::Handled;
  25232. }
  25233. return Server::HandlerResponse::Unhandled;
  25234. });
  25235. std::atomic<bool> handler_called{false};
  25236. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25237. handler_called = true;
  25238. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25239. });
  25240. auto port = svr.bind_to_any_port("localhost");
  25241. std::thread t([&]() { svr.listen_after_bind(); });
  25242. svr.wait_until_ready();
  25243. // Without Authorization header - should be rejected before upgrade
  25244. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25245. "/ws/1");
  25246. EXPECT_FALSE(client1.connect());
  25247. EXPECT_FALSE(handler_called);
  25248. EXPECT_EQ(1, pre_request_calls);
  25249. EXPECT_TRUE(route_matched);
  25250. // The rejection is an ordinary HTTP response, not a protocol switch
  25251. {
  25252. Client cli("localhost", port);
  25253. Headers headers = {{"Upgrade", "websocket"},
  25254. {"Connection", "Upgrade"},
  25255. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25256. {"Sec-WebSocket-Version", "13"}};
  25257. auto res = cli.Get("/ws/1", headers);
  25258. ASSERT_TRUE(res);
  25259. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25260. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25261. EXPECT_EQ("Unauthorized", res->body);
  25262. }
  25263. EXPECT_FALSE(handler_called);
  25264. // With Authorization header - should succeed
  25265. Headers headers = {{"Authorization", "Bearer token123"}};
  25266. ws::WebSocketClient client2(
  25267. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25268. ASSERT_TRUE(client2.connect());
  25269. std::string msg;
  25270. ASSERT_TRUE(client2.read(msg));
  25271. EXPECT_EQ("/ws/:id 2", msg);
  25272. EXPECT_TRUE(handler_called);
  25273. client2.close();
  25274. svr.stop();
  25275. t.join();
  25276. }
  25277. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25278. static Headers websocket_upgrade_headers() {
  25279. return {{"Upgrade", "websocket"},
  25280. {"Connection", "Upgrade"},
  25281. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25282. {"Sec-WebSocket-Version", "13"},
  25283. {"Sec-WebSocket-Protocol", "chat"}};
  25284. }
  25285. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25286. Server svr;
  25287. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25288. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25289. return Server::HandlerResponse::Unhandled;
  25290. });
  25291. svr.set_pre_request_handler([](const Request &req, Response &) {
  25292. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25293. return Server::HandlerResponse::Unhandled;
  25294. });
  25295. svr.set_exception_handler(
  25296. [](const Request &, Response &res, std::exception_ptr ep) {
  25297. try {
  25298. std::rethrow_exception(ep);
  25299. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25300. });
  25301. auto handler = [](const Request &, ws::WebSocket &) {};
  25302. svr.WebSocket("/pre-routing", handler);
  25303. svr.WebSocket("/pre-request", handler);
  25304. svr.WebSocket("/sub-protocol", handler,
  25305. [](const std::vector<std::string> &) -> std::string {
  25306. throw std::runtime_error("/sub-protocol");
  25307. });
  25308. auto port = svr.bind_to_any_port(HOST);
  25309. ASSERT_GT(port, 0);
  25310. thread t = thread([&] { svr.listen_after_bind(); });
  25311. auto se = detail::scope_exit([&] {
  25312. svr.stop();
  25313. t.join();
  25314. ASSERT_FALSE(svr.is_running());
  25315. });
  25316. svr.wait_until_ready();
  25317. Client cli(HOST, port);
  25318. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25319. auto res = cli.Get(path, websocket_upgrade_headers());
  25320. if (!res) {
  25321. ADD_FAILURE() << path << ": " << to_string(res.error());
  25322. continue;
  25323. }
  25324. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25325. EXPECT_EQ(path, res->body);
  25326. }
  25327. }
  25328. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25329. Server svr;
  25330. svr.set_pre_routing_handler(
  25331. [](const Request &, Response &) -> Server::HandlerResponse {
  25332. throw std::runtime_error("pre-routing");
  25333. });
  25334. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25335. auto port = svr.bind_to_any_port(HOST);
  25336. ASSERT_GT(port, 0);
  25337. thread t = thread([&] { svr.listen_after_bind(); });
  25338. auto se = detail::scope_exit([&] {
  25339. svr.stop();
  25340. t.join();
  25341. ASSERT_FALSE(svr.is_running());
  25342. });
  25343. svr.wait_until_ready();
  25344. Client cli(HOST, port);
  25345. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25346. ASSERT_TRUE(res) << to_string(res.error());
  25347. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25348. }
  25349. #endif
  25350. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25351. Server svr;
  25352. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25353. // A read timeout is how a handler gets control back. Without it, a handler
  25354. // parked in read() can never write on the connection it is reading.
  25355. ws.set_read_timeout(std::chrono::milliseconds(100));
  25356. std::string msg;
  25357. while (ws.is_open()) {
  25358. auto r = ws.read(msg);
  25359. if (r == httplib::ws::Timeout) {
  25360. ws.send("tick");
  25361. continue;
  25362. }
  25363. if (r == httplib::ws::Fail) { break; }
  25364. ws.send(msg);
  25365. }
  25366. });
  25367. auto port = svr.bind_to_any_port("localhost");
  25368. std::thread t([&]() { svr.listen_after_bind(); });
  25369. svr.wait_until_ready();
  25370. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25371. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25372. ASSERT_TRUE(client.connect());
  25373. // The client sends nothing, so anything it receives came out of the
  25374. // handler's timeout path.
  25375. std::string msg;
  25376. ASSERT_EQ(client.read(msg), ws::Text);
  25377. EXPECT_EQ("tick", msg);
  25378. client.close();
  25379. svr.stop();
  25380. t.join();
  25381. }
  25382. // Stream::read may return fewer bytes than asked for. This is that contract at
  25383. // its worst -- one byte per call -- which is what a frame header straddling a
  25384. // read buffer's boundary looks like to the frame parser.
  25385. class WsByteAtATimeStream : public Stream {
  25386. public:
  25387. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25388. bool is_readable() const override { return true; }
  25389. bool wait_readable() const override { return true; }
  25390. bool wait_writable() const override { return true; }
  25391. ssize_t read(char *ptr, size_t size) override {
  25392. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25393. *ptr = data_[pos_++];
  25394. return 1;
  25395. }
  25396. ssize_t write(const char *, size_t size) override {
  25397. return static_cast<ssize_t>(size);
  25398. }
  25399. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25400. ip = "127.0.0.1";
  25401. port = 0;
  25402. }
  25403. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25404. ip = "127.0.0.1";
  25405. port = 0;
  25406. }
  25407. socket_t socket() const override { return INVALID_SOCKET; }
  25408. time_t duration() const override { return 0; }
  25409. private:
  25410. std::string data_;
  25411. size_t pos_ = 0;
  25412. };
  25413. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25414. // The payload uses the 16-bit extended length, so the header, the length
  25415. // and the mask key are all multi-byte fields here. Each used to be read
  25416. // with a single read() call, which fails as soon as one is split. The
  25417. // payload is also a little over one read chunk, so it is read in two.
  25418. std::string body;
  25419. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25420. body += static_cast<char>(i % 251);
  25421. }
  25422. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25423. std::string frame;
  25424. frame += static_cast<char>(0x81); // FIN + Text
  25425. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25426. frame += static_cast<char>(body.size() >> 8);
  25427. frame += static_cast<char>(body.size() & 0xff);
  25428. for (size_t i = 0; i < 4; i++) {
  25429. frame += static_cast<char>(mask[i]);
  25430. }
  25431. for (size_t i = 0; i < body.size(); i++) {
  25432. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25433. }
  25434. WsByteAtATimeStream strm(frame);
  25435. ws::Opcode opcode;
  25436. std::string payload;
  25437. bool fin = false;
  25438. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25439. /*expect_masked=*/true, body.size()),
  25440. ws::impl::FrameRead::Ok);
  25441. EXPECT_TRUE(fin);
  25442. EXPECT_EQ(opcode, ws::Opcode::Text);
  25443. EXPECT_EQ(payload, body);
  25444. }
  25445. // Keeps what is written, counting the writes, and reads it back.
  25446. class WsWriteCountingStream : public Stream {
  25447. public:
  25448. bool is_readable() const override { return true; }
  25449. bool wait_readable() const override { return true; }
  25450. bool wait_writable() const override { return true; }
  25451. ssize_t read(char *ptr, size_t size) override {
  25452. auto n = (std::min)(size, data_.size() - pos_);
  25453. if (n == 0) { return 0; }
  25454. memcpy(ptr, data_.data() + pos_, n);
  25455. pos_ += n;
  25456. return static_cast<ssize_t>(n);
  25457. }
  25458. ssize_t write(const char *ptr, size_t size) override {
  25459. writes++;
  25460. data_.append(ptr, size);
  25461. return static_cast<ssize_t>(size);
  25462. }
  25463. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25464. ip = "127.0.0.1";
  25465. port = 0;
  25466. }
  25467. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25468. ip = "127.0.0.1";
  25469. port = 0;
  25470. }
  25471. socket_t socket() const override { return INVALID_SOCKET; }
  25472. time_t duration() const override { return 0; }
  25473. int writes = 0;
  25474. private:
  25475. std::string data_;
  25476. size_t pos_ = 0;
  25477. };
  25478. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25479. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25480. // masked and not, reads back as written; a payload over one chunk follows
  25481. // its first in more writes.
  25482. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25483. for (auto mask : {false, true}) {
  25484. std::string body(len, '\0');
  25485. for (size_t i = 0; i < len; i++) {
  25486. body[i] = static_cast<char>(i % 251);
  25487. }
  25488. WsWriteCountingStream strm;
  25489. ASSERT_TRUE(detail::write_websocket_frame(
  25490. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25491. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25492. ws::Opcode opcode;
  25493. std::string payload;
  25494. bool fin = false;
  25495. ASSERT_EQ(
  25496. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25497. ws::impl::FrameRead::Ok)
  25498. << len << " " << mask;
  25499. EXPECT_TRUE(fin);
  25500. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25501. EXPECT_EQ(body, payload) << len << " " << mask;
  25502. }
  25503. }
  25504. }
  25505. // Hands out its pieces one read at a time, timing out between each two.
  25506. class WsTimeoutBetweenPiecesStream : public Stream {
  25507. public:
  25508. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25509. : pieces_(std::move(pieces)) {}
  25510. bool is_readable() const override { return true; }
  25511. bool wait_readable() const override { return true; }
  25512. bool wait_writable() const override { return true; }
  25513. ssize_t read(char *ptr, size_t size) override {
  25514. if (time_out_) {
  25515. time_out_ = false;
  25516. error_ = Error::Timeout;
  25517. return -1;
  25518. }
  25519. if (i_ >= pieces_.size()) {
  25520. error_ = Error::ConnectionClosed;
  25521. return 0;
  25522. }
  25523. auto &piece = pieces_[i_];
  25524. auto n = (std::min)(size, piece.size() - at_);
  25525. memcpy(ptr, piece.data() + at_, n);
  25526. at_ += n;
  25527. if (at_ == piece.size()) {
  25528. i_++;
  25529. at_ = 0;
  25530. time_out_ = true;
  25531. }
  25532. return static_cast<ssize_t>(n);
  25533. }
  25534. ssize_t write(const char *, size_t size) override {
  25535. return static_cast<ssize_t>(size);
  25536. }
  25537. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25538. ip = "127.0.0.1";
  25539. port = 0;
  25540. }
  25541. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25542. ip = "127.0.0.1";
  25543. port = 0;
  25544. }
  25545. socket_t socket() const override { return INVALID_SOCKET; }
  25546. time_t duration() const override { return 0; }
  25547. private:
  25548. std::vector<std::string> pieces_;
  25549. size_t i_ = 0;
  25550. size_t at_ = 0;
  25551. bool time_out_ = false;
  25552. };
  25553. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25554. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25555. std::string frame = "\x81\x85";
  25556. frame.append(4, '\0');
  25557. frame += "Hello";
  25558. // The header's first byte, then its second with half the mask key, then
  25559. // the rest
  25560. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25561. frame.substr(4)};
  25562. WsTimeoutBetweenPiecesStream strm(pieces);
  25563. ws::impl::FrameReader reader;
  25564. ws::Opcode opcode;
  25565. std::string payload;
  25566. bool fin = false;
  25567. for (int i = 0; i < 2; i++) {
  25568. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25569. reader.read(strm, opcode, payload, fin, true, 0));
  25570. EXPECT_TRUE(reader.begun());
  25571. }
  25572. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25573. reader.read(strm, opcode, payload, fin, true, 0));
  25574. EXPECT_FALSE(reader.begun());
  25575. EXPECT_TRUE(fin);
  25576. EXPECT_EQ(ws::Opcode::Text, opcode);
  25577. EXPECT_EQ("Hello", payload);
  25578. // Read in one go, the frame cannot be gone on with after a timeout
  25579. WsTimeoutBetweenPiecesStream again(pieces);
  25580. EXPECT_EQ(
  25581. ws::impl::FrameRead::Fail,
  25582. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25583. }
  25584. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25585. std::string body(2000, 'x');
  25586. std::string frame;
  25587. frame += static_cast<char>(0x82); // FIN + Binary
  25588. frame += static_cast<char>(126); // 16-bit length follows
  25589. frame += static_cast<char>(body.size() >> 8);
  25590. frame += static_cast<char>(body.size() & 0xff);
  25591. frame += body;
  25592. detail::BufferStream strm;
  25593. strm.write(frame.data(), frame.size());
  25594. ws::Opcode opcode;
  25595. std::string payload;
  25596. bool fin;
  25597. EXPECT_EQ(
  25598. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25599. ws::impl::FrameRead::Ok);
  25600. EXPECT_EQ(body, payload);
  25601. }
  25602. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25603. // The header announces the largest payload allowed, and only 3 bytes of it
  25604. // ever arrive.
  25605. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25606. std::string frame;
  25607. frame += static_cast<char>(0x82); // FIN + Binary
  25608. frame += static_cast<char>(127); // 64-bit length follows
  25609. for (int shift = 56; shift >= 0; shift -= 8) {
  25610. frame += static_cast<char>((len >> shift) & 0xff);
  25611. }
  25612. frame += "abc";
  25613. detail::BufferStream strm;
  25614. strm.write(frame.data(), frame.size());
  25615. ws::Opcode opcode;
  25616. std::string payload;
  25617. bool fin;
  25618. EXPECT_EQ(
  25619. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25620. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25621. ws::impl::FrameRead::Fail);
  25622. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25623. }
  25624. TEST(WebSocketTest, QueryStringInHandshake) {
  25625. Server svr;
  25626. std::mutex mtx;
  25627. std::string received_target;
  25628. std::string received_token;
  25629. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25630. {
  25631. std::lock_guard<std::mutex> lock(mtx);
  25632. received_target = req.target;
  25633. if (req.has_param("token")) {
  25634. received_token = req.get_param_value("token");
  25635. }
  25636. }
  25637. std::string msg;
  25638. while (ws.read(msg)) {
  25639. ws.send(msg);
  25640. }
  25641. });
  25642. auto port = svr.bind_to_any_port("localhost");
  25643. std::thread t([&]() { svr.listen_after_bind(); });
  25644. svr.wait_until_ready();
  25645. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25646. "/ws?token=ABC&session=123");
  25647. ASSERT_TRUE(client.connect());
  25648. // Round-trip ensures the handler has run and captured the request.
  25649. ASSERT_TRUE(client.send("hello"));
  25650. std::string msg;
  25651. ASSERT_TRUE(client.read(msg));
  25652. EXPECT_EQ("hello", msg);
  25653. client.close();
  25654. {
  25655. std::lock_guard<std::mutex> lock(mtx);
  25656. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25657. EXPECT_EQ("ABC", received_token);
  25658. }
  25659. svr.stop();
  25660. t.join();
  25661. }
  25662. // Run a handshake against a throwaway server and hand the request the server
  25663. // received back to the caller, so tests can assert on the headers the client
  25664. // actually put on the wire.
  25665. static void capture_websocket_handshake_request(
  25666. const Headers &client_headers,
  25667. std::function<void(const Request &, int port)> verify) {
  25668. Server svr;
  25669. std::mutex mtx;
  25670. Request received;
  25671. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25672. {
  25673. std::lock_guard<std::mutex> lock(mtx);
  25674. received = req;
  25675. }
  25676. std::string msg;
  25677. while (ws.read(msg)) {
  25678. ws.send(msg);
  25679. }
  25680. });
  25681. auto port = svr.bind_to_any_port("localhost");
  25682. std::thread t([&]() { svr.listen_after_bind(); });
  25683. auto se = detail::scope_exit([&] {
  25684. svr.stop();
  25685. t.join();
  25686. });
  25687. svr.wait_until_ready();
  25688. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25689. client_headers);
  25690. ASSERT_TRUE(client.connect());
  25691. ASSERT_TRUE(client.send("hello"));
  25692. std::string msg;
  25693. ASSERT_TRUE(client.read(msg));
  25694. client.close();
  25695. {
  25696. std::lock_guard<std::mutex> lock(mtx);
  25697. verify(received, port);
  25698. }
  25699. }
  25700. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25701. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25702. // Non-default port must be present in the Host header. Default ports
  25703. // (80/443) are omitted; that logic is covered by
  25704. // MakeHostAndPortStringTest.
  25705. EXPECT_EQ("localhost:" + std::to_string(port),
  25706. req.get_header_value("Host"));
  25707. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25708. req.get_header_value("User-Agent"));
  25709. EXPECT_FALSE(req.has_header("Accept"));
  25710. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25711. EXPECT_FALSE(req.has_header("Content-Length"));
  25712. });
  25713. }
  25714. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25715. capture_websocket_handshake_request(
  25716. {{"Host", "example.com"},
  25717. {"User-Agent", "custom-agent"},
  25718. {"X-Custom", "value"}},
  25719. [](const Request &req, int) {
  25720. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25721. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25722. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25723. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25724. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25725. });
  25726. }
  25727. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25728. capture_websocket_handshake_request(
  25729. {{"Upgrade", "bogus"},
  25730. {"Connection", "close"},
  25731. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25732. {"Sec-WebSocket-Version", "8"}},
  25733. [](const Request &req, int) {
  25734. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25735. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25736. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25737. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25738. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25739. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25740. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25741. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25742. req.get_header_value("Sec-WebSocket-Key"));
  25743. });
  25744. }
  25745. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25746. // A header the client refuses to send must abort the handshake before any
  25747. // part of it reaches the wire; a lone request line would otherwise sit in
  25748. // the peer's buffer as a truncated request.
  25749. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25750. ASSERT_NE(INVALID_SOCKET, srv);
  25751. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25752. sockaddr_in addr{};
  25753. addr.sin_family = AF_INET;
  25754. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25755. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25756. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25757. ASSERT_EQ(0, ::listen(srv, 1));
  25758. sockaddr_in bound{};
  25759. socklen_t bound_len = sizeof(bound);
  25760. ASSERT_EQ(
  25761. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25762. auto port = ntohs(bound.sin_port);
  25763. ssize_t received = -1;
  25764. std::thread t([&] {
  25765. // Bound every blocking call so a regression fails the test with a bad
  25766. // value instead of hanging the suite.
  25767. fd_set rfds;
  25768. FD_ZERO(&rfds);
  25769. FD_SET(srv, &rfds);
  25770. timeval tv{5, 0};
  25771. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25772. 0) {
  25773. return;
  25774. }
  25775. sockaddr_in cli_addr{};
  25776. socklen_t cli_len = sizeof(cli_addr);
  25777. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25778. if (cli == INVALID_SOCKET) { return; }
  25779. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25780. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25781. char buf[4096];
  25782. received = ::recv(cli, buf, sizeof(buf), 0);
  25783. });
  25784. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25785. // connect() has already shut the socket down by the time it returns false,
  25786. // so the peer sees EOF without waiting for the client to be destroyed.
  25787. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25788. {{"X-Bad", "a\r\nInjected: 1"}});
  25789. EXPECT_FALSE(client.connect());
  25790. t.join();
  25791. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25792. EXPECT_EQ(0, received);
  25793. }
  25794. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25795. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25796. // contains "upgrade" as a substring is a different token and must not
  25797. // start a WebSocket handshake.
  25798. auto make_request = [](const std::vector<std::string> &connection_values) {
  25799. Request req;
  25800. req.method = "GET";
  25801. req.headers.emplace("Upgrade", "websocket");
  25802. for (const auto &value : connection_values) {
  25803. req.headers.emplace("Connection", value);
  25804. }
  25805. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25806. req.headers.emplace("Sec-WebSocket-Version", "13");
  25807. return req;
  25808. };
  25809. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25810. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25811. EXPECT_TRUE(
  25812. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25813. EXPECT_TRUE(
  25814. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25815. EXPECT_TRUE(
  25816. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25817. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25818. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25819. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25820. EXPECT_FALSE(
  25821. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25822. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25823. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25824. }
  25825. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25826. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25827. // asks recipients to match each protocol-name case-insensitively, and RFC
  25828. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25829. // client naming websocket alongside another protocol, or on a second field
  25830. // line, is offering websocket; a value that merely contains "websocket" as a
  25831. // substring is a different protocol name and is not.
  25832. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25833. Request req;
  25834. req.method = "GET";
  25835. for (const auto &value : upgrade_values) {
  25836. req.headers.emplace("Upgrade", value);
  25837. }
  25838. req.headers.emplace("Connection", "Upgrade");
  25839. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25840. req.headers.emplace("Sec-WebSocket-Version", "13");
  25841. return req;
  25842. };
  25843. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25844. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25845. EXPECT_TRUE(
  25846. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25847. EXPECT_TRUE(
  25848. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25849. EXPECT_TRUE(
  25850. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25851. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25852. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25853. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25854. EXPECT_FALSE(
  25855. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25856. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25857. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25858. }
  25859. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25860. Server svr;
  25861. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25862. auto port = svr.bind_to_any_port("localhost");
  25863. std::thread t([&]() { svr.listen_after_bind(); });
  25864. auto se = detail::scope_exit([&] {
  25865. svr.stop();
  25866. t.join();
  25867. });
  25868. svr.wait_until_ready();
  25869. Headers headers = {{"Upgrade", "websocket"},
  25870. {"Connection", "notupgrade"},
  25871. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25872. {"Sec-WebSocket-Version", "13"}};
  25873. Client cli("localhost", port);
  25874. auto res = cli.Get("/ws", headers);
  25875. // The route exists only as a WebSocket route, so a request that fails the
  25876. // handshake check falls through to ordinary routing.
  25877. ASSERT_TRUE(res);
  25878. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25879. }
  25880. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25881. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25882. // Connection value is the only thing left for the client to reject.
  25883. Server svr;
  25884. svr.Get("/ws", [](const Request &req, Response &res) {
  25885. res.status = StatusCode::SwitchingProtocol_101;
  25886. res.set_header("Upgrade", "websocket");
  25887. res.set_header("Connection", "notupgrade");
  25888. res.set_header("Sec-WebSocket-Accept",
  25889. detail::websocket_accept_key(
  25890. req.get_header_value("Sec-WebSocket-Key")));
  25891. });
  25892. auto port = svr.bind_to_any_port("localhost");
  25893. std::thread t([&]() { svr.listen_after_bind(); });
  25894. auto se = detail::scope_exit([&] {
  25895. svr.stop();
  25896. t.join();
  25897. });
  25898. svr.wait_until_ready();
  25899. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25900. auto res = client.connect();
  25901. EXPECT_FALSE(res);
  25902. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25903. EXPECT_FALSE(client.is_open());
  25904. }
  25905. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25906. Server svr;
  25907. svr.Get("/ws", [](const Request &req, Response &res) {
  25908. res.status = StatusCode::SwitchingProtocol_101;
  25909. res.set_header("Upgrade", "websocket");
  25910. res.set_header("Connection", "Upgrade");
  25911. res.set_header("Sec-WebSocket-Accept",
  25912. detail::websocket_accept_key(
  25913. req.get_header_value("Sec-WebSocket-Key")));
  25914. res.set_header("Sec-WebSocket-Protocol", "admin");
  25915. });
  25916. auto port = svr.bind_to_any_port("localhost");
  25917. std::thread t([&]() { svr.listen_after_bind(); });
  25918. auto se = detail::scope_exit([&] {
  25919. svr.stop();
  25920. t.join();
  25921. });
  25922. svr.wait_until_ready();
  25923. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25924. // Server selects a subprotocol the client never offered
  25925. {
  25926. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25927. ws::WebSocketClient client(url, headers);
  25928. auto res = client.connect();
  25929. EXPECT_FALSE(res);
  25930. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25931. EXPECT_FALSE(client.is_open());
  25932. EXPECT_TRUE(client.subprotocol().empty());
  25933. }
  25934. // Client offered none but the server named one anyway
  25935. {
  25936. ws::WebSocketClient client(url);
  25937. auto res = client.connect();
  25938. EXPECT_FALSE(res);
  25939. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25940. EXPECT_FALSE(client.is_open());
  25941. EXPECT_TRUE(client.subprotocol().empty());
  25942. }
  25943. }
  25944. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25945. // The socket path doubles as the URL host, so it must not contain '/'.
  25946. const char *shard = getenv("GTEST_SHARD_INDEX");
  25947. const std::string sock_path =
  25948. shard ? std::string("httplib-ws-") + shard + ".sock"
  25949. : std::string("httplib-ws.sock");
  25950. std::remove(sock_path.c_str());
  25951. Server svr;
  25952. std::mutex mtx;
  25953. std::string received_host;
  25954. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25955. {
  25956. std::lock_guard<std::mutex> lock(mtx);
  25957. received_host = req.get_header_value("Host");
  25958. }
  25959. std::string msg;
  25960. while (ws.read(msg)) {
  25961. ws.send(msg);
  25962. }
  25963. });
  25964. svr.set_address_family(AF_UNIX);
  25965. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  25966. auto se = detail::scope_exit([&] {
  25967. svr.stop();
  25968. t.join();
  25969. std::remove(sock_path.c_str());
  25970. });
  25971. svr.wait_until_ready();
  25972. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  25973. client.set_address_family(AF_UNIX);
  25974. ASSERT_TRUE(client.connect());
  25975. ASSERT_TRUE(client.send("hello"));
  25976. std::string msg;
  25977. ASSERT_TRUE(client.read(msg));
  25978. client.close();
  25979. {
  25980. std::lock_guard<std::mutex> lock(mtx);
  25981. // There is no host:port for a Unix socket, so the same "localhost"
  25982. // placeholder the HTTP client uses is expected.
  25983. EXPECT_EQ("localhost", received_host);
  25984. }
  25985. }
  25986. // Two threads must never parse WebSocket frames from the same stream.
  25987. // close() used to read the peer's Close reply with its own frame read, so it
  25988. // raced a reader thread that was in the middle of a payload: the payload loop
  25989. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  25990. // so bytes taken by close() were replaced with bytes from further along the
  25991. // stream. The message kept its length and silently changed content.
  25992. //
  25993. // The raw peer below sends a frame header plus part of the payload, waits for
  25994. // the handler to call close(), and only then sends the rest. Whichever thread
  25995. // would win the race for those bytes, the message must arrive intact, because
  25996. // close() must not touch the stream while read() owns it.
  25997. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  25998. #ifndef _WIN32
  25999. signal(SIGPIPE, SIG_IGN);
  26000. #endif
  26001. const size_t payload_len = 120; // fits the 7-bit length field
  26002. const size_t prefix_len = 8;
  26003. const int attempts = 8;
  26004. std::string expected(payload_len, '\0');
  26005. for (size_t i = 0; i < payload_len; i++) {
  26006. expected[i] = static_cast<char>('a' + i % 26);
  26007. }
  26008. std::atomic<bool> peer_stalled{false};
  26009. std::atomic<bool> handler_done{false};
  26010. std::mutex received_mutex;
  26011. std::vector<std::string> received;
  26012. // Bound every wait, so a regression fails the test instead of hanging the
  26013. // suite.
  26014. auto wait_for = [](const std::atomic<bool> &flag) {
  26015. for (int i = 0; i < 500 && !flag; i++) {
  26016. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26017. }
  26018. };
  26019. Server svr;
  26020. svr.set_websocket_ping_interval(0);
  26021. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26022. std::thread reader([&]() {
  26023. std::string msg;
  26024. while (ws.read(msg)) {
  26025. std::lock_guard<std::mutex> guard(received_mutex);
  26026. received.push_back(msg);
  26027. }
  26028. });
  26029. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26030. // inside a frame when close() runs.
  26031. wait_for(peer_stalled);
  26032. ws.close();
  26033. reader.join();
  26034. handler_done = true;
  26035. });
  26036. auto port = svr.bind_to_any_port("127.0.0.1");
  26037. std::thread t([&]() { svr.listen_after_bind(); });
  26038. auto se = detail::scope_exit([&] {
  26039. svr.stop();
  26040. t.join();
  26041. });
  26042. svr.wait_until_ready();
  26043. auto send_bytes = [](socket_t s, const std::string &data) {
  26044. #ifdef _WIN32
  26045. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26046. #else
  26047. auto n = ::send(s, data.data(), data.size(), 0);
  26048. #endif
  26049. return n == static_cast<decltype(n)>(data.size());
  26050. };
  26051. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26052. // Every length used here fits the 7-bit length field.
  26053. auto masked_header = [](uint8_t first_byte, size_t len) {
  26054. std::string h;
  26055. h += static_cast<char>(first_byte);
  26056. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26057. h.append(4, '\0'); // mask key
  26058. return h;
  26059. };
  26060. for (int attempt = 0; attempt < attempts; attempt++) {
  26061. peer_stalled = false;
  26062. handler_done = false;
  26063. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26064. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26065. auto se_sock = detail::scope_exit([&] {
  26066. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26067. });
  26068. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26069. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26070. sockaddr_in addr{};
  26071. addr.sin_family = AF_INET;
  26072. addr.sin_port = htons(static_cast<uint16_t>(port));
  26073. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26074. ASSERT_EQ(
  26075. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26076. << "attempt " << attempt;
  26077. ASSERT_TRUE(send_bytes(sock,
  26078. "GET /ws HTTP/1.1\r\n"
  26079. "Host: 127.0.0.1\r\n"
  26080. "Upgrade: websocket\r\n"
  26081. "Connection: Upgrade\r\n"
  26082. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26083. "Sec-WebSocket-Version: 13\r\n"
  26084. "\r\n"))
  26085. << "attempt " << attempt;
  26086. std::string response;
  26087. while (response.find("\r\n\r\n") == std::string::npos) {
  26088. char buf[512];
  26089. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26090. if (n <= 0) { break; }
  26091. response.append(buf, static_cast<size_t>(n));
  26092. }
  26093. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26094. << "attempt " << attempt;
  26095. // Send the header of a Binary message but only the first prefix_len bytes
  26096. // of its payload, leaving the reader thread stalled inside the payload.
  26097. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26098. expected.substr(0, prefix_len)))
  26099. << "attempt " << attempt;
  26100. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26101. peer_stalled = true;
  26102. // Let close() send its Close frame and park in its own read before the
  26103. // rest of the payload arrives, so both threads are waiting for it.
  26104. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26105. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26106. close_frame += static_cast<char>(0x03); // status 1000
  26107. close_frame += static_cast<char>(0xE8);
  26108. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26109. << "attempt " << attempt;
  26110. // Closing the peer releases the reader thread even on the buggy path,
  26111. // where it waits for bytes another thread already consumed.
  26112. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26113. detail::close_socket(sock);
  26114. sock = INVALID_SOCKET;
  26115. wait_for(handler_done);
  26116. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26117. }
  26118. std::lock_guard<std::mutex> guard(received_mutex);
  26119. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26120. << "a message in flight when close() ran was dropped";
  26121. for (size_t i = 0; i < received.size(); i++) {
  26122. EXPECT_EQ(expected, received[i]) << "message " << i;
  26123. }
  26124. }
  26125. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26126. // returning the socket, or INVALID_SOCKET.
  26127. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26128. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26129. if (sock == INVALID_SOCKET) { return sock; }
  26130. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26131. sockaddr_in addr{};
  26132. addr.sin_family = AF_INET;
  26133. addr.sin_port = htons(static_cast<uint16_t>(port));
  26134. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26135. std::string req = "GET " + path +
  26136. " HTTP/1.1\r\n"
  26137. "Host: 127.0.0.1\r\n"
  26138. "Upgrade: websocket\r\n"
  26139. "Connection: Upgrade\r\n"
  26140. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26141. "Sec-WebSocket-Version: 13\r\n"
  26142. "\r\n";
  26143. std::string res;
  26144. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26145. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26146. static_cast<ssize_t>(req.size())) {
  26147. char c;
  26148. while (res.find("\r\n\r\n") == std::string::npos &&
  26149. ::recv(sock, &c, 1, 0) == 1) {
  26150. res += c;
  26151. }
  26152. }
  26153. if (res.find(" 101 ") == std::string::npos) {
  26154. detail::close_socket(sock);
  26155. return INVALID_SOCKET;
  26156. }
  26157. return sock;
  26158. }
  26159. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26160. // The payload must fit the 7-bit length field.
  26161. static std::string masked_frame(uint8_t first_byte,
  26162. const std::string &payload) {
  26163. std::string f;
  26164. f += static_cast<char>(first_byte);
  26165. f += static_cast<char>(0x80 | payload.size());
  26166. f.append(4, '\0');
  26167. return f + payload;
  26168. }
  26169. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26170. // server sends back, or what came before it closed.
  26171. static std::string raw_websocket_reply(int port, const std::string &frames,
  26172. size_t n) {
  26173. auto sock = connect_raw_websocket(port, "/ws");
  26174. if (sock == INVALID_SOCKET) { return std::string(); }
  26175. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26176. std::string reply;
  26177. char buf[256];
  26178. while (reply.size() < n) {
  26179. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26180. if (got <= 0) { break; }
  26181. reply.append(buf, static_cast<size_t>(got));
  26182. }
  26183. detail::close_socket(sock);
  26184. return reply;
  26185. }
  26186. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26187. std::atomic<bool> done{false};
  26188. std::string received;
  26189. Server svr;
  26190. svr.set_websocket_ping_interval(0);
  26191. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26192. std::string msg;
  26193. if (ws.read(msg) == ws::Binary) { received = msg; }
  26194. done = true;
  26195. });
  26196. auto port = svr.bind_to_any_port("127.0.0.1");
  26197. std::thread t([&]() { svr.listen_after_bind(); });
  26198. auto se = detail::scope_exit([&] {
  26199. svr.stop();
  26200. t.join();
  26201. });
  26202. svr.wait_until_ready();
  26203. auto sock = connect_raw_websocket(port, "/ws");
  26204. ASSERT_NE(INVALID_SOCKET, sock);
  26205. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26206. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26207. masked_frame(0x89, "p") + // FIN + Ping
  26208. masked_frame(0x80, "lo"); // FIN + Continuation
  26209. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26210. for (int i = 0; i < 500 && !done; i++) {
  26211. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26212. }
  26213. ASSERT_TRUE(done);
  26214. EXPECT_EQ("Hello", received);
  26215. // The Ping between the fragments is answered with a Pong.
  26216. char pong[3];
  26217. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26218. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26219. }
  26220. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26221. #ifndef _WIN32
  26222. signal(SIGPIPE, SIG_IGN);
  26223. #endif
  26224. std::atomic<bool> read_ended{false};
  26225. std::atomic<bool> sending{true};
  26226. Server svr;
  26227. svr.set_websocket_ping_interval(0);
  26228. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26229. std::thread reader([&]() {
  26230. std::string msg;
  26231. while (ws.read(msg)) {}
  26232. read_ended = true;
  26233. });
  26234. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26235. ws.close();
  26236. reader.join();
  26237. });
  26238. auto port = svr.bind_to_any_port("127.0.0.1");
  26239. std::thread t([&]() { svr.listen_after_bind(); });
  26240. auto se = detail::scope_exit([&] {
  26241. svr.stop();
  26242. t.join();
  26243. });
  26244. svr.wait_until_ready();
  26245. auto sock = connect_raw_websocket(port, "/ws");
  26246. ASSERT_NE(INVALID_SOCKET, sock);
  26247. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26248. // A Text message whose empty continuation frames never end
  26249. std::thread sender([&]() {
  26250. auto data = masked_frame(0x01, "");
  26251. while (sending) {
  26252. data += masked_frame(0x00, "");
  26253. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26254. return;
  26255. }
  26256. data.clear();
  26257. }
  26258. });
  26259. for (int i = 0; i < 300 && !read_ended; i++) {
  26260. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26261. }
  26262. sending = false;
  26263. sender.join();
  26264. EXPECT_TRUE(read_ended);
  26265. }
  26266. TEST(WebSocketTest, ServerMaxMessageLength) {
  26267. Server svr;
  26268. svr.set_websocket_ping_interval(0);
  26269. svr.set_websocket_max_message_length(100);
  26270. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26271. std::string msg;
  26272. while (ws.read(msg)) {
  26273. ws.send(msg);
  26274. }
  26275. });
  26276. auto port = svr.bind_to_any_port("127.0.0.1");
  26277. std::thread t([&]() { svr.listen_after_bind(); });
  26278. auto se = detail::scope_exit([&] {
  26279. svr.stop();
  26280. t.join();
  26281. });
  26282. svr.wait_until_ready();
  26283. const std::string ping(110, 'p');
  26284. const std::string half(50, 'a');
  26285. const std::string over(60, 'b');
  26286. const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
  26287. // A Ping longer than the limit is answered, since the limit is for
  26288. // messages. A message at the limit is echoed, and one over it is refused
  26289. // although each of its frames is within it.
  26290. EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
  26291. raw_websocket_reply(
  26292. port,
  26293. masked_frame(0x89, ping) + masked_frame(0x01, half) +
  26294. masked_frame(0x80, half) + masked_frame(0x01, over) +
  26295. masked_frame(0x80, over),
  26296. 2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
  26297. // A header that announces more than the limit is refused before its payload
  26298. EXPECT_EQ(too_big, raw_websocket_reply(port,
  26299. std::string("\x82\xfe\x03\xe8", 4) +
  26300. std::string(4, '\0'),
  26301. too_big.size()));
  26302. }
  26303. TEST(WebSocketTest, ClientMaxMessageLength) {
  26304. Server svr;
  26305. svr.set_websocket_ping_interval(0);
  26306. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26307. ws.send(std::string(1024, 'a'));
  26308. ws.send(std::string(2048, 'b'));
  26309. std::string msg;
  26310. while (ws.read(msg)) {}
  26311. });
  26312. auto port = svr.bind_to_any_port(HOST);
  26313. std::thread t([&]() { svr.listen_after_bind(); });
  26314. auto se = detail::scope_exit([&] {
  26315. svr.stop();
  26316. t.join();
  26317. });
  26318. svr.wait_until_ready();
  26319. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26320. client.set_read_timeout(5, 0);
  26321. client.set_websocket_max_message_length(1024);
  26322. ASSERT_TRUE(client.connect());
  26323. std::string msg;
  26324. ASSERT_EQ(ws::Text, client.read(msg));
  26325. EXPECT_EQ(1024u, msg.size());
  26326. EXPECT_EQ(ws::Fail, client.read(msg));
  26327. EXPECT_FALSE(client.is_open());
  26328. // 0 lifts the limit
  26329. client.set_websocket_max_message_length(0);
  26330. ASSERT_TRUE(client.connect());
  26331. EXPECT_EQ(ws::Text, client.read(msg));
  26332. EXPECT_EQ(ws::Text, client.read(msg));
  26333. EXPECT_EQ(2048u, msg.size());
  26334. }
  26335. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26336. Server svr;
  26337. svr.set_websocket_ping_interval(-1);
  26338. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26339. std::string msg;
  26340. while (ws.read(msg)) {}
  26341. });
  26342. auto port = svr.bind_to_any_port("127.0.0.1");
  26343. std::thread t([&]() { svr.listen_after_bind(); });
  26344. auto se = detail::scope_exit([&] {
  26345. svr.stop();
  26346. t.join();
  26347. });
  26348. svr.wait_until_ready();
  26349. auto sock = connect_raw_websocket(port, "/ws");
  26350. ASSERT_NE(INVALID_SOCKET, sock);
  26351. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26352. // Nothing comes while the client stays quiet.
  26353. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26354. char c;
  26355. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26356. }
  26357. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26358. // and that has to end a read() already waiting on the peer, on every platform.
  26359. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26360. // The peer sends no pings, and its handler never calls read(), which is
  26361. // where pongs are written.
  26362. std::mutex mutex;
  26363. std::condition_variable cv;
  26364. auto release = false;
  26365. svr.set_websocket_ping_interval(0);
  26366. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26367. std::unique_lock<std::mutex> lock(mutex);
  26368. cv.wait(lock, [&] { return release; });
  26369. });
  26370. auto port = svr.bind_to_any_port(HOST);
  26371. std::thread t([&]() { svr.listen_after_bind(); });
  26372. auto se = detail::scope_exit([&] {
  26373. {
  26374. std::lock_guard<std::mutex> lock(mutex);
  26375. release = true;
  26376. }
  26377. cv.notify_all();
  26378. svr.stop();
  26379. t.join();
  26380. });
  26381. svr.wait_until_ready();
  26382. ws::WebSocketClient client(std::string(scheme) +
  26383. "://localhost:" + std::to_string(port) + "/ws");
  26384. #ifdef CPPHTTPLIB_SSL_ENABLED
  26385. client.enable_server_certificate_verification(false);
  26386. #endif
  26387. // A ping a second, given up on after two go unanswered: about 3s
  26388. client.set_websocket_ping_interval(1);
  26389. client.set_websocket_max_missed_pongs(2);
  26390. // Well past that, so that a read the timeout ends instead stands out
  26391. client.set_read_timeout(10);
  26392. ASSERT_TRUE(client.connect());
  26393. auto start = std::chrono::steady_clock::now();
  26394. std::string msg;
  26395. EXPECT_EQ(ws::Fail, client.read(msg));
  26396. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26397. std::chrono::steady_clock::now() - start)
  26398. .count(),
  26399. 6000);
  26400. EXPECT_FALSE(client.is_open());
  26401. }
  26402. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26403. Server svr;
  26404. check_pong_timeout_ends_read(svr, "ws");
  26405. }
  26406. #ifdef CPPHTTPLIB_SSL_ENABLED
  26407. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26408. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26409. ASSERT_TRUE(svr.is_valid());
  26410. check_pong_timeout_ends_read(svr, "wss");
  26411. }
  26412. #endif
  26413. // listen() returns only after every handler has, so Server::stop() has to end
  26414. // a WebSocket handler's read() waiting on a client that stays connected and
  26415. // quiet, whether or not the handler bounded its reads, and the client's
  26416. // connection ends with it.
  26417. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26418. bool bounded) {
  26419. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26420. if (bounded) { ws.set_read_timeout(0, 50000); }
  26421. std::string msg;
  26422. while (ws.read(msg) != ws::Fail) {}
  26423. });
  26424. auto port = svr.bind_to_any_port(HOST);
  26425. std::thread t([&]() { svr.listen_after_bind(); });
  26426. auto se = detail::scope_exit([&] {
  26427. if (t.joinable()) {
  26428. svr.stop();
  26429. t.join();
  26430. }
  26431. });
  26432. svr.wait_until_ready();
  26433. ws::WebSocketClient client(std::string(scheme) +
  26434. "://localhost:" + std::to_string(port) + "/ws");
  26435. #ifdef CPPHTTPLIB_SSL_ENABLED
  26436. client.enable_server_certificate_verification(false);
  26437. #endif
  26438. client.set_read_timeout(2);
  26439. ASSERT_TRUE(client.connect());
  26440. auto stopped = std::async(std::launch::async, [&] {
  26441. svr.stop();
  26442. t.join();
  26443. });
  26444. std::string msg;
  26445. EXPECT_EQ(ws::Fail, client.read(msg));
  26446. EXPECT_FALSE(client.is_open());
  26447. auto in_time =
  26448. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26449. // A handler the stop did not reach ends when the client leaves
  26450. if (!in_time) { client.close(); }
  26451. stopped.wait();
  26452. EXPECT_TRUE(in_time);
  26453. }
  26454. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26455. Server svr;
  26456. check_stop_ends_websocket_read(svr, "ws", false);
  26457. }
  26458. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26459. Server svr;
  26460. check_stop_ends_websocket_read(svr, "ws", true);
  26461. }
  26462. #ifdef CPPHTTPLIB_SSL_ENABLED
  26463. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26464. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26465. ASSERT_TRUE(svr.is_valid());
  26466. check_stop_ends_websocket_read(svr, "wss", false);
  26467. }
  26468. #endif
  26469. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26470. // dropped connection, whether the handler waits for a message or for the rest
  26471. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26472. // time out inside the message as well, and the stop ends them too.
  26473. static void check_stop_closes_with_going_away(const std::string &sent,
  26474. bool bounded = false) {
  26475. Server svr;
  26476. svr.set_websocket_ping_interval(0);
  26477. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26478. if (bounded) { ws.set_read_timeout(0, 10000); }
  26479. std::string msg;
  26480. while (ws.read(msg) != ws::Fail) {}
  26481. });
  26482. auto port = svr.bind_to_any_port("127.0.0.1");
  26483. std::thread t([&]() { svr.listen_after_bind(); });
  26484. auto se = detail::scope_exit([&] {
  26485. svr.stop();
  26486. t.join();
  26487. });
  26488. svr.wait_until_ready();
  26489. // Closed before the join above, which a handler the stop did not reach
  26490. // would otherwise hold up.
  26491. auto sock = connect_raw_websocket(port, "/ws");
  26492. ASSERT_NE(INVALID_SOCKET, sock);
  26493. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26494. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26495. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26496. // Let the handler take what was sent and wait for more
  26497. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26498. svr.stop();
  26499. // FIN + Close, its length, then the code: unmasked, from a server
  26500. std::string head;
  26501. char c;
  26502. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26503. head += c;
  26504. }
  26505. const std::string reason = "server stopping";
  26506. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26507. "\x03\xe9",
  26508. head);
  26509. }
  26510. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26511. check_stop_closes_with_going_away("");
  26512. }
  26513. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26514. // A Text frame without FIN: the first fragment of a message
  26515. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26516. }
  26517. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26518. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26519. /*bounded=*/true);
  26520. }
  26521. // A handler that bounds its reads gets control back within its timeout even
  26522. // while a message arrives in pieces, and the message whole once the last has
  26523. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26524. // sent once read() has timed out twice since the one before was sent, so the
  26525. // second timeout came from a read() that had that piece to take.
  26526. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26527. const std::string &expected) {
  26528. std::atomic<bool> done{false};
  26529. std::atomic<int> timeouts{0};
  26530. std::string received;
  26531. Server svr;
  26532. svr.set_websocket_ping_interval(0);
  26533. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26534. ws.set_read_timeout(0, 10000);
  26535. std::string msg;
  26536. ws::ReadResult r;
  26537. while ((r = ws.read(msg)) == ws::Timeout) {
  26538. timeouts++;
  26539. }
  26540. if (r == ws::Text) { received = msg; }
  26541. done = true;
  26542. });
  26543. auto port = svr.bind_to_any_port("127.0.0.1");
  26544. std::thread t([&]() { svr.listen_after_bind(); });
  26545. auto se = detail::scope_exit([&] {
  26546. svr.stop();
  26547. t.join();
  26548. });
  26549. svr.wait_until_ready();
  26550. auto sock = connect_raw_websocket(port, "/ws");
  26551. ASSERT_NE(INVALID_SOCKET, sock);
  26552. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26553. // Each piece goes out at once, not held back by Nagle's algorithm
  26554. ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  26555. for (size_t i = 0; i < pieces.size(); i++) {
  26556. ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
  26557. detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
  26558. if (i + 1 == pieces.size()) { break; }
  26559. auto before = timeouts.load();
  26560. for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
  26561. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26562. }
  26563. ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
  26564. }
  26565. for (int i = 0; i < 5000 && !done; i++) {
  26566. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26567. }
  26568. ASSERT_TRUE(done);
  26569. EXPECT_EQ(expected, received);
  26570. }
  26571. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26572. // The header's first byte, then its second with half the mask key, then
  26573. // the rest: what a frame written in several writes may look like when
  26574. // Nagle's algorithm holds the later ones back for an ACK.
  26575. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26576. check_bounded_read_resumes(
  26577. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26578. }
  26579. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26580. check_bounded_read_resumes(
  26581. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26582. }
  26583. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26584. Server svr;
  26585. svr.set_websocket_ping_interval(0);
  26586. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26587. std::string msg;
  26588. while (ws.read(msg)) {}
  26589. });
  26590. auto port = svr.bind_to_any_port("127.0.0.1");
  26591. std::thread t([&]() { svr.listen_after_bind(); });
  26592. auto se = detail::scope_exit([&] {
  26593. svr.stop();
  26594. t.join();
  26595. });
  26596. svr.wait_until_ready();
  26597. // Each Close payload and the reply it should get: an echo when valid, 1002
  26598. // otherwise.
  26599. std::vector<std::pair<std::string, std::string>> cases = {
  26600. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26601. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26602. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26603. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26604. };
  26605. // Also between the fragments of a message.
  26606. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26607. for (const auto &c : cases) {
  26608. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26609. c.second,
  26610. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26611. 2 + c.second.size()));
  26612. }
  26613. }
  26614. }
  26615. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26616. Server svr;
  26617. svr.set_websocket_ping_interval(0);
  26618. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26619. std::string msg;
  26620. while (ws.read(msg)) {}
  26621. });
  26622. auto port = svr.bind_to_any_port("127.0.0.1");
  26623. std::thread t([&]() { svr.listen_after_bind(); });
  26624. auto se = detail::scope_exit([&] {
  26625. svr.stop();
  26626. t.join();
  26627. });
  26628. svr.wait_until_ready();
  26629. // A header that announces one byte over the limit, and none of its payload
  26630. std::string too_big = "\x82\xff";
  26631. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26632. for (int shift = 56; shift >= 0; shift -= 8) {
  26633. too_big += static_cast<char>((len >> shift) & 0xff);
  26634. }
  26635. too_big.append(4, '\0');
  26636. const std::string protocol_error("\x03\xea"); // 1002
  26637. const std::string too_big_error("\x03\xf1"); // 1009
  26638. // What the client sends and the status the server closes with
  26639. std::vector<std::pair<std::string, std::string>> cases = {
  26640. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26641. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26642. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26643. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26644. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26645. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26646. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26647. protocol_error}, // a new message inside a fragmented one
  26648. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26649. protocol_error}, // 64-bit length with its top bit set
  26650. {too_big, too_big_error},
  26651. };
  26652. for (const auto &c : cases) {
  26653. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26654. raw_websocket_reply(port, c.first, 4));
  26655. }
  26656. }
  26657. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26658. SilentListener listener;
  26659. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26660. // A peer that completes the handshake, then sends a masked frame, which a
  26661. // server must never do, and keeps what the client sends back.
  26662. std::string reply;
  26663. std::thread peer([&]() {
  26664. auto sock = listener.accept();
  26665. if (sock == INVALID_SOCKET) { return; }
  26666. std::string req;
  26667. char c;
  26668. while (req.find("\r\n\r\n") == std::string::npos &&
  26669. ::recv(sock, &c, 1, 0) == 1) {
  26670. req += c;
  26671. }
  26672. const std::string field = "Sec-WebSocket-Key: ";
  26673. auto pos = req.find(field);
  26674. if (pos != std::string::npos) {
  26675. pos += field.size();
  26676. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26677. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26678. "Upgrade: websocket\r\n"
  26679. "Connection: Upgrade\r\n"
  26680. "Sec-WebSocket-Accept: " +
  26681. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26682. masked_frame(0x81, "a");
  26683. detail::send_socket(sock, res.data(), res.size(), 0);
  26684. // FIN + Close, masked with a length of 2, the mask key, the code
  26685. char buf[256];
  26686. while (reply.size() < 8) {
  26687. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26688. if (n <= 0) { break; }
  26689. reply.append(buf, static_cast<size_t>(n));
  26690. }
  26691. }
  26692. detail::close_socket(sock);
  26693. });
  26694. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26695. "/ws");
  26696. auto connected = static_cast<bool>(client.connect());
  26697. std::string msg;
  26698. auto r = connected ? client.read(msg) : ws::Fail;
  26699. peer.join();
  26700. ASSERT_TRUE(connected);
  26701. EXPECT_EQ(ws::Fail, r);
  26702. detail::BufferStream strm;
  26703. strm.write(reply.data(), reply.size());
  26704. ws::Opcode opcode;
  26705. std::string payload;
  26706. bool fin;
  26707. ASSERT_EQ(
  26708. ws::impl::FrameRead::Ok,
  26709. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26710. EXPECT_EQ(ws::Opcode::Close, opcode);
  26711. EXPECT_EQ(std::string("\x03\xea"), payload);
  26712. }
  26713. // What a handler sees of the peer's close once read() has failed
  26714. TEST(WebSocketTest, HandlerSeesThePeersClose) {
  26715. std::mutex m;
  26716. std::condition_variable cv;
  26717. size_t handled = 0;
  26718. uint16_t seen_status = 0;
  26719. std::string seen_reason;
  26720. Server svr;
  26721. svr.set_websocket_ping_interval(0);
  26722. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26723. std::string msg;
  26724. while (ws.read(msg)) {}
  26725. std::lock_guard<std::mutex> lock(m);
  26726. seen_status = static_cast<uint16_t>(ws.close_status());
  26727. seen_reason = ws.close_reason();
  26728. handled++;
  26729. cv.notify_one();
  26730. });
  26731. auto port = svr.bind_to_any_port("127.0.0.1");
  26732. std::thread t([&]() { svr.listen_after_bind(); });
  26733. auto se = detail::scope_exit([&] {
  26734. svr.stop();
  26735. t.join();
  26736. });
  26737. svr.wait_until_ready();
  26738. auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
  26739. const char *label) {
  26740. std::unique_lock<std::mutex> lock(m);
  26741. ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
  26742. return handled == n;
  26743. })) << label;
  26744. EXPECT_EQ(status, seen_status) << label;
  26745. EXPECT_EQ(reason, seen_reason) << label;
  26746. };
  26747. // What a raw client sends before it drops the connection
  26748. struct Case {
  26749. const char *label;
  26750. std::string sent;
  26751. uint16_t status;
  26752. std::string reason;
  26753. };
  26754. std::vector<Case> cases = {
  26755. {"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
  26756. "logout"},
  26757. {"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
  26758. {"no status", masked_frame(0x88, ""), 1005, ""},
  26759. {"malformed", masked_frame(0x88, "\x03"), 1002, ""},
  26760. {"no Close", masked_frame(0x81, "hi"), 1006, ""},
  26761. };
  26762. for (size_t i = 0; i < cases.size(); i++) {
  26763. auto sock = connect_raw_websocket(port, "/ws");
  26764. ASSERT_NE(INVALID_SOCKET, sock);
  26765. detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
  26766. detail::close_socket(sock);
  26767. expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
  26768. }
  26769. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
  26770. ASSERT_TRUE(client.connect());
  26771. client.close(static_cast<ws::CloseStatus>(4001), "logout");
  26772. expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
  26773. }
  26774. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26775. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26776. protected:
  26777. void SetUp() override {
  26778. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26779. SERVER_PRIVATE_KEY_FILE);
  26780. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26781. std::string msg;
  26782. ws::ReadResult ret;
  26783. while ((ret = ws.read(msg))) {
  26784. if (ret == ws::Binary) {
  26785. ws.send(msg.data(), msg.size());
  26786. } else {
  26787. ws.send(msg);
  26788. }
  26789. }
  26790. });
  26791. port_ = server_->bind_to_any_port(HOST);
  26792. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26793. server_->wait_until_ready();
  26794. }
  26795. void TearDown() override {
  26796. server_->stop();
  26797. if (server_thread_.joinable()) { server_thread_.join(); }
  26798. }
  26799. std::unique_ptr<SSLServer> server_;
  26800. std::thread server_thread_;
  26801. int port_ = 0;
  26802. };
  26803. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26804. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26805. {
  26806. ws::WebSocketClient client(url);
  26807. client.enable_server_certificate_verification(false);
  26808. auto calls = 0;
  26809. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26810. calls++;
  26811. return false;
  26812. });
  26813. EXPECT_FALSE(client.connect());
  26814. EXPECT_GT(calls, 0);
  26815. }
  26816. {
  26817. ws::WebSocketClient client(url);
  26818. client.enable_server_certificate_verification(false);
  26819. client.set_session_verifier([](tls::session_t) {
  26820. return SSLVerifierResponse::CertificateRejected;
  26821. });
  26822. EXPECT_FALSE(client.connect());
  26823. }
  26824. {
  26825. ws::WebSocketClient client(url);
  26826. client.enable_server_certificate_verification(false);
  26827. client.set_session_verifier([](tls::session_t) {
  26828. return SSLVerifierResponse::CertificateAccepted;
  26829. });
  26830. EXPECT_TRUE(client.connect());
  26831. }
  26832. }
  26833. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26834. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26835. "/ws-echo");
  26836. client.enable_server_certificate_verification(false);
  26837. ASSERT_TRUE(client.connect());
  26838. ASSERT_TRUE(client.is_open());
  26839. ASSERT_TRUE(client.send("Hello WSS"));
  26840. std::string msg;
  26841. EXPECT_EQ(ws::Text, client.read(msg));
  26842. EXPECT_EQ("Hello WSS", msg);
  26843. client.close();
  26844. }
  26845. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26846. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26847. "/ws-echo");
  26848. client.enable_server_certificate_verification(false);
  26849. EXPECT_TRUE(client.connect());
  26850. }
  26851. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26852. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26853. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26854. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26855. // client (without calling close() first) is the only path that runs
  26856. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26857. // bug exactly.
  26858. //
  26859. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26860. // when linked against an instrumented libssl; run under Valgrind to catch it
  26861. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26862. // suite (the freed session otherwise stalls on the close handshake) — this test
  26863. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26864. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26865. {
  26866. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26867. "/ws-echo");
  26868. client.enable_server_certificate_verification(false);
  26869. client.set_read_timeout(2, 0);
  26870. client.set_write_timeout(2, 0);
  26871. ASSERT_TRUE(client.connect());
  26872. ASSERT_TRUE(client.is_open());
  26873. ASSERT_TRUE(client.send("still open"));
  26874. // Intentionally do NOT call client.close(): leaving scope runs
  26875. // shutdown_and_close() with the WebSocket still open, which must send the
  26876. // close frame while the TLS session is still alive.
  26877. }
  26878. }
  26879. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26880. // shutdown_and_close() at the start of connect(), reproducing the same
  26881. // use-after-free within the test body rather than at scope exit. The second
  26882. // connect must succeed and echo, proving the close handshake ran over a live
  26883. // session. See the note above about memory-tool requirements.
  26884. TEST_F(WebSocketSSLIntegrationTest,
  26885. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26886. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26887. "/ws-echo");
  26888. client.enable_server_certificate_verification(false);
  26889. client.set_read_timeout(2, 0);
  26890. client.set_write_timeout(2, 0);
  26891. ASSERT_TRUE(client.connect());
  26892. ASSERT_TRUE(client.is_open());
  26893. ASSERT_TRUE(client.send("still open"));
  26894. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26895. // the still-open connection, which must not touch a freed TLS session.
  26896. ASSERT_TRUE(client.connect());
  26897. ASSERT_TRUE(client.is_open());
  26898. ASSERT_TRUE(client.send("after reconnect"));
  26899. std::string msg;
  26900. EXPECT_EQ(ws::Text, client.read(msg));
  26901. EXPECT_EQ("after reconnect", msg);
  26902. client.close();
  26903. }
  26904. #endif
  26905. #ifdef CPPHTTPLIB_SSL_ENABLED
  26906. class WebSocketSSLCATest : public ::testing::Test {
  26907. protected:
  26908. void SetUp() override {
  26909. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26910. SERVER_PRIVATE_KEY_FILE);
  26911. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26912. std::string msg;
  26913. while (ws.read(msg)) {
  26914. ws.send(msg);
  26915. }
  26916. });
  26917. port_ = server_->bind_to_any_port("127.0.0.1");
  26918. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26919. server_->wait_until_ready();
  26920. }
  26921. void TearDown() override {
  26922. server_->stop();
  26923. if (server_thread_.joinable()) { server_thread_.join(); }
  26924. }
  26925. std::string url() const {
  26926. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26927. }
  26928. std::unique_ptr<SSLServer> server_;
  26929. std::thread server_thread_;
  26930. int port_ = 0;
  26931. };
  26932. // A custom CA loaded as PEM verifies the server with full certificate
  26933. // verification enabled
  26934. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26935. ws::WebSocketClient client(url());
  26936. std::string cert;
  26937. read_file(SERVER_CERT2_FILE, cert);
  26938. client.load_ca_cert_store(cert.c_str(), cert.size());
  26939. ASSERT_TRUE(client.connect());
  26940. ASSERT_TRUE(client.send("hello"));
  26941. std::string msg;
  26942. EXPECT_EQ(ws::Text, client.read(msg));
  26943. EXPECT_EQ("hello", msg);
  26944. client.close();
  26945. }
  26946. // A custom CA that does not cover the server must fail verification (the
  26947. // custom CA is exclusive; system certs are not loaded alongside it)
  26948. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26949. ws::WebSocketClient client(url());
  26950. std::string cert;
  26951. read_file(CLIENT_CA_CERT_FILE, cert);
  26952. client.load_ca_cert_store(cert.c_str(), cert.size());
  26953. auto res = client.connect();
  26954. ASSERT_FALSE(res);
  26955. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26956. EXPECT_EQ(-1, res.status());
  26957. EXPECT_NE(0u, res.ssl_backend_error());
  26958. }
  26959. // The same CA as a file path rather than PEM in memory
  26960. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26961. ws::WebSocketClient client(url());
  26962. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26963. ASSERT_TRUE(client.connect());
  26964. ASSERT_TRUE(client.send("hello"));
  26965. std::string msg;
  26966. EXPECT_EQ(ws::Text, client.read(msg));
  26967. EXPECT_EQ("hello", msg);
  26968. client.close();
  26969. }
  26970. // ...and a CA file that does not cover the server still fails, so it is the
  26971. // path above that decides the outcome
  26972. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  26973. ws::WebSocketClient client(url());
  26974. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  26975. ASSERT_FALSE(client.connect());
  26976. }
  26977. // Regression test: reconnecting with a native custom CA store used to reuse
  26978. // a store handle the previous TLS context had already freed (use-after-free
  26979. // under the OpenSSL backend). The context now lives as long as the client.
  26980. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  26981. ws::WebSocketClient client(url());
  26982. std::string cert;
  26983. read_file(SERVER_CERT2_FILE, cert);
  26984. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  26985. ASSERT_TRUE(client.connect());
  26986. client.close();
  26987. ASSERT_TRUE(client.connect());
  26988. ASSERT_TRUE(client.send("again"));
  26989. std::string msg;
  26990. EXPECT_EQ(ws::Text, client.read(msg));
  26991. EXPECT_EQ("again", msg);
  26992. client.close();
  26993. }
  26994. // Regression test: a certificate with a trusted chain but no identity match
  26995. // for the server IP must be rejected. The Mbed TLS backend used to skip
  26996. // verification entirely for IP hosts, so this connection succeeded there.
  26997. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  26998. // chain verification while the identity check must still fail.
  26999. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  27000. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  27001. ASSERT_TRUE(svr.is_valid());
  27002. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27003. std::string msg;
  27004. while (ws.read(msg)) {
  27005. ws.send(msg);
  27006. }
  27007. });
  27008. auto port = svr.bind_to_any_port("127.0.0.1");
  27009. auto t = std::thread([&]() { svr.listen_after_bind(); });
  27010. auto se = detail::scope_exit([&] {
  27011. svr.stop();
  27012. t.join();
  27013. });
  27014. svr.wait_until_ready();
  27015. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  27016. "/echo");
  27017. std::string cert;
  27018. read_file(SERVER_CERT_FILE, cert);
  27019. client.load_ca_cert_store(cert.c_str(), cert.size());
  27020. ASSERT_FALSE(client.connect());
  27021. }
  27022. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  27023. // SNI, so nothing binds the host name to the TLS session. These bind the
  27024. // server to "localhost" instead, the only shape that exercises the SNI and
  27025. // hostname-verification path with certificate verification left enabled.
  27026. class WebSocketSSLDnsHostTest : public ::testing::Test {
  27027. protected:
  27028. void Start(const char *cert_file) {
  27029. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  27030. SERVER_PRIVATE_KEY_FILE);
  27031. ASSERT_TRUE(server_->is_valid());
  27032. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27033. std::string msg;
  27034. while (ws.read(msg)) {
  27035. ws.send(msg);
  27036. }
  27037. });
  27038. port_ = server_->bind_to_any_port("localhost");
  27039. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27040. server_->wait_until_ready();
  27041. }
  27042. void TearDown() override {
  27043. if (server_) { server_->stop(); }
  27044. if (server_thread_.joinable()) { server_thread_.join(); }
  27045. }
  27046. std::string url() const {
  27047. return "wss://localhost:" + std::to_string(port_) + "/echo";
  27048. }
  27049. std::unique_ptr<SSLServer> server_;
  27050. std::thread server_thread_;
  27051. int port_ = 0;
  27052. };
  27053. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  27054. // out and the connection is usable
  27055. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  27056. Start(SERVER_CERT2_FILE);
  27057. ws::WebSocketClient client(url());
  27058. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27059. ASSERT_TRUE(client.connect());
  27060. ASSERT_TRUE(client.send("hello"));
  27061. std::string msg;
  27062. EXPECT_EQ(ws::Text, client.read(msg));
  27063. EXPECT_EQ("hello", msg);
  27064. client.close();
  27065. }
  27066. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  27067. // while the identity check must still reject "localhost"
  27068. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  27069. Start(SERVER_CERT_FILE);
  27070. ws::WebSocketClient client(url());
  27071. client.set_ca_cert_path(SERVER_CERT_FILE);
  27072. auto res = client.connect();
  27073. ASSERT_FALSE(res);
  27074. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  27075. EXPECT_EQ(-1, res.status());
  27076. }
  27077. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  27078. // disabled: the chain is still checked, only the identity check is skipped
  27079. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  27080. Start(SERVER_CERT_FILE);
  27081. ws::WebSocketClient client(url());
  27082. client.set_ca_cert_path(SERVER_CERT_FILE);
  27083. client.enable_server_hostname_verification(false);
  27084. ASSERT_TRUE(client.connect());
  27085. ASSERT_TRUE(client.send("hello"));
  27086. std::string msg;
  27087. EXPECT_EQ(ws::Text, client.read(msg));
  27088. EXPECT_EQ("hello", msg);
  27089. client.close();
  27090. }
  27091. // A CA that did not sign the server certificate fails the chain, even though
  27092. // the name would match
  27093. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  27094. Start(SERVER_CERT2_FILE);
  27095. ws::WebSocketClient client(url());
  27096. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27097. ASSERT_FALSE(client.connect());
  27098. }
  27099. // With verification disabled, neither the chain nor the name is checked
  27100. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  27101. Start(SERVER_CERT_FILE);
  27102. ws::WebSocketClient client(url());
  27103. client.enable_server_certificate_verification(false);
  27104. ASSERT_TRUE(client.connect());
  27105. ASSERT_TRUE(client.send("hello"));
  27106. std::string msg;
  27107. EXPECT_EQ(ws::Text, client.read(msg));
  27108. EXPECT_EQ("hello", msg);
  27109. client.close();
  27110. }
  27111. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  27112. protected:
  27113. void SetUp() override {
  27114. server_ = httplib::detail::make_unique<SSLServer>(
  27115. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  27116. ASSERT_TRUE(server_->is_valid());
  27117. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27118. std::string msg;
  27119. while (ws.read(msg)) {
  27120. ws.send(msg);
  27121. }
  27122. });
  27123. port_ = server_->bind_to_any_port("localhost");
  27124. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27125. server_->wait_until_ready();
  27126. }
  27127. void TearDown() override {
  27128. server_->stop();
  27129. if (server_thread_.joinable()) { server_thread_.join(); }
  27130. }
  27131. std::string url() const {
  27132. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27133. }
  27134. void ConnectWithClientCert(const std::string &client_cert_file,
  27135. const std::string &client_private_key_file,
  27136. const char *private_key_password) {
  27137. std::string cert_pem, key_pem;
  27138. read_file(client_cert_file, cert_pem);
  27139. read_file(client_private_key_file, key_pem);
  27140. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27141. key_pem.c_str(), key_pem.size(),
  27142. private_key_password};
  27143. ConnectWithPem(pem);
  27144. }
  27145. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27146. ws::WebSocketClient client(url(), pem);
  27147. ASSERT_TRUE(client.is_valid());
  27148. client.enable_server_certificate_verification(false);
  27149. ASSERT_TRUE(client.connect());
  27150. ASSERT_TRUE(client.send("hello"));
  27151. std::string msg;
  27152. EXPECT_EQ(ws::Text, client.read(msg));
  27153. EXPECT_EQ("hello", msg);
  27154. client.close();
  27155. }
  27156. std::unique_ptr<SSLServer> server_;
  27157. std::thread server_thread_;
  27158. int port_ = 0;
  27159. };
  27160. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27161. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27162. }
  27163. // Control for the tests above: the fixture's server really does require a
  27164. // client certificate, so it is the PEM the constructor installed that decides
  27165. // the outcome.
  27166. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27167. ws::WebSocketClient client(url());
  27168. ASSERT_TRUE(client.is_valid());
  27169. client.enable_server_certificate_verification(false);
  27170. EXPECT_FALSE(client.connect());
  27171. }
  27172. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27173. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27174. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27175. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27176. }
  27177. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27178. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27179. std::string cert_pem, key_pem;
  27180. read_file(CLIENT_CERT_FILE, cert_pem);
  27181. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27182. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27183. std::vector<char> key(key_pem.begin(), key_pem.end());
  27184. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27185. key.size(), nullptr};
  27186. ConnectWithPem(pem);
  27187. }
  27188. #endif
  27189. #if !defined(_WIN32)
  27190. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27191. auto secret_dir = std::string("./symlink_test_secret");
  27192. auto served_dir = std::string("./symlink_test_served");
  27193. auto secret_file = secret_dir + "/secret.txt";
  27194. auto symlink_path = served_dir + "/escape";
  27195. // Setup: create directories and files
  27196. mkdir(secret_dir.c_str(), 0755);
  27197. mkdir(served_dir.c_str(), 0755);
  27198. {
  27199. std::ofstream ofs(secret_file);
  27200. ofs << "SECRET_DATA";
  27201. }
  27202. // Create symlink using absolute path so it resolves correctly
  27203. #ifdef PATH_MAX
  27204. char abs_secret[PATH_MAX];
  27205. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27206. #else
  27207. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27208. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27209. ASSERT_NE(nullptr, abs_secret);
  27210. #endif
  27211. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27212. auto se = detail::scope_exit([&] {
  27213. unlink(symlink_path.c_str());
  27214. unlink(secret_file.c_str());
  27215. rmdir(served_dir.c_str());
  27216. rmdir(secret_dir.c_str());
  27217. });
  27218. Server svr;
  27219. svr.set_mount_point("/", served_dir);
  27220. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27221. auto se2 = detail::scope_exit([&] {
  27222. svr.stop();
  27223. listen_thread.join();
  27224. });
  27225. svr.wait_until_ready();
  27226. Client cli("localhost", PORT);
  27227. // Symlink pointing outside base dir should be blocked
  27228. auto res = cli.Get("/escape/secret.txt");
  27229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27230. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27231. }
  27232. #else
  27233. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27234. auto secret_dir = std::string("junction_test_secret");
  27235. auto served_dir = std::string("junction_test_served");
  27236. auto secret_file = secret_dir + "\\secret.txt";
  27237. auto junction_path = served_dir + "\\escape";
  27238. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27239. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27240. {
  27241. std::ofstream ofs(secret_file);
  27242. ofs << "SECRET_DATA";
  27243. }
  27244. // A junction needs no privilege to create, unlike a symlink
  27245. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27246. ASSERT_EQ(0, std::system(cmd.c_str()));
  27247. auto se = detail::scope_exit([&] {
  27248. ::RemoveDirectoryA(junction_path.c_str());
  27249. std::remove(secret_file.c_str());
  27250. ::RemoveDirectoryA(served_dir.c_str());
  27251. ::RemoveDirectoryA(secret_dir.c_str());
  27252. });
  27253. Server svr;
  27254. svr.set_mount_point("/", served_dir);
  27255. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27256. auto se2 = detail::scope_exit([&] {
  27257. svr.stop();
  27258. listen_thread.join();
  27259. });
  27260. svr.wait_until_ready();
  27261. Client cli("localhost", PORT);
  27262. // Junction pointing outside base dir should be blocked
  27263. auto res = cli.Get("/escape/secret.txt");
  27264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27265. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27266. }
  27267. #endif
  27268. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27269. // "GET /smuggled" request), reads the first response, and only then sends the
  27270. // embedded request as the body. Returns how many times /smuggled ran.
  27271. //
  27272. // The body is sent AFTER receiving the first response (as in the original
  27273. // PoC) so that the stream_line_reader cannot buffer it together with the
  27274. // headers of the first request.
  27275. static int count_smuggled_requests(const std::string &outer_head,
  27276. std::string &first_response) {
  27277. Server svr;
  27278. svr.set_mount_point("/", "./www");
  27279. std::atomic<int> smuggled_count(0);
  27280. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27281. smuggled_count++;
  27282. res.set_content("oops", "text/plain");
  27283. });
  27284. svr.Post("/post", [&](const Request &req, Response &res) {
  27285. res.set_content(req.body, "text/plain");
  27286. });
  27287. auto port = svr.bind_to_any_port("localhost");
  27288. thread t = thread([&] { svr.listen_after_bind(); });
  27289. auto se = detail::scope_exit([&] {
  27290. svr.stop();
  27291. t.join();
  27292. });
  27293. svr.wait_until_ready();
  27294. auto error = Error::Success;
  27295. auto sock = detail::create_client_socket(
  27296. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27297. /*connection_timeout_sec=*/2, 0,
  27298. /*read_timeout_sec=*/2, 0,
  27299. /*write_timeout_sec=*/2, 0, std::string(), error);
  27300. EXPECT_NE(INVALID_SOCKET, sock);
  27301. if (sock == INVALID_SOCKET) { return -1; }
  27302. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27303. // The "smuggled" request will be sent as the body of the outer request
  27304. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27305. "Host: localhost\r\n"
  27306. "Connection: close\r\n"
  27307. "\r\n";
  27308. auto head = outer_head;
  27309. auto len = std::to_string(smuggled.size());
  27310. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27311. pos = head.find("{len}", pos + len.size())) {
  27312. head.replace(pos, 5, len);
  27313. }
  27314. // Step 1: Send only the outer request headers (no body yet)
  27315. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27316. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27317. // Step 2: Read the first response
  27318. char buf[4096];
  27319. for (;;) {
  27320. auto n = recv(sock, buf, sizeof(buf), 0);
  27321. if (n <= 0) break;
  27322. first_response.append(buf, static_cast<size_t>(n));
  27323. // Stop once we have a complete response (headers + body)
  27324. auto hdr_end = first_response.find("\r\n\r\n");
  27325. if (hdr_end != std::string::npos) {
  27326. // Check for Content-Length to know when the body is complete
  27327. auto cl_pos = first_response.find("Content-Length:");
  27328. if (cl_pos != std::string::npos) {
  27329. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27330. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27331. auto cl = std::stoul(
  27332. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27333. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27334. } else {
  27335. break; // No Content-Length, assume headers-only response
  27336. }
  27337. }
  27338. }
  27339. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27340. // vulnerable server the keep-alive loop reads this as a second request. The
  27341. // server may already have closed the connection, so the result is ignored.
  27342. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27343. // Half-close so that a server which drained the body sees EOF and closes,
  27344. // instead of the read below waiting for the read timeout.
  27345. #ifdef _WIN32
  27346. ::shutdown(sock, SD_SEND);
  27347. #else
  27348. ::shutdown(sock, SHUT_WR);
  27349. #endif
  27350. // Step 4: Read until the server closes the connection
  27351. for (;;) {
  27352. auto n = recv(sock, buf, sizeof(buf), 0);
  27353. if (n <= 0) break;
  27354. }
  27355. return smuggled_count.load();
  27356. }
  27357. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27358. // A GET request with Content-Length to a static file handler must have its
  27359. // body drained before the keep-alive connection is reused. Otherwise the
  27360. // unread body bytes are interpreted as the next HTTP request.
  27361. std::string first_response;
  27362. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27363. "Host: localhost\r\n"
  27364. "Content-Length: {len}\r\n"
  27365. "\r\n",
  27366. first_response));
  27367. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27368. }
  27369. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27370. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27371. // be answered with 400 and the connection closed. Treating it as "no body"
  27372. // leaves the body to be parsed as the next request.
  27373. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27374. const char *targets[] = {
  27375. "GET /file", // handler that never reads the body
  27376. "GET /not-found", // no handler matches (404)
  27377. "POST /post", // handler that reads the body
  27378. };
  27379. for (auto target : targets) {
  27380. for (auto value : values) {
  27381. std::string first_response;
  27382. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27383. " HTTP/1.1\r\n"
  27384. "Host: localhost\r\n"
  27385. "Content-Length: " +
  27386. value + "\r\n\r\n",
  27387. first_response))
  27388. << target << " with Content-Length: " << value;
  27389. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27390. << target << " with Content-Length: " << value;
  27391. }
  27392. }
  27393. }
  27394. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27395. // A 400 for an unparseable request line leaves the rest of the message
  27396. // unread, so the connection must be closed rather than reused.
  27397. std::string first_response;
  27398. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27399. "Host: localhost\r\n"
  27400. "Content-Length: {len}\r\n"
  27401. "\r\n",
  27402. first_response));
  27403. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27404. }
  27405. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27406. // Same as above for a header block that fails to parse.
  27407. std::string first_response;
  27408. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27409. "Host: localhost\r\n"
  27410. "Bad Header\r\n"
  27411. "Content-Length: {len}\r\n"
  27412. "\r\n",
  27413. first_response));
  27414. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27415. }
  27416. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27417. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27418. // server must not read another request on that connection, even when the
  27419. // request had no body to drain.
  27420. std::string first_response;
  27421. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27422. "Host: localhost\r\n"
  27423. "\r\n",
  27424. first_response));
  27425. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27426. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27427. }
  27428. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27429. // A content reader that stops early leaves the stream inside the body.
  27430. // Draining the whole Content-Length from there, or reading the body again,
  27431. // reads into the next request, and whatever follows is parsed as a request
  27432. // of its own.
  27433. Server svr;
  27434. std::atomic<int> smuggled_count(0);
  27435. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27436. svr.Post("/upload", [](const Request &req, Response &res,
  27437. const ContentReader &content_reader) {
  27438. // Stop at the last chunk, so the whole body has been read however it
  27439. // arrives.
  27440. auto length = req.get_header_value_u64("Content-Length");
  27441. size_t total = 0;
  27442. auto consumed = content_reader([&](const char *, size_t n) {
  27443. total += n;
  27444. return total < length;
  27445. });
  27446. EXPECT_FALSE(consumed);
  27447. if (req.has_param("retry")) {
  27448. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27449. }
  27450. // Replace the 400 the aborted read set, which would close the connection.
  27451. res.set_redirect("/done");
  27452. });
  27453. auto port = svr.bind_to_any_port(HOST);
  27454. thread t = thread([&] { svr.listen_after_bind(); });
  27455. auto se = detail::scope_exit([&] {
  27456. svr.stop();
  27457. t.join();
  27458. });
  27459. svr.wait_until_ready();
  27460. // A front end sees the second request as a POST whose body is the GET. The
  27461. // first body is as long as the POST's headers, so draining it again reads
  27462. // exactly those and leaves the GET to be parsed next.
  27463. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27464. "Host: localhost\r\n"
  27465. "\r\n";
  27466. std::string second_head = "POST /post HTTP/1.1\r\n"
  27467. "Host: localhost\r\n"
  27468. "Content-Length: " +
  27469. std::to_string(inner.size()) +
  27470. "\r\n"
  27471. "\r\n";
  27472. for (auto target : {"/upload", "/upload?retry"}) {
  27473. smuggled_count = 0;
  27474. std::string request = "POST " + std::string(target) +
  27475. " HTTP/1.1\r\n"
  27476. "Host: localhost\r\n"
  27477. "Content-Length: " +
  27478. std::to_string(second_head.size()) +
  27479. "\r\n"
  27480. "\r\n" +
  27481. std::string(second_head.size(), 'A') + second_head +
  27482. inner;
  27483. std::string response;
  27484. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27485. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27486. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27487. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27488. EXPECT_EQ(0, smuggled_count.load()) << target;
  27489. }
  27490. }
  27491. // An error response closes the connection anyway, so the body is left unread
  27492. // with a redirect, such as one to a login page.
  27493. static void serve_redirects(Server &svr,
  27494. const std::function<void(int)> &client) {
  27495. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27496. res.set_redirect("/login");
  27497. return Server::HandlerResponse::Handled;
  27498. });
  27499. auto port = svr.bind_to_any_port(HOST);
  27500. ASSERT_GT(port, 0);
  27501. thread t = thread([&] { svr.listen_after_bind(); });
  27502. auto se = detail::scope_exit([&] {
  27503. svr.stop();
  27504. t.join();
  27505. ASSERT_FALSE(svr.is_running());
  27506. });
  27507. svr.wait_until_ready();
  27508. client(port);
  27509. }
  27510. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27511. Server svr;
  27512. serve_redirects(svr, [](int port) {
  27513. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27514. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27515. std::to_string(body.size()) + "\r\n\r\n" + body +
  27516. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27517. std::string resp;
  27518. ASSERT_TRUE(send_request(1, req, &resp, port));
  27519. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27520. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27521. });
  27522. }
  27523. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27524. Server svr;
  27525. svr.set_read_timeout(0, 200000);
  27526. serve_redirects(svr, [](int port) {
  27527. // A byte every 100 ms keeps each read within the read timeout, but not the
  27528. // body as a whole, so the server closes and the bytes sent after that fail.
  27529. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27530. "Content-Length: 10\r\n\r\n"};
  27531. parts.resize(11, "x");
  27532. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27533. });
  27534. }
  27535. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27536. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27537. // must be rejected with 400 Bad Request.
  27538. Server svr;
  27539. svr.Post("/test", [&](const Request &, Response &res) {
  27540. res.set_content("ok", "text/plain");
  27541. });
  27542. thread t = thread([&] { svr.listen(HOST, PORT); });
  27543. auto se = detail::scope_exit([&] {
  27544. svr.stop();
  27545. t.join();
  27546. ASSERT_FALSE(svr.is_running());
  27547. });
  27548. svr.wait_until_ready();
  27549. // Exact "chunked"
  27550. {
  27551. auto req = "POST /test HTTP/1.1\r\n"
  27552. "Host: localhost\r\n"
  27553. "Content-Length: 5\r\n"
  27554. "Transfer-Encoding: chunked\r\n"
  27555. "Connection: close\r\n"
  27556. "\r\n"
  27557. "hello";
  27558. std::string response;
  27559. ASSERT_TRUE(send_request(1, req, &response));
  27560. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27561. response.substr(0, response.find("\r\n")));
  27562. }
  27563. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27564. {
  27565. auto req = "POST /test HTTP/1.1\r\n"
  27566. "Host: localhost\r\n"
  27567. "Content-Length: 5\r\n"
  27568. "Transfer-Encoding: gzip, chunked\r\n"
  27569. "Connection: close\r\n"
  27570. "\r\n"
  27571. "hello";
  27572. std::string response;
  27573. ASSERT_TRUE(send_request(1, req, &response));
  27574. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27575. response.substr(0, response.find("\r\n")));
  27576. }
  27577. }
  27578. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27579. Server svr;
  27580. svr.Post("/test", [&](const Request &, Response &res) {
  27581. res.set_content("ok", "text/plain");
  27582. });
  27583. thread t = thread([&] { svr.listen(HOST, PORT); });
  27584. auto se = detail::scope_exit([&] {
  27585. svr.stop();
  27586. t.join();
  27587. ASSERT_FALSE(svr.is_running());
  27588. });
  27589. svr.wait_until_ready();
  27590. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27591. // length cannot be determined, so the server must answer 400 and close
  27592. // rather than treat the request as bodyless and leave the body in the
  27593. // socket for the next request to pick up.
  27594. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27595. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27596. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27597. std::string response;
  27598. ASSERT_TRUE(send_request(1, req, &response));
  27599. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27600. response.substr(0, response.find("\r\n")))
  27601. << transfer_encoding;
  27602. }
  27603. // RFC 9110 5.3: the codings may also be split across several
  27604. // Transfer-Encoding lines, which combine in the order they were received.
  27605. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27606. // just like the single-line "chunked, gzip" above.
  27607. {
  27608. auto req = "POST /test HTTP/1.1\r\n"
  27609. "Host: localhost\r\n"
  27610. "Transfer-Encoding: chunked\r\n"
  27611. "Transfer-Encoding: gzip\r\n"
  27612. "\r\n"
  27613. "0\r\n\r\n";
  27614. std::string response;
  27615. ASSERT_TRUE(send_request(1, req, &response));
  27616. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27617. response.substr(0, response.find("\r\n")));
  27618. }
  27619. }
  27620. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27621. Server svr;
  27622. svr.Post("/test", [&](const Request &, Response &res) {
  27623. res.set_content("ok", "text/plain");
  27624. });
  27625. auto port = svr.bind_to_any_port(HOST);
  27626. ASSERT_GT(port, 0);
  27627. thread t = thread([&] { svr.listen_after_bind(); });
  27628. auto se = detail::scope_exit([&] {
  27629. svr.stop();
  27630. t.join();
  27631. ASSERT_FALSE(svr.is_running());
  27632. });
  27633. svr.wait_until_ready();
  27634. for (auto transfer_encoding :
  27635. {"Transfer-Encoding: gzip, chunked\r\n",
  27636. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27637. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27638. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27639. transfer_encoding + "\r\n0\r\n\r\n";
  27640. std::string response;
  27641. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27642. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27643. response.substr(0, response.find("\r\n")))
  27644. << transfer_encoding;
  27645. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27646. << transfer_encoding;
  27647. }
  27648. }
  27649. // Regression for issue #2450: a DELETE without Content-Length on a
  27650. // keep-alive connection must not let the post-response drain consume the
  27651. // next request's bytes.
  27652. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27653. Server svr;
  27654. std::atomic<int> delete_count(0);
  27655. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27656. delete_count++;
  27657. res.status = StatusCode::NoContent_204;
  27658. });
  27659. auto port = svr.bind_to_any_port(HOST);
  27660. thread t = thread([&] { svr.listen_after_bind(); });
  27661. auto se = detail::scope_exit([&] {
  27662. svr.stop();
  27663. t.join();
  27664. });
  27665. svr.wait_until_ready();
  27666. auto error = Error::Success;
  27667. auto sock = detail::create_client_socket(
  27668. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27669. /*connection_timeout_sec=*/2, 0,
  27670. /*read_timeout_sec=*/2, 0,
  27671. /*write_timeout_sec=*/2, 0, std::string(), error);
  27672. ASSERT_NE(INVALID_SOCKET, sock);
  27673. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27674. auto send_request_and_read_response = [&](const std::string &req,
  27675. std::string &out) -> bool {
  27676. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27677. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27678. char buf[4096];
  27679. for (;;) {
  27680. auto n = recv(sock, buf, sizeof(buf), 0);
  27681. if (n <= 0) { return !out.empty(); }
  27682. out.append(buf, static_cast<size_t>(n));
  27683. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27684. }
  27685. };
  27686. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27687. "Host: localhost\r\n"
  27688. "\r\n";
  27689. std::string resp1;
  27690. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27691. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27692. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27693. "Host: localhost\r\n"
  27694. "Connection: close\r\n"
  27695. "\r\n";
  27696. std::string resp2;
  27697. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27698. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27699. EXPECT_EQ(2, delete_count.load());
  27700. }
  27701. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27702. Server svr;
  27703. svr.Post("/ingest", [&](const Request &, Response &res,
  27704. const ContentReader &content_reader) {
  27705. auto consumed = content_reader([](const char *, size_t) { return false; });
  27706. EXPECT_FALSE(consumed);
  27707. res.status = StatusCode::Conflict_409;
  27708. res.set_header("Connection", "close");
  27709. });
  27710. auto port = svr.bind_to_any_port(HOST);
  27711. thread t = thread([&] { svr.listen_after_bind(); });
  27712. auto se = detail::scope_exit([&] {
  27713. svr.stop();
  27714. t.join();
  27715. });
  27716. svr.wait_until_ready();
  27717. auto error = Error::Success;
  27718. auto sock = detail::create_client_socket(
  27719. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27720. /*connection_timeout_sec=*/2, 0,
  27721. /*read_timeout_sec=*/1, 0,
  27722. /*write_timeout_sec=*/2, 0, std::string(), error);
  27723. ASSERT_NE(INVALID_SOCKET, sock);
  27724. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27725. std::string request = "POST /ingest HTTP/1.1\r\n"
  27726. "Host: localhost\r\n"
  27727. "Transfer-Encoding: chunked\r\n"
  27728. "\r\n"
  27729. "4\r\n"
  27730. "data\r\n";
  27731. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27732. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27733. std::string response;
  27734. ssize_t received = 0;
  27735. do {
  27736. char buf[4096];
  27737. received = recv(sock, buf, sizeof(buf), 0);
  27738. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27739. } while (received > 0);
  27740. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27741. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27742. EXPECT_EQ(0, received);
  27743. }
  27744. namespace no_proxy_test {
  27745. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27746. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27747. // calling listen().
  27748. class ScopedServer {
  27749. public:
  27750. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27751. ~ScopedServer() {
  27752. svr_.stop();
  27753. if (th_.joinable()) { th_.join(); }
  27754. }
  27755. Server &svr() { return svr_; }
  27756. int port() const { return port_; }
  27757. void listen() {
  27758. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27759. svr_.wait_until_ready();
  27760. }
  27761. private:
  27762. Server svr_;
  27763. std::thread th_;
  27764. int port_ = 0;
  27765. };
  27766. class ProxyAndTargetServers {
  27767. public:
  27768. ProxyAndTargetServers() {
  27769. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27770. proxy_hits_++;
  27771. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27772. res.set_content("via-proxy", "text/plain");
  27773. });
  27774. target_.Get(".*", [this](const Request &req, Response &res) {
  27775. target_hits_++;
  27776. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27777. res.set_content("direct", "text/plain");
  27778. });
  27779. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27780. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27781. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27782. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27783. proxy_mock_.wait_until_ready();
  27784. target_.wait_until_ready();
  27785. }
  27786. ~ProxyAndTargetServers() {
  27787. proxy_mock_.stop();
  27788. target_.stop();
  27789. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27790. if (target_thread_.joinable()) { target_thread_.join(); }
  27791. }
  27792. Server &proxy_mock() { return proxy_mock_; }
  27793. Server &target() { return target_; }
  27794. int proxy_port() const { return proxy_port_; }
  27795. int target_port() const { return target_port_; }
  27796. int proxy_hits() const { return proxy_hits_.load(); }
  27797. int target_hits() const { return target_hits_.load(); }
  27798. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27799. void reset_counters() {
  27800. proxy_hits_ = 0;
  27801. target_hits_ = 0;
  27802. last_had_proxy_authz_ = false;
  27803. }
  27804. private:
  27805. Server proxy_mock_;
  27806. Server target_;
  27807. std::thread proxy_thread_;
  27808. std::thread target_thread_;
  27809. int proxy_port_ = 0;
  27810. int target_port_ = 0;
  27811. std::atomic<int> proxy_hits_{0};
  27812. std::atomic<int> target_hits_{0};
  27813. std::atomic<bool> last_had_proxy_authz_{false};
  27814. };
  27815. inline std::unique_ptr<Client> make_client(const std::string &host,
  27816. ProxyAndTargetServers &s) {
  27817. auto cli = detail::make_unique<Client>(host, s.target_port());
  27818. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27819. cli->set_proxy("127.0.0.1", s.proxy_port());
  27820. return cli;
  27821. }
  27822. } // namespace no_proxy_test
  27823. using no_proxy_test::make_client;
  27824. using no_proxy_test::ProxyAndTargetServers;
  27825. // A stream request carries the credentials a buffered request does
  27826. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27827. no_proxy_test::ScopedServer origin;
  27828. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27829. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27830. });
  27831. origin.listen();
  27832. Client cli("127.0.0.1", origin.port());
  27833. cli.set_basic_auth("user", "pass");
  27834. auto handle = cli.open_stream("GET", "/x");
  27835. ASSERT_TRUE(handle.is_valid());
  27836. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27837. Client bearer("127.0.0.1", origin.port());
  27838. bearer.set_bearer_token_auth("tok");
  27839. auto handle2 = bearer.open_stream("GET", "/x");
  27840. ASSERT_TRUE(handle2.is_valid());
  27841. EXPECT_EQ("Bearer tok", read_all(handle2));
  27842. }
  27843. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27844. // takes its own credentials, as for a buffered request
  27845. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27846. std::string target, authz, proxy_authz;
  27847. no_proxy_test::ScopedServer proxy;
  27848. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27849. target = req.target;
  27850. authz = req.get_header_value("Authorization");
  27851. proxy_authz = req.get_header_value("Proxy-Authorization");
  27852. res.set_content("ok", "text/plain");
  27853. });
  27854. proxy.listen();
  27855. Client cli("origin.example", 8080);
  27856. cli.set_proxy("127.0.0.1", proxy.port());
  27857. cli.set_proxy_basic_auth("puser", "ppass");
  27858. cli.set_basic_auth("user", "pass");
  27859. auto handle = cli.open_stream("GET", "/x");
  27860. ASSERT_TRUE(handle.is_valid());
  27861. EXPECT_EQ("ok", read_all(handle));
  27862. EXPECT_EQ("http://origin.example:8080/x", target);
  27863. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27864. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27865. }
  27866. // In absolute-form the path follows the authority, so a path that does not
  27867. // begin with '/' would make the proxy connect to another host
  27868. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27869. std::vector<std::string> targets;
  27870. no_proxy_test::ScopedServer proxy;
  27871. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27872. targets.push_back(req.target);
  27873. res.set_content("ok", "text/plain");
  27874. });
  27875. proxy.listen();
  27876. Client cli("origin.example", 8080);
  27877. cli.set_proxy("127.0.0.1", proxy.port());
  27878. cli.set_basic_auth("user", "pass");
  27879. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27880. auto res = cli.Get(path);
  27881. EXPECT_FALSE(res) << path;
  27882. auto handle = cli.open_stream("GET", path);
  27883. EXPECT_FALSE(handle.is_valid()) << path;
  27884. }
  27885. EXPECT_TRUE(targets.empty());
  27886. auto res = cli.Get("/x");
  27887. ASSERT_TRUE(res);
  27888. ASSERT_EQ(1u, targets.size());
  27889. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27890. }
  27891. TEST(NoProxyTest, ExactHostnameBypasses) {
  27892. ProxyAndTargetServers s;
  27893. auto cli = make_client("example.com", s);
  27894. cli->set_no_proxy({"example.com"});
  27895. auto res = cli->Get("/");
  27896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27897. EXPECT_EQ(0, s.proxy_hits());
  27898. EXPECT_EQ(1, s.target_hits());
  27899. }
  27900. TEST(NoProxyTest, SubdomainBypasses) {
  27901. ProxyAndTargetServers s;
  27902. auto cli = make_client("foo.example.com", s);
  27903. cli->set_no_proxy({"example.com"});
  27904. auto res = cli->Get("/");
  27905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27906. EXPECT_EQ(0, s.proxy_hits());
  27907. EXPECT_EQ(1, s.target_hits());
  27908. }
  27909. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27910. // Regression guard: "evilexample.com" must not be considered a subdomain
  27911. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27912. // check would let traffic bypass the proxy and leak credentials direct
  27913. // to the attacker host.
  27914. ProxyAndTargetServers s;
  27915. auto cli = make_client("evilexample.com", s);
  27916. cli->set_no_proxy({"example.com"});
  27917. auto res = cli->Get("/");
  27918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27919. EXPECT_GE(s.proxy_hits(), 1);
  27920. EXPECT_EQ(0, s.target_hits());
  27921. }
  27922. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27923. ProxyAndTargetServers s;
  27924. auto cli = make_client("example.com.evil.com", s);
  27925. cli->set_no_proxy({"example.com"});
  27926. auto res = cli->Get("/");
  27927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27928. EXPECT_GE(s.proxy_hits(), 1);
  27929. EXPECT_EQ(0, s.target_hits());
  27930. }
  27931. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27932. ProxyAndTargetServers s;
  27933. auto cli = make_client("example.com", s);
  27934. cli->set_no_proxy({".example.com"});
  27935. auto res = cli->Get("/");
  27936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27937. EXPECT_EQ(0, s.proxy_hits());
  27938. EXPECT_EQ(1, s.target_hits());
  27939. }
  27940. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27941. ProxyAndTargetServers s;
  27942. auto cli = make_client("Example.COM", s);
  27943. cli->set_no_proxy({"EXAMPLE.com"});
  27944. auto res = cli->Get("/");
  27945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27946. EXPECT_EQ(0, s.proxy_hits());
  27947. EXPECT_EQ(1, s.target_hits());
  27948. }
  27949. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27950. ProxyAndTargetServers s;
  27951. auto cli = make_client("example.com.", s);
  27952. cli->set_no_proxy({"example.com"});
  27953. auto res = cli->Get("/");
  27954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27955. EXPECT_EQ(0, s.proxy_hits());
  27956. EXPECT_EQ(1, s.target_hits());
  27957. }
  27958. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27959. // Trailing dots must be normalized on BOTH sides — host and entry.
  27960. // An implementation that only strips the host-side trailing dot would
  27961. // fail to match host "example.com" against entry "example.com." because
  27962. // a literal substring search would compare 11 chars against 12.
  27963. ProxyAndTargetServers s;
  27964. auto cli = make_client("example.com", s);
  27965. cli->set_no_proxy({"example.com."});
  27966. auto res = cli->Get("/");
  27967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27968. EXPECT_EQ(0, s.proxy_hits());
  27969. EXPECT_EQ(1, s.target_hits());
  27970. }
  27971. TEST(NoProxyTest, WildcardBypassesEverything) {
  27972. ProxyAndTargetServers s;
  27973. auto cli = make_client("anything.invalid.test", s);
  27974. cli->set_no_proxy({"*"});
  27975. auto res = cli->Get("/");
  27976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27977. EXPECT_EQ(0, s.proxy_hits());
  27978. EXPECT_EQ(1, s.target_hits());
  27979. }
  27980. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  27981. ProxyAndTargetServers s;
  27982. Client cli("127.0.0.1", s.target_port());
  27983. cli.set_proxy("127.0.0.1", s.proxy_port());
  27984. cli.set_no_proxy({"127.0.0.1"});
  27985. auto res = cli.Get("/");
  27986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27987. EXPECT_EQ(0, s.proxy_hits());
  27988. EXPECT_EQ(1, s.target_hits());
  27989. }
  27990. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  27991. ProxyAndTargetServers s;
  27992. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  27993. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  27994. cli.set_proxy("127.0.0.1", s.proxy_port());
  27995. cli.set_no_proxy({"::1"});
  27996. auto res = cli.Get("/");
  27997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27998. EXPECT_EQ(0, s.proxy_hits());
  27999. EXPECT_EQ(1, s.target_hits());
  28000. }
  28001. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  28002. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  28003. // must still be recognized as IPv6 for CIDR matching. Implementations
  28004. // that detect IPv6 only when the host begins with '[' would parse the
  28005. // host as a hostname and miss the match.
  28006. ProxyAndTargetServers s;
  28007. Client cli("fe80::1", s.target_port());
  28008. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28009. cli.set_proxy("127.0.0.1", s.proxy_port());
  28010. cli.set_no_proxy({"fe80::/10"});
  28011. auto res = cli.Get("/");
  28012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28013. EXPECT_EQ(0, s.proxy_hits());
  28014. EXPECT_EQ(1, s.target_hits());
  28015. }
  28016. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  28017. ProxyAndTargetServers s;
  28018. Client cli("::1", s.target_port());
  28019. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  28020. cli.set_proxy("127.0.0.1", s.proxy_port());
  28021. cli.set_no_proxy({"[::1]"});
  28022. auto res = cli.Get("/");
  28023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28024. EXPECT_EQ(0, s.proxy_hits());
  28025. EXPECT_EQ(1, s.target_hits());
  28026. }
  28027. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  28028. ProxyAndTargetServers s;
  28029. Client cli("fe80::1", s.target_port());
  28030. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28031. cli.set_proxy("127.0.0.1", s.proxy_port());
  28032. cli.set_no_proxy({"[fe80::]/10"});
  28033. auto res = cli.Get("/");
  28034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28035. EXPECT_EQ(0, s.proxy_hits());
  28036. EXPECT_EQ(1, s.target_hits());
  28037. }
  28038. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  28039. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  28040. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  28041. // tricks via address-family conversion.
  28042. ProxyAndTargetServers s;
  28043. Client cli("::ffff:127.0.0.1", s.target_port());
  28044. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  28045. cli.set_proxy("127.0.0.1", s.proxy_port());
  28046. cli.set_no_proxy({"127.0.0.1"});
  28047. auto res = cli.Get("/");
  28048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28049. EXPECT_GE(s.proxy_hits(), 1);
  28050. EXPECT_EQ(0, s.target_hits());
  28051. }
  28052. TEST(NoProxyTest, IPv4CidrMatch) {
  28053. ProxyAndTargetServers s;
  28054. Client cli("127.0.0.1", s.target_port());
  28055. cli.set_proxy("127.0.0.1", s.proxy_port());
  28056. cli.set_no_proxy({"127.0.0.0/8"});
  28057. auto res = cli.Get("/");
  28058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28059. EXPECT_EQ(0, s.proxy_hits());
  28060. EXPECT_EQ(1, s.target_hits());
  28061. }
  28062. TEST(NoProxyTest, IPv4CidrNonMatch) {
  28063. ProxyAndTargetServers s;
  28064. Client cli("127.0.0.1", s.target_port());
  28065. cli.set_proxy("127.0.0.1", s.proxy_port());
  28066. cli.set_no_proxy({"10.0.0.0/8"});
  28067. auto res = cli.Get("/");
  28068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28069. EXPECT_GE(s.proxy_hits(), 1);
  28070. EXPECT_EQ(0, s.target_hits());
  28071. }
  28072. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  28073. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  28074. // IPv4 target matches.
  28075. ProxyAndTargetServers s;
  28076. Client cli("127.0.0.1", s.target_port());
  28077. cli.set_proxy("127.0.0.1", s.proxy_port());
  28078. cli.set_no_proxy({"0.0.0.0/0"});
  28079. auto res = cli.Get("/");
  28080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28081. EXPECT_EQ(0, s.proxy_hits());
  28082. EXPECT_EQ(1, s.target_hits());
  28083. }
  28084. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  28085. ProxyAndTargetServers s;
  28086. Client cli("127.0.0.1", s.target_port());
  28087. cli.set_proxy("127.0.0.1", s.proxy_port());
  28088. cli.set_no_proxy({"127.0.0.1"});
  28089. auto res = cli.Get("/");
  28090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28091. EXPECT_EQ(0, s.proxy_hits());
  28092. EXPECT_EQ(1, s.target_hits());
  28093. }
  28094. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  28095. ProxyAndTargetServers s;
  28096. Client cli("127.0.0.1", s.target_port());
  28097. cli.set_proxy("127.0.0.1", s.proxy_port());
  28098. cli.set_no_proxy({"127.0.0.0/33"});
  28099. auto res = cli.Get("/");
  28100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28101. EXPECT_GE(s.proxy_hits(), 1);
  28102. EXPECT_EQ(0, s.target_hits());
  28103. }
  28104. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  28105. // Empty prefix after the slash must be rejected, not silently treated as /32.
  28106. ProxyAndTargetServers s;
  28107. Client cli("127.0.0.1", s.target_port());
  28108. cli.set_proxy("127.0.0.1", s.proxy_port());
  28109. cli.set_no_proxy({"127.0.0.1/"});
  28110. auto res = cli.Get("/");
  28111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28112. EXPECT_GE(s.proxy_hits(), 1);
  28113. EXPECT_EQ(0, s.target_hits());
  28114. }
  28115. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  28116. ProxyAndTargetServers s;
  28117. auto cli = make_client("internal.corp", s);
  28118. cli->set_proxy_basic_auth("u", "p");
  28119. cli->set_no_proxy({"internal.corp"});
  28120. auto res = cli->Get("/");
  28121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28122. EXPECT_EQ(1, s.target_hits());
  28123. EXPECT_EQ(0, s.proxy_hits());
  28124. EXPECT_FALSE(s.last_had_proxy_authz())
  28125. << "Proxy-Authorization must not be sent direct to the target";
  28126. }
  28127. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  28128. ProxyAndTargetServers s;
  28129. auto cli = make_client("public.example", s);
  28130. cli->set_proxy_basic_auth("u", "p");
  28131. cli->set_no_proxy({"internal.corp"}); // does not match
  28132. auto res = cli->Get("/");
  28133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28134. EXPECT_GE(s.proxy_hits(), 1);
  28135. EXPECT_TRUE(s.last_had_proxy_authz());
  28136. }
  28137. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28138. std::atomic<int> hits{0};
  28139. std::atomic<int> hits_with_authz{0};
  28140. no_proxy_test::ScopedServer proxy_mock;
  28141. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28142. hits++;
  28143. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28144. if (req.target.find("/redir") != std::string::npos) {
  28145. res.set_redirect("http://other.example/landed");
  28146. } else {
  28147. res.set_content("via-proxy", "text/plain");
  28148. }
  28149. });
  28150. proxy_mock.listen();
  28151. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28152. hits = 0;
  28153. hits_with_authz = 0;
  28154. Client cli("public.example", 80);
  28155. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28156. cli.set_proxy_basic_auth(c.first, c.second);
  28157. cli.set_follow_location(true);
  28158. // The redirect to another host goes through the proxy as well
  28159. auto res = cli.Get("/redir");
  28160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28161. EXPECT_EQ(2, hits.load());
  28162. EXPECT_EQ(2, hits_with_authz.load());
  28163. }
  28164. }
  28165. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28166. ProxyAndTargetServers s;
  28167. auto cli = make_client("anything.test", s);
  28168. auto res = cli->Get("/");
  28169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28170. EXPECT_GE(s.proxy_hits(), 1);
  28171. EXPECT_EQ(0, s.target_hits());
  28172. }
  28173. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28174. ProxyAndTargetServers s;
  28175. auto cli = make_client("example.com", s);
  28176. cli->set_no_proxy({"example.com:8080"});
  28177. auto res = cli->Get("/");
  28178. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28179. EXPECT_GE(s.proxy_hits(), 1);
  28180. EXPECT_EQ(0, s.target_hits());
  28181. }
  28182. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28183. ProxyAndTargetServers s;
  28184. auto cli = make_client("anything.test", s);
  28185. cli->set_no_proxy({"", " ", "\t"});
  28186. auto res = cli->Get("/");
  28187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28188. EXPECT_GE(s.proxy_hits(), 1);
  28189. EXPECT_EQ(0, s.target_hits());
  28190. }
  28191. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28192. // An entry with leading/trailing whitespace must still match — env-style
  28193. // values are commonly pasted with stray spaces and an implementation
  28194. // that feeds the raw token directly to inet_pton would fail to match
  28195. // valid CIDRs because of the spaces.
  28196. ProxyAndTargetServers s;
  28197. Client cli("127.0.0.1", s.target_port());
  28198. cli.set_proxy("127.0.0.1", s.proxy_port());
  28199. cli.set_no_proxy({" 127.0.0.0/8 "});
  28200. auto res = cli.Get("/");
  28201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28202. EXPECT_EQ(0, s.proxy_hits());
  28203. EXPECT_EQ(1, s.target_hits());
  28204. }
  28205. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28206. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28207. // go direct and must NOT carry Proxy-Authorization.
  28208. std::atomic<int> proxy_hits{0};
  28209. std::atomic<int> target_hits{0};
  28210. std::atomic<bool> target_saw_authz{false};
  28211. no_proxy_test::ScopedServer proxy_mock, target;
  28212. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28213. proxy_hits++;
  28214. res.status = 302;
  28215. res.set_header("Location", "http://127.0.0.1:" +
  28216. std::to_string(target.port()) + "/landed");
  28217. });
  28218. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28219. target_hits++;
  28220. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28221. res.set_content("direct", "text/plain");
  28222. });
  28223. proxy_mock.listen();
  28224. target.listen();
  28225. Client cli("public.example", target.port());
  28226. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28227. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28228. cli.set_proxy_basic_auth("u", "p");
  28229. cli.set_no_proxy({"127.0.0.1"});
  28230. cli.set_follow_location(true);
  28231. auto res = cli.Get("/redir");
  28232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28233. EXPECT_GE(proxy_hits.load(), 1);
  28234. EXPECT_GE(target_hits.load(), 1);
  28235. EXPECT_FALSE(target_saw_authz.load());
  28236. }
  28237. #ifdef CPPHTTPLIB_SSL_ENABLED
  28238. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28239. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28240. // proxy creds would be sent to the (possibly hostile) origin.
  28241. std::atomic<int> target_hits{0};
  28242. std::atomic<bool> target_saw_proxy_authz{false};
  28243. no_proxy_test::ScopedServer target;
  28244. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28245. target_hits++;
  28246. if (req.has_header("Proxy-Authorization")) {
  28247. target_saw_proxy_authz = true;
  28248. }
  28249. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28250. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28251. "nonce=\"abc\", algorithm=MD5");
  28252. });
  28253. target.listen();
  28254. // The proxy address is set to the target's port: the bypass MUST kick in;
  28255. // if it doesn't, the test still routes "via proxy" to the same server and
  28256. // the Proxy-Authorization assertion below catches the leak.
  28257. Client cli("evil.example", target.port());
  28258. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28259. cli.set_proxy("127.0.0.1", target.port());
  28260. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28261. cli.set_no_proxy({"evil.example"});
  28262. auto res = cli.Get("/x");
  28263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28264. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28265. EXPECT_EQ(1, target_hits.load());
  28266. EXPECT_FALSE(target_saw_proxy_authz.load());
  28267. }
  28268. #endif
  28269. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28270. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28271. std::atomic<int> proxy_hits{0};
  28272. std::atomic<int> bypass_hits{0};
  28273. std::atomic<bool> proxy_saw_c_url{false};
  28274. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28275. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28276. proxy_hits++;
  28277. if (req.path.find("/start") != std::string::npos) {
  28278. res.status = 302;
  28279. res.set_header("Location", "http://127.0.0.1:" +
  28280. std::to_string(bypass_server.port()) +
  28281. "/middle");
  28282. return;
  28283. }
  28284. if (req.path.find("/end") != std::string::npos) {
  28285. proxy_saw_c_url = true;
  28286. res.set_content("c-via-proxy", "text/plain");
  28287. return;
  28288. }
  28289. res.set_content("unexpected", "text/plain");
  28290. });
  28291. // public.example's "advertised" port is arbitrary (the request never lands
  28292. // there — it goes through the proxy), but use a dynamic value to stay
  28293. // friendly with sharded parallel runs.
  28294. int public_port = bypass_server.port();
  28295. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28296. bypass_hits++;
  28297. res.status = 302;
  28298. res.set_header("Location", "http://public.example:" +
  28299. std::to_string(public_port) + "/end");
  28300. });
  28301. proxy_mock.listen();
  28302. bypass_server.listen();
  28303. Client cli("public.example", public_port);
  28304. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28305. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28306. cli.set_no_proxy({"127.0.0.1"});
  28307. cli.set_follow_location(true);
  28308. auto res = cli.Get("/start");
  28309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28310. EXPECT_EQ(StatusCode::OK_200, res->status);
  28311. EXPECT_EQ("c-via-proxy", res->body);
  28312. EXPECT_GE(proxy_hits.load(), 2);
  28313. EXPECT_GE(bypass_hits.load(), 1);
  28314. EXPECT_TRUE(proxy_saw_c_url.load());
  28315. }
  28316. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28317. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28318. // request reconnects to the correct endpoint.
  28319. std::atomic<int> proxy_hits{0};
  28320. std::atomic<int> target_hits{0};
  28321. no_proxy_test::ScopedServer proxy_mock, target;
  28322. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28323. proxy_hits++;
  28324. res.set_content("via-proxy", "text/plain");
  28325. });
  28326. target.svr().Get(".*", [&](const Request &, Response &res) {
  28327. target_hits++;
  28328. res.set_content("direct", "text/plain");
  28329. });
  28330. proxy_mock.listen();
  28331. target.listen();
  28332. Client cli("public.example", target.port());
  28333. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28334. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28335. cli.set_keep_alive(true);
  28336. auto res1 = cli.Get("/a");
  28337. ASSERT_TRUE(res1);
  28338. EXPECT_EQ("via-proxy", res1->body);
  28339. EXPECT_EQ(1, proxy_hits.load());
  28340. EXPECT_EQ(0, target_hits.load());
  28341. cli.set_no_proxy({"public.example"});
  28342. auto res2 = cli.Get("/b");
  28343. ASSERT_TRUE(res2);
  28344. EXPECT_EQ("direct", res2->body);
  28345. EXPECT_EQ(1, proxy_hits.load());
  28346. EXPECT_EQ(1, target_hits.load());
  28347. }
  28348. // Forward declarations (see the base64_encode note).
  28349. namespace httplib {
  28350. namespace detail {
  28351. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28352. int shutdown_socket(socket_t sock) noexcept;
  28353. } // namespace detail
  28354. } // namespace httplib
  28355. namespace proxy_tunnel_test {
  28356. const char *const kTunnelEstablished =
  28357. "HTTP/1.1 200 Connection established\r\n\r\n";
  28358. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28359. using ConnectReply = std::function<std::string(const std::string &head)>;
  28360. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28361. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28362. class ScopedConnectProxy {
  28363. public:
  28364. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28365. : forward_port_(forward_port), reply_(std::move(reply)) {
  28366. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28367. if (listen_sock_ == INVALID_SOCKET) { return; }
  28368. auto a = loopback(0);
  28369. auto addr = reinterpret_cast<sockaddr *>(&a);
  28370. socklen_t alen = sizeof(a);
  28371. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28372. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28373. ::listen(listen_sock_, 4) != 0) {
  28374. return;
  28375. }
  28376. port_ = ntohs(a.sin_port);
  28377. th_ = std::thread([this] { run(); });
  28378. }
  28379. ~ScopedConnectProxy() {
  28380. if (th_.joinable()) {
  28381. stop_ = true;
  28382. auto wake = connect_to(port_);
  28383. th_.join();
  28384. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28385. }
  28386. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28387. }
  28388. int port() const { return port_; }
  28389. int connect_hits() const { return connect_hits_.load(); }
  28390. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28391. std::string connect_request() const {
  28392. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28393. return connect_request_;
  28394. }
  28395. private:
  28396. static sockaddr_in loopback(int port) {
  28397. sockaddr_in a{};
  28398. a.sin_family = AF_INET;
  28399. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28400. a.sin_port = htons(static_cast<unsigned short>(port));
  28401. return a;
  28402. }
  28403. static socket_t connect_to(int port) {
  28404. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28405. if (sock == INVALID_SOCKET) { return sock; }
  28406. auto a = loopback(port);
  28407. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28408. detail::close_socket(sock);
  28409. return INVALID_SOCKET;
  28410. }
  28411. return sock;
  28412. }
  28413. static bool send_all(socket_t sock, const char *data, size_t size) {
  28414. while (size > 0) {
  28415. auto n = detail::send_socket(sock, data, size, 0);
  28416. if (n <= 0) { return false; }
  28417. data += n;
  28418. size -= static_cast<size_t>(n);
  28419. }
  28420. return true;
  28421. }
  28422. void run() {
  28423. for (;;) {
  28424. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28425. if (stop_) {
  28426. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28427. return;
  28428. }
  28429. if (client == INVALID_SOCKET) { continue; }
  28430. serve(client);
  28431. detail::close_socket(client);
  28432. }
  28433. }
  28434. void serve(socket_t client) {
  28435. std::string head;
  28436. char buf[2048];
  28437. while (head.find("\r\n\r\n") == std::string::npos) {
  28438. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28439. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28440. if (n <= 0) { return; }
  28441. head.append(buf, static_cast<size_t>(n));
  28442. }
  28443. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28444. connect_hits_++;
  28445. {
  28446. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28447. connect_request_ = head;
  28448. }
  28449. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28450. if (!send_all(client, res.data(), res.size()) ||
  28451. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28452. return;
  28453. }
  28454. auto origin = connect_to(forward_port_);
  28455. if (origin == INVALID_SOCKET) { return; }
  28456. // When either side stops, shut both down so the other pump returns too.
  28457. auto pump = [&](socket_t from, socket_t to) {
  28458. char b[8192];
  28459. for (;;) {
  28460. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28461. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28462. }
  28463. detail::shutdown_socket(client);
  28464. detail::shutdown_socket(origin);
  28465. };
  28466. std::thread up([&] { pump(client, origin); });
  28467. pump(origin, client);
  28468. up.join();
  28469. detail::close_socket(origin);
  28470. }
  28471. int forward_port_;
  28472. ConnectReply reply_;
  28473. socket_t listen_sock_ = INVALID_SOCKET;
  28474. int port_ = 0;
  28475. std::thread th_;
  28476. std::atomic<bool> stop_{false};
  28477. std::atomic<int> connect_hits_{0};
  28478. mutable std::mutex connect_request_mutex_;
  28479. std::string connect_request_;
  28480. };
  28481. } // namespace proxy_tunnel_test
  28482. #ifdef CPPHTTPLIB_SSL_ENABLED
  28483. namespace proxy_tunnel_test {
  28484. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28485. class ScopedSSLServer {
  28486. public:
  28487. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28488. port_ = svr_.bind_to_any_port("127.0.0.1");
  28489. }
  28490. ~ScopedSSLServer() {
  28491. svr_.stop();
  28492. if (th_.joinable()) { th_.join(); }
  28493. }
  28494. SSLServer &svr() { return svr_; }
  28495. int port() const { return port_; }
  28496. void listen() {
  28497. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28498. svr_.wait_until_ready();
  28499. }
  28500. private:
  28501. SSLServer svr_;
  28502. std::thread th_;
  28503. int port_ = 0;
  28504. };
  28505. // Sends one request through the CONNECT proxy to the TLS origin with a
  28506. // credential configured for each hop, and checks that each credential reaches
  28507. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28508. // origin's (every header in origin_headers) on the tunnelled request.
  28509. void CredentialsStayWithTheirHop(
  28510. const std::function<void(SSLClient &)> &set_credentials,
  28511. const std::string &scheme,
  28512. const std::vector<std::string> &origin_headers = {"Authorization"},
  28513. bool stream = false) {
  28514. std::atomic<int> origin_hits{0};
  28515. std::atomic<bool> origin_saw_proxy_authz{false};
  28516. std::atomic<bool> origin_saw_headers{false};
  28517. ScopedSSLServer origin;
  28518. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28519. origin_hits++;
  28520. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28521. origin_saw_headers =
  28522. std::all_of(origin_headers.begin(), origin_headers.end(),
  28523. [&](const std::string &h) { return req.has_header(h); });
  28524. res.set_content("ok", "text/plain");
  28525. });
  28526. origin.listen();
  28527. ScopedConnectProxy proxy(origin.port());
  28528. ASSERT_NE(0, proxy.port());
  28529. // Pinned to 127.0.0.1 for the same reason as the test below.
  28530. SSLClient cli("127.0.0.1", origin.port());
  28531. cli.enable_server_certificate_verification(false);
  28532. cli.set_proxy("127.0.0.1", proxy.port());
  28533. set_credentials(cli);
  28534. if (stream) {
  28535. auto handle = cli.open_stream("GET", "/x");
  28536. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28537. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28538. } else {
  28539. auto res = cli.Get("/x");
  28540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28541. EXPECT_EQ(StatusCode::OK_200, res->status);
  28542. }
  28543. EXPECT_EQ(1, origin_hits.load());
  28544. EXPECT_EQ(1, proxy.connect_hits());
  28545. EXPECT_TRUE(origin_saw_headers.load());
  28546. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28547. << "Proxy-Authorization must not be sent inside the tunnel";
  28548. auto connect_req = proxy.connect_request();
  28549. EXPECT_NE(std::string::npos,
  28550. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28551. for (const auto &h : origin_headers) {
  28552. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28553. << h << " must not be sent to the proxy on CONNECT";
  28554. }
  28555. }
  28556. } // namespace proxy_tunnel_test
  28557. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28558. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28559. [](SSLClient &cli) {
  28560. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28561. cli.set_basic_auth("origin-user", "origin-pass");
  28562. },
  28563. "Basic");
  28564. }
  28565. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28566. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28567. [](SSLClient &cli) {
  28568. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28569. cli.set_basic_auth("origin-user", "origin-pass");
  28570. },
  28571. "Basic", {"Authorization"}, true);
  28572. }
  28573. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28574. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28575. [](SSLClient &cli) {
  28576. cli.set_proxy_bearer_token_auth("proxy-token");
  28577. cli.set_bearer_token_auth("origin-token");
  28578. },
  28579. "Bearer");
  28580. }
  28581. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28582. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28583. [](SSLClient &cli) {
  28584. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28585. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28586. {"Cookie", "sid=origin-session"},
  28587. {"X-Api-Key", "origin-key"}});
  28588. },
  28589. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28590. }
  28591. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28592. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28593. // retry; otherwise proxy creds would be sent to the origin.
  28594. std::atomic<int> origin_hits{0};
  28595. std::atomic<bool> origin_saw_proxy_authz{false};
  28596. proxy_tunnel_test::ScopedSSLServer origin;
  28597. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28598. origin_hits++;
  28599. if (req.has_header("Proxy-Authorization")) {
  28600. origin_saw_proxy_authz = true;
  28601. }
  28602. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28603. res.set_header("Proxy-Authenticate",
  28604. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28605. "algorithm=MD5");
  28606. });
  28607. origin.listen();
  28608. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28609. ASSERT_NE(0, proxy.port());
  28610. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28611. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28612. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28613. // and answer with its own status, making this test flaky.
  28614. SSLClient cli("127.0.0.1", origin.port());
  28615. cli.enable_server_certificate_verification(false);
  28616. cli.set_proxy("127.0.0.1", proxy.port());
  28617. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28618. auto res = cli.Get("/x");
  28619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28620. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28621. EXPECT_EQ(1, origin_hits.load());
  28622. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28623. EXPECT_EQ(1, proxy.connect_hits());
  28624. }
  28625. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28626. std::string origin_sni;
  28627. std::string origin_host;
  28628. proxy_tunnel_test::ScopedSSLServer origin;
  28629. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28630. origin_sni = req.sni();
  28631. origin_host = req.get_header_value("Host");
  28632. res.set_content("ok", "text/plain");
  28633. });
  28634. origin.listen();
  28635. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28636. ASSERT_NE(0, proxy.port());
  28637. SSLClient cli("origin.example", origin.port());
  28638. cli.enable_server_certificate_verification(false);
  28639. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28640. cli.set_proxy("127.0.0.1", proxy.port());
  28641. auto res = cli.Get("/x");
  28642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28643. EXPECT_EQ(StatusCode::OK_200, res->status);
  28644. auto port = std::to_string(origin.port());
  28645. auto target = "127.0.0.1:" + port;
  28646. auto connect_req = proxy.connect_request();
  28647. EXPECT_EQ(1, proxy.connect_hits());
  28648. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28649. EXPECT_NE(std::string::npos,
  28650. connect_req.find("\r\nHost: " + target + "\r\n"));
  28651. EXPECT_EQ("origin.example", origin_sni);
  28652. EXPECT_EQ("origin.example:" + port, origin_host);
  28653. }
  28654. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28655. proxy_tunnel_test::ScopedSSLServer origin;
  28656. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28657. res.set_content("ok", "text/plain");
  28658. });
  28659. origin.listen();
  28660. proxy_tunnel_test::ScopedConnectProxy proxy(
  28661. origin.port(), [](const std::string &head) -> std::string {
  28662. if (head.find(
  28663. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28664. std::string::npos) {
  28665. return proxy_tunnel_test::kTunnelEstablished;
  28666. }
  28667. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28668. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28669. "nonce=\"abc\", algorithm=MD5\r\n"
  28670. "Content-Length: 0\r\n\r\n";
  28671. });
  28672. ASSERT_NE(0, proxy.port());
  28673. SSLClient cli("origin.example", origin.port());
  28674. cli.enable_server_certificate_verification(false);
  28675. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28676. cli.set_proxy("127.0.0.1", proxy.port());
  28677. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28678. auto res = cli.Get("/x");
  28679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28680. EXPECT_EQ(StatusCode::OK_200, res->status);
  28681. // The retried CONNECT is the one the proxy saw last.
  28682. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28683. auto connect_req = proxy.connect_request();
  28684. EXPECT_EQ(2, proxy.connect_hits());
  28685. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28686. EXPECT_NE(std::string::npos,
  28687. connect_req.find("\r\nHost: " + target + "\r\n"));
  28688. }
  28689. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28690. proxy_tunnel_test::ScopedSSLServer origin;
  28691. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28692. res.set_content("ok", "text/plain");
  28693. });
  28694. origin.listen();
  28695. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28696. ASSERT_NE(0, proxy.port());
  28697. SSLClient cli("origin.example", origin.port());
  28698. cli.enable_server_certificate_verification(false);
  28699. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28700. cli.set_proxy("127.0.0.1", proxy.port());
  28701. auto res = cli.Get("/x");
  28702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28703. EXPECT_EQ(StatusCode::OK_200, res->status);
  28704. auto target = "origin.example:" + std::to_string(origin.port());
  28705. auto connect_req = proxy.connect_request();
  28706. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28707. EXPECT_NE(std::string::npos,
  28708. connect_req.find("\r\nHost: " + target + "\r\n"));
  28709. }
  28710. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28711. proxy_tunnel_test::ScopedSSLServer origin;
  28712. auto port = std::to_string(origin.port());
  28713. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28714. res.set_redirect("https://next.example:" + port + "/y");
  28715. });
  28716. origin.svr().Get("/y", [](const Request &, Response &res) {
  28717. res.set_content("ok", "text/plain");
  28718. });
  28719. origin.listen();
  28720. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28721. ASSERT_NE(0, proxy.port());
  28722. SSLClient cli("origin.example", origin.port());
  28723. cli.enable_server_certificate_verification(false);
  28724. cli.set_tunnel_hostname_addr_map(
  28725. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28726. cli.set_proxy("127.0.0.1", proxy.port());
  28727. cli.set_follow_location(true);
  28728. auto res = cli.Get("/x");
  28729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28730. EXPECT_EQ("ok", res->body);
  28731. // The last CONNECT is the redirect client's.
  28732. ASSERT_EQ(2, proxy.connect_hits());
  28733. auto target = "127.0.0.1:" + port;
  28734. auto connect_req = proxy.connect_request();
  28735. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28736. EXPECT_NE(std::string::npos,
  28737. connect_req.find("\r\nHost: " + target + "\r\n"));
  28738. }
  28739. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28740. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28741. std::atomic<int> origin_hits{0};
  28742. proxy_tunnel_test::ScopedSSLServer origin;
  28743. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28744. origin_hits++;
  28745. res.set_content("ok", "text/plain");
  28746. });
  28747. origin.listen();
  28748. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28749. ASSERT_NE(0, proxy.port());
  28750. SSLClient cli("127.0.0.1", origin.port());
  28751. cli.enable_server_certificate_verification(false);
  28752. cli.set_proxy("127.0.0.1", proxy.port());
  28753. cli.set_keep_alive(true);
  28754. cli.set_session_verifier(
  28755. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28756. auto res = cli.Get("/x");
  28757. EXPECT_FALSE(res);
  28758. ASSERT_FALSE(cli.is_socket_open());
  28759. res = cli.Get("/x");
  28760. EXPECT_FALSE(res);
  28761. EXPECT_EQ(2, proxy.connect_hits());
  28762. auto handle = cli.open_stream("GET", "/x");
  28763. EXPECT_FALSE(handle.is_valid());
  28764. EXPECT_EQ(3, proxy.connect_hits());
  28765. EXPECT_EQ(0, origin_hits.load());
  28766. }
  28767. #endif
  28768. namespace proxy_tunnel_test {
  28769. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28770. // anything else gets a 407 with `challenge`.
  28771. ConnectReply require_proxy_auth(const std::string &expected,
  28772. const std::string &challenge) {
  28773. return [=](const std::string &head) -> std::string {
  28774. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28775. std::string::npos) {
  28776. return kTunnelEstablished;
  28777. }
  28778. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28779. "Proxy-Authenticate: " +
  28780. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28781. };
  28782. }
  28783. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28784. // request, then echoes.
  28785. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28786. ws.send(
  28787. "authorization:" + req.get_header_value("Authorization") +
  28788. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28789. std::string msg;
  28790. while (ws.read(msg)) {
  28791. ws.send(msg);
  28792. }
  28793. }
  28794. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28795. class ScopedWebSocketOrigin {
  28796. public:
  28797. ScopedWebSocketOrigin() {
  28798. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28799. server_.listen();
  28800. }
  28801. int port() const { return server_.port(); }
  28802. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28803. std::string url() const {
  28804. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28805. }
  28806. private:
  28807. no_proxy_test::ScopedServer server_;
  28808. };
  28809. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28810. // passed as a constructor header, and checks that each reaches only its hop.
  28811. void WebSocketCredentialsStayWithTheirHop(
  28812. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28813. const std::string &proxy_authz, const std::string &origin_authz) {
  28814. ScopedWebSocketOrigin origin;
  28815. ScopedConnectProxy proxy(
  28816. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28817. ASSERT_NE(0, proxy.port());
  28818. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28819. client.set_proxy("127.0.0.1", proxy.port());
  28820. set_proxy_credentials(client);
  28821. auto res = client.connect();
  28822. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28823. std::string msg;
  28824. ASSERT_TRUE(client.read(msg));
  28825. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28826. client.close();
  28827. EXPECT_EQ(1, proxy.connect_hits());
  28828. EXPECT_EQ(std::string::npos,
  28829. proxy.connect_request().find("\r\nAuthorization: "))
  28830. << "origin credentials must not be sent to the proxy";
  28831. }
  28832. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28833. void WebSocketSetterCredentialsStayWithTheirHop(
  28834. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28835. const std::string &proxy_authz, const std::string &origin_authz) {
  28836. ScopedWebSocketOrigin origin;
  28837. ScopedConnectProxy proxy(
  28838. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28839. ASSERT_NE(0, proxy.port());
  28840. ws::WebSocketClient client(origin.url());
  28841. client.set_proxy("127.0.0.1", proxy.port());
  28842. set_credentials(client);
  28843. auto res = client.connect();
  28844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28845. std::string msg;
  28846. ASSERT_TRUE(client.read(msg));
  28847. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28848. client.close();
  28849. EXPECT_EQ(1, proxy.connect_hits());
  28850. EXPECT_EQ(std::string::npos,
  28851. proxy.connect_request().find("\r\nAuthorization: "))
  28852. << "origin credentials must not be sent to the proxy";
  28853. }
  28854. } // namespace proxy_tunnel_test
  28855. namespace {
  28856. // Connects `client` and returns the Authorization header its upgrade
  28857. // request carried, or "<failed>" when the connection could not be opened.
  28858. std::string websocket_authorization(ws::WebSocketClient &client) {
  28859. if (!client.connect()) { return "<failed>"; }
  28860. std::string msg;
  28861. if (!client.read(msg)) { return "<failed>"; }
  28862. client.close();
  28863. auto prefix = std::string("authorization:");
  28864. auto end = msg.find("|proxy-authorization:");
  28865. return msg.substr(prefix.size(), end - prefix.size());
  28866. }
  28867. } // namespace
  28868. TEST(WebSocketClientAuthTest, BasicAuth) {
  28869. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28870. ws::WebSocketClient client(origin.url());
  28871. client.set_basic_auth("user", "pass");
  28872. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28873. websocket_authorization(client));
  28874. }
  28875. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28876. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28877. ws::WebSocketClient client(origin.url());
  28878. client.set_basic_auth("user", "");
  28879. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28880. websocket_authorization(client));
  28881. }
  28882. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28883. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28884. ws::WebSocketClient client(origin.url());
  28885. client.set_bearer_token_auth("token123");
  28886. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28887. }
  28888. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28889. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28890. ws::WebSocketClient client(origin.url());
  28891. client.set_bearer_token_auth("token123");
  28892. client.set_basic_auth("user", "pass");
  28893. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28894. websocket_authorization(client));
  28895. }
  28896. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28897. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28898. ws::WebSocketClient client(origin.url(),
  28899. {{"Authorization", "Bearer from-header"}});
  28900. client.set_bearer_token_auth("from-setter");
  28901. client.set_basic_auth("user", "pass");
  28902. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28903. }
  28904. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28905. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28906. ws::WebSocketClient client(origin.url());
  28907. EXPECT_EQ("", websocket_authorization(client));
  28908. client.set_bearer_token_auth("first");
  28909. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28910. client.set_bearer_token_auth("second");
  28911. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28912. client.set_bearer_token_auth("");
  28913. EXPECT_EQ("", websocket_authorization(client));
  28914. }
  28915. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28916. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28917. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28918. ASSERT_NE(0, proxy.port());
  28919. ws::WebSocketClient client(origin.url());
  28920. client.set_proxy("127.0.0.1", proxy.port());
  28921. auto res = client.connect();
  28922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28923. std::string msg;
  28924. ASSERT_TRUE(client.read(msg));
  28925. ASSERT_TRUE(client.send("hello"));
  28926. ASSERT_TRUE(client.read(msg));
  28927. EXPECT_EQ("hello", msg);
  28928. client.close();
  28929. EXPECT_EQ(1, proxy.connect_hits());
  28930. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28931. auto connect_req = proxy.connect_request();
  28932. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28933. EXPECT_NE(std::string::npos,
  28934. connect_req.find("\r\nHost: " + target + "\r\n"));
  28935. }
  28936. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28937. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28938. [](ws::WebSocketClient &cli) {
  28939. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28940. },
  28941. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28942. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28943. }
  28944. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28945. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28946. [](ws::WebSocketClient &cli) {
  28947. cli.set_proxy_bearer_token_auth("proxy-token");
  28948. },
  28949. "Bearer proxy-token", "Bearer origin-token");
  28950. }
  28951. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28952. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28953. [](ws::WebSocketClient &cli) {
  28954. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28955. cli.set_basic_auth("origin-user", "origin-pass");
  28956. },
  28957. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28958. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28959. }
  28960. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28961. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28962. [](ws::WebSocketClient &cli) {
  28963. cli.set_proxy_bearer_token_auth("proxy-token");
  28964. cli.set_bearer_token_auth("origin-token");
  28965. },
  28966. "Bearer proxy-token", "Bearer origin-token");
  28967. }
  28968. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  28969. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28970. proxy_tunnel_test::ScopedConnectProxy proxy(
  28971. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28972. "Basic " + detail::base64_encode("proxy-user:"),
  28973. "Basic realm=\"proxy\""));
  28974. ASSERT_NE(0, proxy.port());
  28975. ws::WebSocketClient client(origin.url());
  28976. client.set_proxy("127.0.0.1", proxy.port());
  28977. client.set_proxy_basic_auth("proxy-user", "");
  28978. auto res = client.connect();
  28979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28980. client.close();
  28981. EXPECT_EQ(1, proxy.connect_hits());
  28982. }
  28983. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  28984. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28985. proxy_tunnel_test::ScopedConnectProxy proxy(
  28986. origin.port(), proxy_tunnel_test::require_proxy_auth(
  28987. "Bearer proxy-token", "Basic realm=\"proxy\""));
  28988. ASSERT_NE(0, proxy.port());
  28989. ws::WebSocketClient client(origin.url());
  28990. client.set_proxy("127.0.0.1", proxy.port());
  28991. auto res = client.connect();
  28992. EXPECT_FALSE(res);
  28993. EXPECT_EQ(Error::ProxyConnection, res.error());
  28994. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  28995. EXPECT_EQ("Basic realm=\"proxy\"",
  28996. res.get_header_value("Proxy-Authenticate"));
  28997. EXPECT_FALSE(client.is_open());
  28998. }
  28999. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  29000. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29001. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29002. ASSERT_NE(0, proxy.port());
  29003. ws::WebSocketClient client(origin.url());
  29004. client.set_proxy("127.0.0.1", proxy.port());
  29005. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29006. client.set_no_proxy({"127.0.0.1"});
  29007. auto res = client.connect();
  29008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29009. std::string msg;
  29010. ASSERT_TRUE(client.read(msg));
  29011. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29012. << "proxy credentials must not reach a bypassed origin";
  29013. client.close();
  29014. EXPECT_EQ(0, proxy.connect_hits());
  29015. }
  29016. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  29017. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29018. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29019. ASSERT_NE(0, proxy.port());
  29020. ws::WebSocketClient client(origin.url());
  29021. client.set_proxy("127.0.0.1", proxy.port());
  29022. ASSERT_TRUE(client.connect());
  29023. ASSERT_TRUE(client.connect());
  29024. client.close();
  29025. EXPECT_EQ(2, proxy.connect_hits());
  29026. }
  29027. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  29028. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29029. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29030. ASSERT_NE(0, proxy.port());
  29031. auto port = std::to_string(origin.port());
  29032. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29033. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29034. client.set_proxy("127.0.0.1", proxy.port());
  29035. auto res = client.connect();
  29036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29037. std::string msg;
  29038. ASSERT_TRUE(client.read(msg));
  29039. client.close();
  29040. EXPECT_EQ(1, proxy.connect_hits());
  29041. auto target = "127.0.0.1:" + port;
  29042. auto connect_req = proxy.connect_request();
  29043. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29044. EXPECT_NE(std::string::npos,
  29045. connect_req.find("\r\nHost: " + target + "\r\n"));
  29046. }
  29047. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  29048. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29049. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29050. ASSERT_NE(0, proxy.port());
  29051. auto port = std::to_string(origin.port());
  29052. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29053. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29054. client.set_proxy("127.0.0.1", proxy.port());
  29055. auto res = client.connect();
  29056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29057. client.close();
  29058. auto target = "origin.example:" + port;
  29059. auto connect_req = proxy.connect_request();
  29060. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29061. EXPECT_NE(std::string::npos,
  29062. connect_req.find("\r\nHost: " + target + "\r\n"));
  29063. }
  29064. #ifdef CPPHTTPLIB_SSL_ENABLED
  29065. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  29066. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29067. proxy_tunnel_test::ScopedConnectProxy proxy(
  29068. origin.port(), [](const std::string &head) -> std::string {
  29069. if (head.find(
  29070. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  29071. std::string::npos) {
  29072. return proxy_tunnel_test::kTunnelEstablished;
  29073. }
  29074. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29075. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  29076. "nonce=\"abc\", algorithm=MD5\r\n"
  29077. "Content-Length: 0\r\n\r\n";
  29078. });
  29079. ASSERT_NE(0, proxy.port());
  29080. ws::WebSocketClient client(origin.url());
  29081. client.set_proxy("127.0.0.1", proxy.port());
  29082. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  29083. auto res = client.connect();
  29084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29085. std::string msg;
  29086. ASSERT_TRUE(client.read(msg));
  29087. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  29088. client.close();
  29089. EXPECT_EQ(2, proxy.connect_hits());
  29090. }
  29091. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  29092. proxy_tunnel_test::ScopedSSLServer origin;
  29093. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  29094. origin.listen();
  29095. proxy_tunnel_test::ScopedConnectProxy proxy(
  29096. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29097. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  29098. ASSERT_NE(0, proxy.port());
  29099. ws::WebSocketClient client(
  29100. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  29101. client.enable_server_certificate_verification(false);
  29102. client.set_proxy("127.0.0.1", proxy.port());
  29103. client.set_proxy_bearer_token_auth("proxy-token");
  29104. auto res = client.connect();
  29105. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29106. std::string msg;
  29107. ASSERT_TRUE(client.read(msg));
  29108. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29109. << "Proxy-Authorization must not be sent inside the tunnel";
  29110. client.close();
  29111. EXPECT_EQ(1, proxy.connect_hits());
  29112. }
  29113. #endif
  29114. // ---------------------------------------------------------------------------
  29115. // Poller
  29116. // ---------------------------------------------------------------------------
  29117. namespace poller_test {
  29118. struct PollerBackend {
  29119. const char *name;
  29120. std::unique_ptr<detail::Poller> (*create)();
  29121. };
  29122. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  29123. *os << backend.name;
  29124. }
  29125. // Every backend runs the same contract tests. A new one is added here only.
  29126. std::vector<PollerBackend> poller_backends() {
  29127. return {
  29128. {"poll", &detail::PollPoller::create},
  29129. #ifdef __linux__
  29130. {"epoll", &detail::EpollPoller::create},
  29131. #endif
  29132. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29133. {"kqueue", &detail::KqueuePoller::create},
  29134. #endif
  29135. };
  29136. }
  29137. // A descriptor whose readability the test controls.
  29138. struct TestSocketPair {
  29139. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29140. TestSocketPair() { detail::create_socket_pair(fd); }
  29141. ~TestSocketPair() {
  29142. for (auto s : fd) {
  29143. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29144. }
  29145. }
  29146. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29147. socket_t reader() const { return fd[0]; }
  29148. void make_readable() {
  29149. const char c = 1;
  29150. detail::send_socket(fd[1], &c, 1, 0);
  29151. }
  29152. void close_writer() {
  29153. detail::close_socket(fd[1]);
  29154. fd[1] = INVALID_SOCKET;
  29155. }
  29156. };
  29157. using Tokens = std::vector<detail::Poller::Token>;
  29158. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29159. protected:
  29160. void SetUp() override {
  29161. poller_ = GetParam().create();
  29162. ASSERT_TRUE(poller_ != nullptr);
  29163. }
  29164. Tokens wait_for(int timeout_ms) {
  29165. Tokens ready;
  29166. poller_->wait(timeout_ms, ready);
  29167. std::sort(ready.begin(), ready.end());
  29168. return ready;
  29169. }
  29170. std::unique_ptr<detail::Poller> poller_;
  29171. };
  29172. } // namespace poller_test
  29173. using poller_test::PollerTest;
  29174. using poller_test::TestSocketPair;
  29175. using poller_test::Tokens;
  29176. INSTANTIATE_TEST_SUITE_P(
  29177. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29178. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29179. return std::string(p.param.name);
  29180. });
  29181. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29182. TestSocketPair sp;
  29183. ASSERT_TRUE(sp.ok());
  29184. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29185. EXPECT_EQ(Tokens{}, wait_for(0));
  29186. sp.make_readable();
  29187. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29188. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29189. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29190. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29191. }
  29192. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29193. TestSocketPair sp;
  29194. ASSERT_TRUE(sp.ok());
  29195. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29196. poller_->disarm(sp.reader());
  29197. poller_->disarm(sp.reader()); // disarming twice is harmless
  29198. sp.make_readable();
  29199. EXPECT_EQ(Tokens{}, wait_for(0));
  29200. }
  29201. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29202. TestSocketPair sp;
  29203. ASSERT_TRUE(sp.ok());
  29204. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29205. auto start = std::chrono::steady_clock::now();
  29206. EXPECT_EQ(Tokens{}, wait_for(30));
  29207. auto elapsed = std::chrono::steady_clock::now() - start;
  29208. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29209. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29210. }
  29211. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29212. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29213. for (detail::Poller::Token i = 0; i < 8; i++) {
  29214. sps.emplace_back(new TestSocketPair());
  29215. ASSERT_TRUE(sps.back()->ok());
  29216. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29217. }
  29218. sps[0]->make_readable();
  29219. sps[3]->make_readable();
  29220. sps[7]->make_readable();
  29221. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29222. // The others are still armed, the delivered ones are not.
  29223. sps[1]->make_readable();
  29224. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29225. EXPECT_EQ(Tokens{}, wait_for(0));
  29226. }
  29227. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29228. TestSocketPair s0, s1, s2;
  29229. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29230. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29231. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29232. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29233. // A delivery may move another entry inside the poller.
  29234. s0.make_readable();
  29235. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29236. // The entries left must still be found by descriptor.
  29237. poller_->disarm(s2.reader());
  29238. s1.make_readable();
  29239. s2.make_readable();
  29240. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29241. }
  29242. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29243. TestSocketPair sp;
  29244. ASSERT_TRUE(sp.ok());
  29245. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29246. sp.close_writer();
  29247. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29248. char c;
  29249. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29250. }
  29251. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29252. std::thread waker([&] {
  29253. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29254. poller_->wake();
  29255. });
  29256. Tokens ready;
  29257. auto start = std::chrono::steady_clock::now();
  29258. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29259. waker.join();
  29260. EXPECT_TRUE(ready.empty());
  29261. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29262. }
  29263. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29264. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29265. Tokens ready;
  29266. EXPECT_TRUE(poller_->wait(1000, ready));
  29267. }
  29268. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29269. for (int i = 0; i < 1000; i++) {
  29270. poller_->wake();
  29271. }
  29272. Tokens ready;
  29273. EXPECT_TRUE(poller_->wait(0, ready));
  29274. EXPECT_FALSE(poller_->wait(0, ready));
  29275. poller_->wake();
  29276. EXPECT_TRUE(poller_->wait(0, ready));
  29277. }
  29278. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29279. // Two threads publish changes and wake() after each, as a reactor's workers
  29280. // do. Every change must be seen without a wait() timing out. A lost wake()
  29281. // needs an unlucky interleaving, hence the rounds.
  29282. for (int round = 0; round < 5; round++) {
  29283. SCOPED_TRACE(round);
  29284. const int per_thread = 20000;
  29285. std::atomic<int> posted{0};
  29286. auto post = [&] {
  29287. for (int i = 0; i < per_thread; i++) {
  29288. posted++;
  29289. poller_->wake();
  29290. }
  29291. };
  29292. std::thread t1(post), t2(post);
  29293. auto lost = false;
  29294. Tokens ready;
  29295. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29296. if (!poller_->wait(1000, ready)) {
  29297. lost = true;
  29298. break;
  29299. }
  29300. }
  29301. t1.join();
  29302. t2.join();
  29303. ASSERT_FALSE(lost);
  29304. }
  29305. }
  29306. TEST(PollerFactoryTest, MakePollerWorks) {
  29307. auto poller = detail::make_poller();
  29308. ASSERT_TRUE(poller != nullptr);
  29309. poller->wake();
  29310. std::vector<detail::Poller::Token> ready;
  29311. EXPECT_TRUE(poller->wait(1000, ready));
  29312. }
  29313. // ---------------------------------------------------------------------------
  29314. // Keep-alive parking
  29315. // ---------------------------------------------------------------------------
  29316. namespace parking_test {
  29317. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29318. // runs once the port is bound and listening, before the server accepts.
  29319. struct RunningServer {
  29320. explicit RunningServer(
  29321. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29322. : svr_(svr) {
  29323. port = svr_.bind_to_any_port("127.0.0.1");
  29324. if (before_listen) { before_listen(port); }
  29325. thread = std::thread([this] { svr_.listen_after_bind(); });
  29326. svr_.wait_until_ready();
  29327. }
  29328. ~RunningServer() {
  29329. svr_.stop();
  29330. if (thread.joinable()) { thread.join(); }
  29331. }
  29332. Server &svr_;
  29333. int port = 0;
  29334. std::thread thread;
  29335. };
  29336. struct Sockets {
  29337. std::vector<socket_t> socks;
  29338. ~Sockets() {
  29339. for (auto s : socks) {
  29340. detail::close_socket(s);
  29341. }
  29342. }
  29343. socket_t connect(int port) {
  29344. auto error = Error::Success;
  29345. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29346. false, false, nullptr, 2, 0, 2, 0, 2,
  29347. 0, std::string(), error);
  29348. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29349. return s;
  29350. }
  29351. };
  29352. std::chrono::steady_clock::time_point in_ms(int ms) {
  29353. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29354. }
  29355. bool readable_by(socket_t sock,
  29356. std::chrono::steady_clock::time_point deadline) {
  29357. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29358. deadline - std::chrono::steady_clock::now())
  29359. .count();
  29360. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29361. }
  29362. bool send_get(socket_t sock, const std::string &path = "/") {
  29363. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29364. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29365. static_cast<ssize_t>(req.size());
  29366. }
  29367. // Reads one response whose body is "ok".
  29368. bool receives_ok(socket_t sock, int timeout_ms) {
  29369. auto deadline = in_ms(timeout_ms);
  29370. std::string buf;
  29371. while (readable_by(sock, deadline)) {
  29372. char tmp[1024];
  29373. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29374. if (n <= 0) { return false; }
  29375. buf.append(tmp, static_cast<size_t>(n));
  29376. auto end = buf.find("\r\n\r\n");
  29377. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29378. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29379. buf.compare(end + 4, 2, "ok") == 0;
  29380. }
  29381. }
  29382. return false;
  29383. }
  29384. bool get_ok(socket_t sock, int timeout_ms) {
  29385. return send_get(sock) && receives_ok(sock, timeout_ms);
  29386. }
  29387. // Whether the server closes `sock` by `deadline`.
  29388. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29389. char c;
  29390. return readable_by(sock, deadline) &&
  29391. detail::read_socket(sock, &c, 1, 0) <= 0;
  29392. }
  29393. // Whether the server closes `sock` without answering a request.
  29394. bool get_refused(socket_t sock, int timeout_ms) {
  29395. return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
  29396. }
  29397. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29398. auto deadline = in_ms(timeout_ms);
  29399. while (!cond()) {
  29400. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29401. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29402. }
  29403. return true;
  29404. }
  29405. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29406. svr.new_task_queue = std::move(new_task_queue);
  29407. svr.set_keep_alive_parking(true);
  29408. svr.Get("/", [](const Request &, Response &res) {
  29409. res.set_content("ok", "text/plain");
  29410. });
  29411. }
  29412. std::function<TaskQueue *(void)> threads(size_t n) {
  29413. return [n] { return new ThreadPool(n); };
  29414. }
  29415. // Counts what the event loop managed to queue, so that a test can wait for it.
  29416. class CountingTaskQueue final : public TaskQueue {
  29417. public:
  29418. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29419. std::atomic<int> &full)
  29420. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29421. bool enqueue(std::function<void()> fn) override {
  29422. auto queued = pool_.enqueue([this, fn]() {
  29423. fn();
  29424. // Holds the worker back from taking the next job.
  29425. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29426. });
  29427. (queued ? ok_ : full_)++;
  29428. return queued;
  29429. }
  29430. void shutdown() override { pool_.shutdown(); }
  29431. std::atomic<int> pause_after_ms{0};
  29432. private:
  29433. ThreadPool pool_;
  29434. std::atomic<int> &ok_;
  29435. std::atomic<int> &full_;
  29436. };
  29437. // Holds handlers until it opens, or for 3 seconds at most.
  29438. class Gate {
  29439. public:
  29440. void wait() {
  29441. std::unique_lock<std::mutex> lock(m_);
  29442. entered_++;
  29443. cv_.notify_all();
  29444. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29445. }
  29446. void open() {
  29447. std::lock_guard<std::mutex> guard(m_);
  29448. open_ = true;
  29449. cv_.notify_all();
  29450. }
  29451. int entered() {
  29452. std::lock_guard<std::mutex> guard(m_);
  29453. return entered_;
  29454. }
  29455. private:
  29456. std::mutex m_;
  29457. std::condition_variable cv_;
  29458. bool open_ = false;
  29459. int entered_ = 0;
  29460. };
  29461. } // namespace parking_test
  29462. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29463. using namespace parking_test;
  29464. Server svr;
  29465. serve_ok(svr, threads(1));
  29466. RunningServer running(svr);
  29467. Sockets socks;
  29468. // One kept-alive connection that has been served, and many that have not
  29469. // sent anything yet. None of them may keep the only worker.
  29470. auto served = socks.connect(running.port);
  29471. ASSERT_TRUE(get_ok(served, 2000));
  29472. for (int i = 0; i < 49; i++) {
  29473. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29474. }
  29475. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29476. EXPECT_TRUE(get_ok(served, 1000));
  29477. }
  29478. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29479. using namespace parking_test;
  29480. Server svr;
  29481. serve_ok(svr, threads(1));
  29482. svr.set_keep_alive_timeout(1);
  29483. RunningServer running(svr);
  29484. Sockets socks;
  29485. for (int i = 0; i < 3; i++) {
  29486. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29487. }
  29488. // One worker waiting on each in turn would take about 3 seconds.
  29489. auto deadline = in_ms(2000);
  29490. for (auto s : socks.socks) {
  29491. EXPECT_TRUE(sees_eof(s, deadline));
  29492. }
  29493. }
  29494. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29495. using namespace parking_test;
  29496. std::atomic<int> queued{0}, full{0};
  29497. Server svr;
  29498. // One worker and room for one queued task.
  29499. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29500. Gate gate;
  29501. svr.Get("/block", [&](const Request &, Response &res) {
  29502. gate.wait();
  29503. res.set_content("ok", "text/plain");
  29504. });
  29505. RunningServer running(svr);
  29506. // Before the server stops, so that a failed run does not wait for the
  29507. // handler's timeout.
  29508. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29509. Sockets socks;
  29510. auto a = socks.connect(running.port);
  29511. ASSERT_TRUE(get_ok(a, 2000));
  29512. // B keeps the only worker busy.
  29513. auto b = socks.connect(running.port);
  29514. ASSERT_TRUE(send_get(b, "/block"));
  29515. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29516. // A new connection C fills the queue.
  29517. auto c = socks.connect(running.port);
  29518. ASSERT_TRUE(send_get(c));
  29519. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29520. // A's next request finds the queue full, but A has been served before, so it
  29521. // waits instead of being cut off.
  29522. ASSERT_TRUE(send_get(a));
  29523. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29524. gate.open();
  29525. EXPECT_TRUE(receives_ok(b, 2000));
  29526. EXPECT_TRUE(receives_ok(c, 2000));
  29527. EXPECT_TRUE(receives_ok(a, 2000));
  29528. }
  29529. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29530. using namespace parking_test;
  29531. std::atomic<int> queued{0}, full{0};
  29532. CountingTaskQueue *queue = nullptr;
  29533. Server svr;
  29534. // Two workers and room for one queued task.
  29535. serve_ok(svr,
  29536. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29537. Gate first, second;
  29538. svr.Get("/first", [&](const Request &, Response &res) {
  29539. first.wait();
  29540. res.set_content("ok", "text/plain");
  29541. });
  29542. svr.Get("/second", [&](const Request &, Response &res) {
  29543. second.wait();
  29544. res.set_content("ok", "text/plain");
  29545. });
  29546. RunningServer running(svr);
  29547. auto open_gates = detail::scope_exit([&] {
  29548. first.open();
  29549. second.open();
  29550. });
  29551. Sockets socks;
  29552. auto a = socks.connect(running.port);
  29553. ASSERT_TRUE(get_ok(a, 2000));
  29554. // B and D take both workers, and C fills the queue. One at a time: the
  29555. // queue has room for one job only until a worker takes it.
  29556. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29557. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29558. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29559. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29560. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29561. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29562. // A's next request waits in the backlog.
  29563. ASSERT_TRUE(send_get(a));
  29564. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29565. // B's worker finishes, then takes C off the queue only later, which makes
  29566. // room for A.
  29567. queue->pause_after_ms = 200;
  29568. first.open();
  29569. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29570. queue->pause_after_ms = 0;
  29571. second.open();
  29572. EXPECT_TRUE(receives_ok(a, 2000));
  29573. }
  29574. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29575. using namespace parking_test;
  29576. Server svr;
  29577. serve_ok(svr, threads(1));
  29578. svr.set_keep_alive_timeout(0);
  29579. // The request is on the socket before the server accepts the connection,
  29580. // so it does not race the 10 ms floor. Without the floor the connection is
  29581. // closed unread.
  29582. Sockets socks;
  29583. auto sock = INVALID_SOCKET;
  29584. RunningServer running(svr, [&](int port) {
  29585. sock = socks.connect(port);
  29586. send_get(sock);
  29587. });
  29588. EXPECT_TRUE(receives_ok(sock, 1000));
  29589. }
  29590. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29591. using namespace parking_test;
  29592. for (int round = 0; round < 5; round++) {
  29593. SCOPED_TRACE(round);
  29594. Server svr;
  29595. serve_ok(svr, threads(2));
  29596. RunningServer running(svr);
  29597. Sockets socks;
  29598. for (int i = 0; i < 20; i++) {
  29599. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29600. }
  29601. auto start = std::chrono::steady_clock::now();
  29602. svr.stop();
  29603. running.thread.join();
  29604. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29605. std::chrono::milliseconds(500));
  29606. auto deadline = in_ms(1000);
  29607. for (auto s : socks.socks) {
  29608. EXPECT_TRUE(sees_eof(s, deadline));
  29609. }
  29610. }
  29611. }
  29612. #ifdef CPPHTTPLIB_SSL_ENABLED
  29613. namespace parking_test {
  29614. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29615. // that has opened a connection ahead of time. Freeing the session sends no
  29616. // close_notify, so the connection stays quiet.
  29617. bool handshake_only(socket_t sock) {
  29618. auto ctx = tls::create_client_context();
  29619. tls::set_verify_client(ctx, false);
  29620. auto session = tls::create_session(ctx, sock);
  29621. auto se = detail::scope_exit([&] {
  29622. tls::free_session(session);
  29623. tls::free_context(ctx);
  29624. });
  29625. tls::TlsError err;
  29626. return session &&
  29627. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29628. }
  29629. Client tls_client(int port) {
  29630. Client cli("https://127.0.0.1:" + std::to_string(port));
  29631. cli.enable_server_certificate_verification(false);
  29632. cli.set_keep_alive(true);
  29633. cli.set_connection_timeout(1);
  29634. cli.set_read_timeout(1);
  29635. return cli;
  29636. }
  29637. bool tls_get_ok(Client &cli) {
  29638. auto res = cli.Get("/");
  29639. return res && res->body == "ok";
  29640. }
  29641. } // namespace parking_test
  29642. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29643. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29644. struct {
  29645. unsigned long version;
  29646. bool safe;
  29647. } cases[] = {
  29648. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29649. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29650. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29651. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29652. };
  29653. for (const auto &c : cases) {
  29654. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29655. << std::hex << c.version;
  29656. }
  29657. }
  29658. #endif
  29659. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29660. using namespace parking_test;
  29661. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29662. ASSERT_TRUE(svr.is_valid());
  29663. serve_ok(svr, threads(1));
  29664. svr.set_read_timeout(1); // so that a failing run does not take long
  29665. RunningServer running(svr);
  29666. Sockets socks;
  29667. // One served connection, some that have not started their handshake, and
  29668. // one that has finished it and gone quiet. None may keep the only worker.
  29669. auto served = tls_client(running.port);
  29670. ASSERT_TRUE(tls_get_ok(served));
  29671. for (int i = 0; i < 10; i++) {
  29672. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29673. }
  29674. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29675. auto other = tls_client(running.port);
  29676. EXPECT_TRUE(tls_get_ok(other));
  29677. EXPECT_TRUE(tls_get_ok(served));
  29678. }
  29679. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29680. using namespace parking_test;
  29681. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29682. ASSERT_TRUE(svr.is_valid());
  29683. serve_ok(svr, threads(1));
  29684. RunningServer running(svr);
  29685. Sockets socks;
  29686. auto plain = socks.connect(running.port);
  29687. ASSERT_TRUE(send_get(plain));
  29688. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29689. EXPECT_NE(0, svr.ssl_last_error());
  29690. }
  29691. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29692. using namespace parking_test;
  29693. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29694. ASSERT_TRUE(svr.is_valid());
  29695. serve_ok(svr, threads(2));
  29696. RunningServer running(svr);
  29697. std::vector<Client> clients;
  29698. for (int i = 0; i < 5; i++) {
  29699. clients.push_back(tls_client(running.port));
  29700. ASSERT_TRUE(tls_get_ok(clients.back()));
  29701. }
  29702. auto start = std::chrono::steady_clock::now();
  29703. svr.stop();
  29704. running.thread.join();
  29705. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29706. std::chrono::milliseconds(500));
  29707. }
  29708. #endif
  29709. TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
  29710. using namespace parking_test;
  29711. for (auto parking : {false, true}) {
  29712. SCOPED_TRACE(parking);
  29713. Server svr;
  29714. serve_ok(svr, threads(2));
  29715. svr.set_keep_alive_parking(parking);
  29716. std::atomic<int> served{0};
  29717. svr.set_pre_routing_handler([&](const Request &, Response &) {
  29718. served++;
  29719. return Server::HandlerResponse::Unhandled;
  29720. });
  29721. std::atomic<bool> allow{false};
  29722. std::atomic<bool> peer_seen{false};
  29723. svr.set_accept_handler([&](socket_t sock) {
  29724. sockaddr_in addr{};
  29725. socklen_t len = sizeof(addr);
  29726. peer_seen =
  29727. getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
  29728. addr.sin_family == AF_INET &&
  29729. ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
  29730. return allow.load();
  29731. });
  29732. RunningServer running(svr);
  29733. Sockets socks;
  29734. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29735. EXPECT_TRUE(peer_seen);
  29736. EXPECT_EQ(0, served);
  29737. allow = true;
  29738. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29739. EXPECT_EQ(1, served);
  29740. }
  29741. }
  29742. TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
  29743. using namespace parking_test;
  29744. Server svr;
  29745. serve_ok(svr, threads(1));
  29746. svr.set_read_timeout(std::chrono::milliseconds(50));
  29747. std::atomic<bool> timed_out{false};
  29748. svr.set_accept_handler([&](socket_t sock) {
  29749. char c;
  29750. timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
  29751. return true;
  29752. });
  29753. RunningServer running(svr);
  29754. Sockets socks;
  29755. auto sock = socks.connect(running.port);
  29756. EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
  29757. EXPECT_TRUE(get_ok(sock, 1000));
  29758. }
  29759. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  29760. TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
  29761. using namespace parking_test;
  29762. Server svr;
  29763. serve_ok(svr, threads(1));
  29764. std::atomic<bool> throws{true};
  29765. svr.set_accept_handler([&](socket_t) -> bool {
  29766. if (throws) { throw std::runtime_error("refused"); }
  29767. return true;
  29768. });
  29769. std::atomic<int> logged{0};
  29770. svr.set_error_logger([&](const Error &err, const Request *) {
  29771. if (err == Error::UserCallbackException) { logged++; }
  29772. });
  29773. RunningServer running(svr);
  29774. Sockets socks;
  29775. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29776. EXPECT_EQ(1, logged);
  29777. throws = false;
  29778. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29779. }
  29780. #endif
  29781. #ifdef CPPHTTPLIB_SSL_ENABLED
  29782. TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
  29783. using namespace parking_test;
  29784. for (auto parking : {false, true}) {
  29785. SCOPED_TRACE(parking);
  29786. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29787. ASSERT_TRUE(svr.is_valid());
  29788. serve_ok(svr, threads(1));
  29789. svr.set_keep_alive_parking(parking);
  29790. svr.set_accept_handler([](socket_t) { return false; });
  29791. RunningServer running(svr);
  29792. Sockets socks;
  29793. // A handshake on a plain request would fail and set ssl_last_error().
  29794. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29795. EXPECT_EQ(0, svr.ssl_last_error());
  29796. }
  29797. }
  29798. #endif