test.cc 1.1 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516315173151831519315203152131522315233152431525315263152731528315293153031531315323153331534315353153631537315383153931540315413154231543315443154531546315473154831549315503155131552315533155431555315563155731558315593156031561315623156331564315653156631567315683156931570315713157231573315743157531576315773157831579315803158131582315833158431585315863158731588315893159031591315923159331594315953159631597315983159931600316013160231603316043160531606316073160831609316103161131612316133161431615316163161731618316193162031621316223162331624316253162631627316283162931630316313163231633316343163531636316373163831639316403164131642316433164431645316463164731648316493165031651316523165331654316553165631657316583165931660316613166231663316643166531666316673166831669316703167131672316733167431675316763167731678316793168031681316823168331684316853168631687316883168931690316913169231693316943169531696316973169831699317003170131702317033170431705317063170731708317093171031711317123171331714317153171631717317183171931720317213172231723317243172531726317273172831729317303173131732317333173431735317363173731738317393174031741317423174331744317453174631747317483174931750317513175231753317543175531756317573175831759317603176131762317633176431765317663176731768317693177031771317723177331774317753177631777317783177931780317813178231783317843178531786317873178831789317903179131792317933179431795317963179731798317993180031801318023180331804318053180631807318083180931810318113181231813318143181531816318173181831819318203182131822318233182431825318263182731828318293183031831318323183331834318353183631837318383183931840318413184231843318443184531846318473184831849318503185131852318533185431855318563185731858318593186031861318623186331864318653186631867318683186931870318713187231873318743187531876318773187831879318803188131882318833188431885318863188731888318893189031891318923189331894318953189631897318983189931900319013190231903319043190531906319073190831909319103191131912319133191431915319163191731918319193192031921319223192331924319253192631927319283192931930319313193231933319343193531936319373193831939319403194131942319433194431945319463194731948319493195031951319523195331954319553195631957319583195931960319613196231963319643196531966319673196831969319703197131972319733197431975319763197731978319793198031981319823198331984319853198631987319883198931990319913199231993319943199531996319973199831999320003200132002320033200432005320063200732008320093201032011320123201332014320153201632017320183201932020320213202232023320243202532026320273202832029320303203132032320333203432035320363203732038320393204032041320423204332044320453204632047320483204932050320513205232053320543205532056320573205832059320603206132062320633206432065320663206732068320693207032071320723207332074320753207632077320783207932080320813208232083320843208532086320873208832089320903209132092320933209432095320963209732098320993210032101321023210332104321053210632107321083210932110321113211232113321143211532116321173211832119321203212132122321233212432125321263212732128321293213032131321323213332134321353213632137321383213932140321413214232143321443214532146321473214832149321503215132152321533215432155321563215732158321593216032161321623216332164321653216632167321683216932170321713217232173321743217532176321773217832179321803218132182321833218432185321863218732188321893219032191321923219332194321953219632197321983219932200322013220232203322043220532206322073220832209322103221132212322133221432215322163221732218322193222032221322223222332224322253222632227322283222932230322313223232233322343223532236322373223832239322403224132242322433224432245322463224732248322493225032251322523225332254322553225632257322583225932260322613226232263322643226532266322673226832269322703227132272322733227432275322763227732278322793228032281322823228332284322853228632287322883228932290322913229232293322943229532296322973229832299323003230132302323033230432305323063230732308323093231032311323123231332314323153231632317323183231932320323213232232323323243232532326323273232832329323303233132332323333233432335323363233732338323393234032341323423234332344323453234632347323483234932350323513235232353323543235532356323573235832359323603236132362323633236432365323663236732368323693237032371323723237332374323753237632377323783237932380323813238232383323843238532386323873238832389323903239132392323933239432395323963239732398323993240032401324023240332404324053240632407324083240932410324113241232413324143241532416324173241832419324203242132422324233242432425324263242732428324293243032431324323243332434324353243632437324383243932440324413244232443324443244532446324473244832449324503245132452324533245432455324563245732458324593246032461324623246332464324653246632467324683246932470324713247232473324743247532476324773247832479324803248132482324833248432485324863248732488324893249032491324923249332494324953249632497324983249932500325013250232503325043250532506325073250832509325103251132512325133251432515325163251732518325193252032521325223252332524325253252632527325283252932530325313253232533325343253532536325373253832539325403254132542325433254432545325463254732548325493255032551325523255332554325553255632557325583255932560325613256232563325643256532566325673256832569325703257132572325733257432575325763257732578325793258032581325823258332584325853258632587325883258932590325913259232593325943259532596325973259832599326003260132602326033260432605326063260732608326093261032611326123261332614326153261632617326183261932620326213262232623326243262532626326273262832629326303263132632326333263432635326363263732638326393264032641326423264332644326453264632647326483264932650326513265232653326543265532656326573265832659326603266132662326633266432665326663266732668326693267032671326723267332674326753267632677326783267932680326813268232683326843268532686326873268832689326903269132692326933269432695326963269732698326993270032701327023270332704327053270632707327083270932710327113271232713327143271532716327173271832719327203272132722327233272432725327263272732728327293273032731327323273332734327353273632737327383273932740327413274232743327443274532746327473274832749327503275132752327533275432755327563275732758327593276032761327623276332764327653276632767327683276932770327713277232773327743277532776327773277832779327803278132782327833278432785327863278732788327893279032791327923279332794327953279632797327983279932800328013280232803328043280532806328073280832809328103281132812328133281432815328163281732818328193282032821328223282332824328253282632827328283282932830328313283232833328343283532836328373283832839328403284132842328433284432845328463284732848328493285032851328523285332854328553285632857328583285932860328613286232863328643286532866328673286832869328703287132872328733287432875328763287732878328793288032881328823288332884328853288632887328883288932890328913289232893328943289532896328973289832899329003290132902329033290432905329063290732908329093291032911329123291332914329153291632917329183291932920329213292232923329243292532926329273292832929329303293132932329333293432935329363293732938329393294032941329423294332944329453294632947329483294932950329513295232953329543295532956329573295832959329603296132962329633296432965329663296732968329693297032971329723297332974329753297632977329783297932980329813298232983329843298532986329873298832989329903299132992329933299432995329963299732998329993300033001330023300333004330053300633007330083300933010330113301233013330143301533016330173301833019330203302133022330233302433025330263302733028330293303033031330323303333034330353303633037330383303933040330413304233043330443304533046330473304833049330503305133052330533305433055330563305733058330593306033061330623306333064330653306633067330683306933070330713307233073330743307533076330773307833079330803308133082330833308433085330863308733088330893309033091330923309333094330953309633097330983309933100331013310233103331043310533106331073310833109331103311133112331133311433115331163311733118331193312033121331223312333124331253312633127331283312933130331313313233133331343313533136331373313833139331403314133142331433314433145331463314733148331493315033151331523315333154331553315633157331583315933160331613316233163331643316533166331673316833169331703317133172331733317433175331763317733178331793318033181331823318333184331853318633187331883318933190331913319233193331943319533196331973319833199332003320133202332033320433205332063320733208332093321033211332123321333214332153321633217332183321933220332213322233223332243322533226332273322833229332303323133232332333323433235332363323733238332393324033241332423324333244332453324633247332483324933250332513325233253332543325533256332573325833259332603326133262332633326433265332663326733268332693327033271332723327333274332753327633277332783327933280332813328233283332843328533286332873328833289332903329133292332933329433295332963329733298332993330033301333023330333304333053330633307333083330933310333113331233313333143331533316333173331833319333203332133322333233332433325333263332733328333293333033331333323333333334333353333633337333383333933340333413334233343333443334533346333473334833349333503335133352333533335433355333563335733358333593336033361333623336333364333653336633367333683336933370333713337233373333743337533376333773337833379333803338133382333833338433385333863338733388333893339033391333923339333394333953339633397333983339933400334013340233403334043340533406334073340833409334103341133412334133341433415334163341733418334193342033421334223342333424334253342633427334283342933430334313343233433334343343533436334373343833439334403344133442334433344433445334463344733448334493345033451334523345333454334553345633457334583345933460334613346233463334643346533466334673346833469334703347133472334733347433475334763347733478334793348033481334823348333484334853348633487334883348933490334913349233493334943349533496334973349833499335003350133502335033350433505335063350733508335093351033511335123351333514335153351633517335183351933520335213352233523335243352533526335273352833529335303353133532335333353433535335363353733538335393354033541335423354333544335453354633547335483354933550335513355233553335543355533556335573355833559335603356133562335633356433565335663356733568335693357033571335723357333574335753357633577335783357933580335813358233583335843358533586335873358833589335903359133592335933359433595335963359733598335993360033601336023360333604336053360633607336083360933610336113361233613336143361533616336173361833619336203362133622336233362433625336263362733628336293363033631336323363333634336353363633637336383363933640336413364233643336443364533646336473364833649336503365133652336533365433655336563365733658336593366033661336623366333664336653366633667336683366933670336713367233673336743367533676336773367833679336803368133682336833368433685336863368733688336893369033691336923369333694336953369633697336983369933700337013370233703337043370533706337073370833709337103371133712337133371433715337163371733718337193372033721337223372333724337253372633727337283372933730337313373233733337343373533736337373373833739337403374133742337433374433745337463374733748337493375033751337523375333754337553375633757337583375933760337613376233763337643376533766337673376833769337703377133772337733377433775337763377733778337793378033781337823378333784337853378633787337883378933790337913379233793337943379533796337973379833799338003380133802338033380433805338063380733808338093381033811338123381333814338153381633817338183381933820338213382233823338243382533826338273382833829338303383133832338333383433835338363383733838338393384033841338423384333844338453384633847338483384933850338513385233853338543385533856338573385833859338603386133862338633386433865338663386733868338693387033871338723387333874338753387633877338783387933880338813388233883338843388533886338873388833889338903389133892338933389433895338963389733898338993390033901339023390333904339053390633907339083390933910339113391233913339143391533916339173391833919339203392133922339233392433925339263392733928339293393033931339323393333934339353393633937339383393933940339413394233943339443394533946339473394833949339503395133952339533395433955339563395733958339593396033961339623396333964339653396633967339683396933970339713397233973339743397533976339773397833979339803398133982339833398433985339863398733988339893399033991339923399333994339953399633997339983399934000340013400234003340043400534006340073400834009340103401134012340133401434015340163401734018340193402034021340223402334024340253402634027340283402934030340313403234033340343403534036340373403834039340403404134042340433404434045340463404734048340493405034051340523405334054340553405634057340583405934060340613406234063340643406534066340673406834069340703407134072340733407434075340763407734078340793408034081340823408334084340853408634087340883408934090340913409234093340943409534096340973409834099341003410134102341033410434105341063410734108341093411034111341123411334114341153411634117341183411934120341213412234123341243412534126341273412834129341303413134132341333413434135341363413734138341393414034141341423414334144341453414634147341483414934150341513415234153341543415534156341573415834159341603416134162341633416434165341663416734168341693417034171341723417334174341753417634177341783417934180341813418234183341843418534186341873418834189341903419134192341933419434195341963419734198341993420034201342023420334204342053420634207342083420934210342113421234213342143421534216342173421834219342203422134222342233422434225342263422734228342293423034231342323423334234342353423634237342383423934240342413424234243342443424534246342473424834249342503425134252342533425434255342563425734258342593426034261342623426334264342653426634267342683426934270342713427234273342743427534276342773427834279342803428134282342833428434285342863428734288342893429034291342923429334294342953429634297342983429934300343013430234303343043430534306343073430834309343103431134312343133431434315343163431734318343193432034321343223432334324343253432634327343283432934330343313433234333343343433534336343373433834339343403434134342343433434434345343463434734348343493435034351343523435334354343553435634357343583435934360343613436234363343643436534366343673436834369343703437134372343733437434375343763437734378343793438034381343823438334384343853438634387343883438934390343913439234393343943439534396343973439834399344003440134402344033440434405344063440734408344093441034411344123441334414344153441634417344183441934420344213442234423344243442534426344273442834429344303443134432344333443434435344363443734438344393444034441344423444334444344453444634447344483444934450344513445234453344543445534456344573445834459344603446134462344633446434465344663446734468344693447034471344723447334474344753447634477344783447934480344813448234483344843448534486344873448834489344903449134492344933449434495344963449734498344993450034501345023450334504345053450634507345083450934510345113451234513345143451534516345173451834519345203452134522345233452434525345263452734528345293453034531345323453334534345353453634537345383453934540345413454234543345443454534546345473454834549345503455134552345533455434555345563455734558345593456034561345623456334564345653456634567345683456934570345713457234573345743457534576345773457834579345803458134582345833458434585345863458734588345893459034591345923459334594345953459634597345983459934600346013460234603346043460534606346073460834609346103461134612346133461434615346163461734618346193462034621346223462334624346253462634627346283462934630346313463234633346343463534636346373463834639346403464134642346433464434645346463464734648346493465034651346523465334654346553465634657346583465934660346613466234663346643466534666346673466834669346703467134672346733467434675346763467734678346793468034681346823468334684346853468634687346883468934690346913469234693346943469534696346973469834699347003470134702347033470434705347063470734708347093471034711347123471334714347153471634717347183471934720347213472234723347243472534726347273472834729347303473134732347333473434735347363473734738347393474034741347423474334744347453474634747347483474934750347513475234753347543475534756347573475834759347603476134762347633476434765347663476734768347693477034771347723477334774347753477634777347783477934780347813478234783347843478534786347873478834789347903479134792347933479434795347963479734798347993480034801348023480334804348053480634807348083480934810348113481234813348143481534816348173481834819348203482134822348233482434825348263482734828348293483034831348323483334834348353483634837348383483934840348413484234843348443484534846348473484834849348503485134852348533485434855348563485734858348593486034861348623486334864348653486634867348683486934870348713487234873348743487534876348773487834879348803488134882348833488434885348863488734888348893489034891348923489334894348953489634897348983489934900349013490234903349043490534906349073490834909349103491134912349133491434915349163491734918349193492034921349223492334924349253492634927349283492934930349313493234933349343493534936349373493834939349403494134942349433494434945349463494734948349493495034951349523495334954349553495634957349583495934960349613496234963349643496534966349673496834969349703497134972349733497434975349763497734978349793498034981349823498334984349853498634987349883498934990349913499234993349943499534996349973499834999350003500135002350033500435005350063500735008350093501035011350123501335014350153501635017350183501935020350213502235023350243502535026350273502835029350303503135032350333503435035350363503735038350393504035041350423504335044350453504635047350483504935050350513505235053350543505535056350573505835059350603506135062350633506435065350663506735068350693507035071350723507335074350753507635077350783507935080350813508235083350843508535086350873508835089350903509135092350933509435095350963509735098350993510035101351023510335104351053510635107351083510935110351113511235113351143511535116351173511835119351203512135122351233512435125351263512735128351293513035131351323513335134351353513635137351383513935140351413514235143351443514535146351473514835149351503515135152351533515435155351563515735158351593516035161351623516335164351653516635167351683516935170351713517235173351743517535176351773517835179351803518135182351833518435185351863518735188
  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. // Runs one 401 -> Digest-retry round trip with the given WWW-Authenticate
  3350. // field lines (get_combined_header_value() joins them in receipt order) and
  3351. // returns the Authorization header of the retry.
  3352. static std::string
  3353. get_digest_retry_authorization(const std::vector<std::string> &challenges) {
  3354. std::atomic<int> hits{0};
  3355. std::string authorization;
  3356. Server svr;
  3357. svr.Get("/x", [&](const Request &req, Response &res) {
  3358. if (++hits == 1) {
  3359. res.status = StatusCode::Unauthorized_401;
  3360. for (const auto &challenge : challenges) {
  3361. res.set_header("WWW-Authenticate", challenge);
  3362. }
  3363. } else {
  3364. authorization = req.get_header_value("Authorization");
  3365. res.set_content("ok", "text/plain");
  3366. }
  3367. });
  3368. auto port = svr.bind_to_any_port(HOST);
  3369. std::thread t([&]() { svr.listen_after_bind(); });
  3370. auto se = detail::scope_exit([&] {
  3371. svr.stop();
  3372. t.join();
  3373. });
  3374. svr.wait_until_ready();
  3375. Client cli(HOST, port);
  3376. cli.set_digest_auth("hello", "world");
  3377. auto res = cli.Get("/x");
  3378. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(2, hits.load());
  3380. return authorization;
  3381. }
  3382. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3383. // comma-separated list of challenges, and each challenge may itself carry a
  3384. // comma-separated auth-param list, so a server can legally offer Basic
  3385. // before Digest, either as two field lines or packed into one. Checks that
  3386. // the retry carries a well-formed Digest Authorization header naming
  3387. // expected_realm.
  3388. static void
  3389. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3390. const std::string &expected_realm) {
  3391. auto authorization = get_digest_retry_authorization(challenges);
  3392. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3393. EXPECT_NE(std::string::npos,
  3394. authorization.find("realm=\"" + expected_realm + "\""));
  3395. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3396. }
  3397. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3398. static const char *kDigestChallenge =
  3399. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3400. "algorithm=MD5";
  3401. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3402. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3403. "testrealm");
  3404. }
  3405. // Same challenge list with the schemes in the opposite order, to make sure
  3406. // the fix above didn't just special-case "Basic first".
  3407. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3408. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3409. "testrealm");
  3410. }
  3411. // A comma inside a quoted auth-param value must not be mistaken for the
  3412. // separator between two challenges (or two auth-params).
  3413. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3414. run_digest_challenge_list_test(
  3415. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3416. "algorithm=MD5"},
  3417. "test,realm");
  3418. }
  3419. // RFC 9110 11.2: auth-param names are matched case-insensitively.
  3420. TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
  3421. auto authorization = get_digest_retry_authorization(
  3422. {"Digest Realm=\"testrealm\", QOP=\"auth\", Nonce=\"abc123\", "
  3423. "Algorithm=SHA-256, OPAQUE=\"op\""});
  3424. EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
  3425. EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
  3426. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3427. EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
  3428. EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
  3429. }
  3430. // The algorithm is matched case-insensitively and sent back as the server
  3431. // wrote it (RFC 7616 3.4).
  3432. TEST(DigestAuthTest, AlgorithmValueIsCaseInsensitive) {
  3433. auto authorization = get_digest_retry_authorization(
  3434. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth\", algorithm=sha-256"});
  3435. EXPECT_NE(std::string::npos, authorization.find("algorithm=sha-256"));
  3436. const std::string prefix = "response=\"";
  3437. auto b = authorization.find(prefix);
  3438. ASSERT_NE(std::string::npos, b);
  3439. b += prefix.size();
  3440. EXPECT_EQ(64u, authorization.find('"', b) - b); // SHA-256, not MD5
  3441. }
  3442. // qop options are matched case-insensitively as whole tokens.
  3443. TEST(DigestAuthTest, QopValueIsCaseInsensitive) {
  3444. auto authorization = get_digest_retry_authorization(
  3445. {"Digest realm=\"r\", nonce=\"n\", qop=\"AUTH\""});
  3446. EXPECT_NE(std::string::npos, authorization.find("qop=auth,"));
  3447. authorization = get_digest_retry_authorization(
  3448. {"Digest realm=\"r\", nonce=\"n\", qop=\"auth-conf\""});
  3449. EXPECT_EQ(std::string::npos, authorization.find("qop="));
  3450. }
  3451. // RFC 7616 3.7: the client uses the first Digest challenge it can answer.
  3452. TEST(DigestAuthTest, SkipsUnanswerableDigestChallenges) {
  3453. auto authorization = get_digest_retry_authorization(
  3454. {"Digest realm=\"r\", nonce=\"n1\", algorithm=SHA-512-256, "
  3455. "Digest realm=\"r\", nonce=\"n2\", algorithm=SHA-256"});
  3456. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3457. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3458. authorization = get_digest_retry_authorization(
  3459. {"Digest realm=\"r\", qop=\"auth\", Digest realm=\"r\", nonce=\"n2\""});
  3460. EXPECT_NE(std::string::npos, authorization.find("nonce=\"n2\""));
  3461. }
  3462. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3463. // the params and leaves out the fragment.
  3464. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3465. Server svr;
  3466. std::string uri, target;
  3467. svr.Get("/a b", [&](const Request &req, Response &res) {
  3468. auto auth = req.get_header_value("Authorization");
  3469. if (auth.empty()) {
  3470. res.status = StatusCode::Unauthorized_401;
  3471. res.set_header("WWW-Authenticate",
  3472. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3473. return;
  3474. }
  3475. auto b = auth.find("uri=\"") + 5;
  3476. uri = auth.substr(b, auth.find('"', b) - b);
  3477. target = req.target;
  3478. });
  3479. auto port = svr.bind_to_any_port(HOST);
  3480. std::thread t([&]() { svr.listen_after_bind(); });
  3481. auto se = detail::scope_exit([&] {
  3482. svr.stop();
  3483. t.join();
  3484. });
  3485. svr.wait_until_ready();
  3486. Client cli(HOST, port);
  3487. cli.set_digest_auth("hello", "world");
  3488. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3490. EXPECT_EQ("/a%20b?x=1", target);
  3491. EXPECT_EQ(target, uri);
  3492. }
  3493. // A Digest challenge the client can't answer (realm or nonce missing, or an
  3494. // algorithm it doesn't implement (RFC 7616 3.3)) must leave the 401 as it is,
  3495. // without a retry.
  3496. static void
  3497. run_unanswerable_digest_challenge_test(const std::string &challenge) {
  3498. std::atomic<int> hits{0};
  3499. Server svr;
  3500. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3501. ++hits;
  3502. res.status = StatusCode::Unauthorized_401;
  3503. res.set_header("WWW-Authenticate", challenge);
  3504. });
  3505. auto port = svr.bind_to_any_port(HOST);
  3506. std::thread t([&]() { svr.listen_after_bind(); });
  3507. auto se = detail::scope_exit([&] {
  3508. svr.stop();
  3509. t.join();
  3510. });
  3511. svr.wait_until_ready();
  3512. Client cli(HOST, port);
  3513. cli.set_digest_auth("hello", "world");
  3514. auto res = cli.Get("/x");
  3515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3516. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3517. EXPECT_EQ(1, hits.load());
  3518. }
  3519. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3520. run_unanswerable_digest_challenge_test("Digest qop=\"auth\"");
  3521. }
  3522. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3523. run_unanswerable_digest_challenge_test("Digest realm=\"r\", qop=\"auth\"");
  3524. }
  3525. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3526. run_unanswerable_digest_challenge_test("Digest nonce=\"n\", qop=\"auth\"");
  3527. }
  3528. // RFC 7616 3.3: a challenge with an algorithm the client doesn't implement is
  3529. // ignored. The last value isn't a token and would otherwise inject auth-params
  3530. // into the Authorization header.
  3531. TEST(DigestAuthTest, UnsupportedAlgorithmIsIgnored) {
  3532. for (auto algorithm :
  3533. {"SHA-512-256", "MD5-sess", "\"MD5, injected=\\\"y\\\"\""}) {
  3534. SCOPED_TRACE(algorithm);
  3535. run_unanswerable_digest_challenge_test(
  3536. std::string("Digest realm=\"r\", nonce=\"n\", qop=\"auth\", "
  3537. "algorithm=") +
  3538. algorithm);
  3539. }
  3540. }
  3541. // A hostile server can put a '"' in realm/nonce/opaque in its challenge.
  3542. // parse_www_authenticate() de-escapes quoted-pairs when storing the values, so
  3543. // the header builder has to re-escape them; otherwise the value breaks out of
  3544. // its quoted-string and injects extra auth-params into the Authorization.
  3545. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3546. // On the wire the quotes embedded in the value are backslash-escaped.
  3547. auto authorization = get_digest_retry_authorization(
  3548. {"Digest realm=\"testrealm\", nonce=\"n\\\"; injected=\\\"x\", "
  3549. "qop=\"auth\""});
  3550. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3551. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3552. // inside its quoted-string rather than starting an "injected" auth-param.
  3553. EXPECT_NE(std::string::npos,
  3554. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3555. }
  3556. #endif
  3557. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3558. auto host = "google.com";
  3559. auto another_host = "example.com";
  3560. auto wrong_ip = "0.0.0.0";
  3561. #ifdef CPPHTTPLIB_SSL_ENABLED
  3562. SSLClient cli(host);
  3563. #else
  3564. Client cli(host);
  3565. #endif
  3566. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3567. auto res = cli.Get("/");
  3568. // Any status: Google may redirect or rate-limit CI runners.
  3569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3570. }
  3571. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3572. auto host = "google.com";
  3573. auto wrong_ip = "0.0.0.0";
  3574. #ifdef CPPHTTPLIB_SSL_ENABLED
  3575. SSLClient cli(host);
  3576. #else
  3577. Client cli(host);
  3578. #endif
  3579. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3580. auto res = cli.Get("/");
  3581. ASSERT_TRUE(!res);
  3582. EXPECT_EQ(Error::Connection, res.error());
  3583. }
  3584. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3585. // A mapped value that is not an IP literal must be resolved. "localhost"
  3586. // resolves from the hosts file, so this test needs no external DNS.
  3587. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3588. auto host = "target.invalid";
  3589. Server svr;
  3590. std::string received_host;
  3591. svr.Get("/hi", [&](const Request &req, Response &res) {
  3592. received_host = req.get_header_value("Host");
  3593. res.set_content("Hello World!", "text/plain");
  3594. });
  3595. auto port = svr.bind_to_any_port(HOST);
  3596. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3597. auto se = detail::scope_exit([&] {
  3598. svr.stop();
  3599. thread.join();
  3600. ASSERT_FALSE(svr.is_running());
  3601. });
  3602. svr.wait_until_ready();
  3603. Client cli(host, port);
  3604. cli.set_direct_hostname_addr_map({{host, HOST}});
  3605. auto res = cli.Get("/hi");
  3606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3607. EXPECT_EQ(StatusCode::OK_200, res->status);
  3608. // The mapping only redirects the connection; the identity stays host_.
  3609. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3610. }
  3611. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3612. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3613. auto host = "target.invalid";
  3614. Server svr;
  3615. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3616. res.set_content("Hello World!", "text/plain");
  3617. });
  3618. auto port = svr.bind_to_any_port("127.0.0.1");
  3619. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3620. auto se = detail::scope_exit([&] {
  3621. svr.stop();
  3622. thread.join();
  3623. ASSERT_FALSE(svr.is_running());
  3624. });
  3625. svr.wait_until_ready();
  3626. Client cli(host, port);
  3627. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3628. auto res = cli.Get("/hi");
  3629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3630. EXPECT_EQ(StatusCode::OK_200, res->status);
  3631. }
  3632. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3633. // An empty mapped value must leave host_ as the connection target. Without
  3634. // that guard the empty value would become the host argument, getaddrinfo
  3635. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3636. // loopback - silently connecting somewhere the caller never asked for.
  3637. // The server listens on loopback, so such a fallback would succeed and is
  3638. // therefore observable as a failure of this test.
  3639. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3640. Server svr;
  3641. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3642. res.set_content("Hello World!", "text/plain");
  3643. });
  3644. auto port = svr.bind_to_any_port(HOST);
  3645. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3646. auto se = detail::scope_exit([&] {
  3647. svr.stop();
  3648. thread.join();
  3649. ASSERT_FALSE(svr.is_running());
  3650. });
  3651. svr.wait_until_ready();
  3652. Client cli(blackhole, port);
  3653. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3654. cli.set_connection_timeout(1);
  3655. auto res = cli.Get("/hi");
  3656. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3657. }
  3658. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3659. auto host = "target.invalid";
  3660. Server svr;
  3661. std::string received_host;
  3662. svr.Get("/hi", [&](const Request &req, Response &res) {
  3663. received_host = req.get_header_value("Host");
  3664. res.set_content("Hello World!", "text/plain");
  3665. });
  3666. auto port = svr.bind_to_any_port("127.0.0.1");
  3667. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3668. auto se = detail::scope_exit([&] {
  3669. svr.stop();
  3670. thread.join();
  3671. ASSERT_FALSE(svr.is_running());
  3672. });
  3673. svr.wait_until_ready();
  3674. Client cli(host, port);
  3675. #pragma GCC diagnostic push
  3676. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3677. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3678. #pragma GCC diagnostic pop
  3679. auto res = cli.Get("/hi");
  3680. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3681. EXPECT_EQ(StatusCode::OK_200, res->status);
  3682. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3683. }
  3684. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3685. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3686. Server svr;
  3687. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3688. res.set_content("Hello World!", "text/plain");
  3689. });
  3690. auto port = svr.bind_to_any_port("127.0.0.1");
  3691. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3692. auto se = detail::scope_exit([&] {
  3693. svr.stop();
  3694. thread.join();
  3695. ASSERT_FALSE(svr.is_running());
  3696. });
  3697. svr.wait_until_ready();
  3698. Client cli("127.0.0.1", port);
  3699. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3700. cli.set_connection_timeout(1);
  3701. auto res = cli.Get("/hi");
  3702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3703. EXPECT_EQ(StatusCode::OK_200, res->status);
  3704. }
  3705. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3706. auto host = "httpbingo.org";
  3707. auto path = std::string{"/absolute-redirect/3"};
  3708. #ifdef CPPHTTPLIB_SSL_ENABLED
  3709. SSLClient cli(host);
  3710. #else
  3711. Client cli(host);
  3712. #endif
  3713. cli.set_follow_location(true);
  3714. auto res = retry_service_failures([&] { return cli.Get(path); });
  3715. SKIP_ON_SERVICE_FAILURE(res);
  3716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3717. EXPECT_EQ(StatusCode::OK_200, res->status);
  3718. }
  3719. TEST(RedirectTest, Redirect_Online) {
  3720. auto host = "httpbingo.org";
  3721. auto path = std::string{"/redirect/3"};
  3722. #ifdef CPPHTTPLIB_SSL_ENABLED
  3723. SSLClient cli(host);
  3724. #else
  3725. Client cli(host);
  3726. #endif
  3727. cli.set_follow_location(true);
  3728. auto res = retry_service_failures([&] { return cli.Get(path); });
  3729. SKIP_ON_SERVICE_FAILURE(res);
  3730. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3731. EXPECT_EQ(StatusCode::OK_200, res->status);
  3732. }
  3733. TEST(RelativeRedirectTest, Redirect_Online) {
  3734. auto host = "httpbingo.org";
  3735. auto path = std::string{"/relative-redirect/3"};
  3736. #ifdef CPPHTTPLIB_SSL_ENABLED
  3737. SSLClient cli(host);
  3738. #else
  3739. Client cli(host);
  3740. #endif
  3741. cli.set_follow_location(true);
  3742. auto res = retry_service_failures([&] { return cli.Get(path); });
  3743. SKIP_ON_SERVICE_FAILURE(res);
  3744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3745. EXPECT_EQ(StatusCode::OK_200, res->status);
  3746. }
  3747. TEST(TooManyRedirectTest, Redirect_Online) {
  3748. auto host = "httpbingo.org";
  3749. auto path = std::string{"/redirect/21"};
  3750. #ifdef CPPHTTPLIB_SSL_ENABLED
  3751. SSLClient cli(host);
  3752. #else
  3753. Client cli(host);
  3754. #endif
  3755. cli.set_follow_location(true);
  3756. auto res = retry_service_failures([&] { return cli.Get(path); });
  3757. SKIP_ON_SERVICE_FAILURE(res);
  3758. ASSERT_TRUE(!res);
  3759. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3760. }
  3761. #ifdef CPPHTTPLIB_SSL_ENABLED
  3762. TEST(YahooRedirectTest, Redirect_Online) {
  3763. Client cli("yahoo.com");
  3764. auto res = cli.Get("/");
  3765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3766. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3767. cli.set_follow_location(true);
  3768. res = cli.Get("/");
  3769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3770. EXPECT_EQ(StatusCode::OK_200, res->status);
  3771. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3772. }
  3773. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3774. #define REDIR_HOST "httpbingo.org"
  3775. #define REDIR_PATH "/redirect-to"
  3776. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3777. SSLClient cli(REDIR_HOST);
  3778. cli.set_follow_location(true);
  3779. auto res = retry_service_failures([&] {
  3780. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3781. });
  3782. SKIP_ON_SERVICE_FAILURE(res);
  3783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3784. EXPECT_EQ(StatusCode::OK_200, res->status);
  3785. }
  3786. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3787. SSLClient cli(REDIR_HOST);
  3788. cli.set_follow_location(true);
  3789. Params params;
  3790. params.emplace("url", "http://example.com");
  3791. params.emplace("status_code", "302");
  3792. auto res = retry_service_failures(
  3793. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3794. SKIP_ON_SERVICE_FAILURE(res);
  3795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3796. EXPECT_EQ(StatusCode::OK_200, res->status);
  3797. }
  3798. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3799. SSLClient cli(REDIR_HOST);
  3800. cli.set_follow_location(true);
  3801. Params params;
  3802. params.emplace("url", "http://example.com");
  3803. auto res = retry_service_failures([&] {
  3804. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3805. });
  3806. SKIP_ON_SERVICE_FAILURE(res);
  3807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3808. EXPECT_EQ(StatusCode::OK_200, res->status);
  3809. }
  3810. TEST(UrlWithSpace, Redirect_Online) {
  3811. SSLClient cli("edge.forgecdn.net");
  3812. cli.set_follow_location(true);
  3813. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3815. EXPECT_EQ(StatusCode::OK_200, res->status);
  3816. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3817. }
  3818. #endif
  3819. #if !defined(_WIN32) && !defined(_WIN64)
  3820. TEST(ReceiveSignals, Signal) {
  3821. auto setupSignalHandlers = []() {
  3822. struct sigaction act;
  3823. sigemptyset(&act.sa_mask);
  3824. act.sa_flags = SA_SIGINFO;
  3825. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3826. switch (sig) {
  3827. case SIGINT:
  3828. default: break;
  3829. }
  3830. };
  3831. ::sigaction(SIGINT, &act, nullptr);
  3832. };
  3833. Server svr;
  3834. int port = 0;
  3835. auto thread = std::thread([&]() {
  3836. setupSignalHandlers();
  3837. port = svr.bind_to_any_port(HOST);
  3838. svr.listen_after_bind();
  3839. });
  3840. auto se = detail::scope_exit([&] {
  3841. svr.stop();
  3842. thread.join();
  3843. ASSERT_FALSE(svr.is_running());
  3844. });
  3845. svr.wait_until_ready();
  3846. ASSERT_TRUE(svr.is_running());
  3847. pthread_kill(thread.native_handle(), SIGINT);
  3848. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3849. ASSERT_TRUE(svr.is_running());
  3850. }
  3851. #endif
  3852. TEST(RedirectToDifferentPort, Redirect) {
  3853. Server svr1;
  3854. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3855. res.set_content("Hello World!", "text/plain");
  3856. });
  3857. int svr1_port = 0;
  3858. auto thread1 = std::thread([&]() {
  3859. svr1_port = svr1.bind_to_any_port(HOST);
  3860. svr1.listen_after_bind();
  3861. });
  3862. Server svr2;
  3863. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3864. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3865. });
  3866. int svr2_port = 0;
  3867. auto thread2 = std::thread([&]() {
  3868. svr2_port = svr2.bind_to_any_port(HOST);
  3869. svr2.listen_after_bind();
  3870. });
  3871. auto se = detail::scope_exit([&] {
  3872. svr2.stop();
  3873. thread2.join();
  3874. svr1.stop();
  3875. thread1.join();
  3876. ASSERT_FALSE(svr2.is_running());
  3877. ASSERT_FALSE(svr1.is_running());
  3878. });
  3879. svr1.wait_until_ready();
  3880. svr2.wait_until_ready();
  3881. Client cli("localhost", svr2_port);
  3882. cli.set_follow_location(true);
  3883. auto res = cli.Get("/2");
  3884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3885. EXPECT_EQ(StatusCode::OK_200, res->status);
  3886. EXPECT_EQ("Hello World!", res->body);
  3887. }
  3888. // GET /redir on one server redirects to /target on another port, so the
  3889. // client follows it with a new client.
  3890. static Result
  3891. GetThroughRedirectToDifferentPort(Server::Handler target,
  3892. const std::function<void(Client &)> &setup,
  3893. const Headers &headers = Headers()) {
  3894. Server target_svr;
  3895. target_svr.Get("/target", target);
  3896. int target_port = 0;
  3897. auto target_thread = std::thread([&]() {
  3898. target_port = target_svr.bind_to_any_port(HOST);
  3899. target_svr.listen_after_bind();
  3900. });
  3901. Server origin_svr;
  3902. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3903. res.set_redirect(
  3904. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3905. });
  3906. int origin_port = 0;
  3907. auto origin_thread = std::thread([&]() {
  3908. origin_port = origin_svr.bind_to_any_port(HOST);
  3909. origin_svr.listen_after_bind();
  3910. });
  3911. auto se = detail::scope_exit([&] {
  3912. origin_svr.stop();
  3913. origin_thread.join();
  3914. target_svr.stop();
  3915. target_thread.join();
  3916. });
  3917. target_svr.wait_until_ready();
  3918. origin_svr.wait_until_ready();
  3919. Client cli("localhost", origin_port);
  3920. cli.set_follow_location(true);
  3921. setup(cli);
  3922. return cli.Get("/redir", headers);
  3923. }
  3924. static void
  3925. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3926. std::string captured_authorization;
  3927. auto result = GetThroughRedirectToDifferentPort(
  3928. [&](const Request &req, Response &res) {
  3929. captured_authorization = req.get_header_value("Authorization");
  3930. res.set_content("OK", "text/plain");
  3931. },
  3932. set_auth);
  3933. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3934. EXPECT_EQ(StatusCode::OK_200, result->status);
  3935. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3936. EXPECT_TRUE(captured_authorization.empty());
  3937. }
  3938. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3939. TestDoNotForwardCredentialsOnRedirect(
  3940. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3941. }
  3942. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3943. TestDoNotForwardCredentialsOnRedirect(
  3944. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3945. }
  3946. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3947. std::string captured_cookie;
  3948. auto result = GetThroughRedirectToDifferentPort(
  3949. [&](const Request &req, Response &res) {
  3950. captured_cookie = req.get_header_value("Cookie");
  3951. res.set_content("OK", "text/plain");
  3952. },
  3953. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3954. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3955. EXPECT_EQ(StatusCode::OK_200, result->status);
  3956. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3957. EXPECT_TRUE(captured_cookie.empty());
  3958. }
  3959. TEST(RedirectToSamePort, ForwardCookie) {
  3960. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3961. // header so that ordinary session flows keep working.
  3962. Server svr;
  3963. std::string captured_cookie;
  3964. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3965. res.set_redirect("/target", 302);
  3966. });
  3967. svr.Get("/target", [&](const Request &req, Response &res) {
  3968. captured_cookie = req.get_header_value("Cookie");
  3969. res.set_content("OK", "text/plain");
  3970. });
  3971. auto port = svr.bind_to_any_port(HOST);
  3972. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3973. auto se = detail::scope_exit([&] {
  3974. svr.stop();
  3975. thread.join();
  3976. ASSERT_FALSE(svr.is_running());
  3977. });
  3978. svr.wait_until_ready();
  3979. Client cli(HOST, port);
  3980. cli.set_follow_location(true);
  3981. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3982. auto res = cli.Get("/redir", headers);
  3983. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3984. EXPECT_EQ(StatusCode::OK_200, res->status);
  3985. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3986. }
  3987. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3988. // The Location alone names the next target, on any origin.
  3989. Server target_svr;
  3990. std::string cross_target;
  3991. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3992. cross_target = req.target;
  3993. res.set_content("OK", "text/plain");
  3994. });
  3995. auto target_port = target_svr.bind_to_any_port(HOST);
  3996. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3997. Server origin_svr;
  3998. std::string same_target;
  3999. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  4000. res.set_redirect(
  4001. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  4002. });
  4003. origin_svr.Get("/same", [&](const Request &, Response &res) {
  4004. res.set_redirect("/landing", 302);
  4005. });
  4006. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  4007. same_target = req.target;
  4008. res.set_content("OK", "text/plain");
  4009. });
  4010. auto origin_port = origin_svr.bind_to_any_port(HOST);
  4011. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  4012. auto se = detail::scope_exit([&] {
  4013. origin_svr.stop();
  4014. origin_thread.join();
  4015. target_svr.stop();
  4016. target_thread.join();
  4017. });
  4018. target_svr.wait_until_ready();
  4019. origin_svr.wait_until_ready();
  4020. Client cli("localhost", origin_port);
  4021. cli.set_follow_location(true);
  4022. Request req;
  4023. req.method = "GET";
  4024. req.params = {{"api_key", "SECRET"}};
  4025. req.path = "/cross";
  4026. auto res = cli.send(req);
  4027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4028. EXPECT_EQ("/landing", cross_target);
  4029. req.path = "/same";
  4030. res = cli.send(req);
  4031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4032. EXPECT_EQ("/landing", same_target);
  4033. }
  4034. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  4035. std::string authorization;
  4036. std::string trace_id;
  4037. auto result = GetThroughRedirectToDifferentPort(
  4038. [&](const Request &req, Response &res) {
  4039. authorization = req.get_header_value("Authorization");
  4040. trace_id = req.get_header_value("X-Trace-Id");
  4041. res.set_content("OK", "text/plain");
  4042. },
  4043. [](Client &cli) {
  4044. cli.set_default_headers(
  4045. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4046. });
  4047. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4048. EXPECT_EQ(StatusCode::OK_200, result->status);
  4049. // Like a header given with the request, a default one goes along unless it
  4050. // carries credentials (RFC 9110 15.4).
  4051. EXPECT_TRUE(authorization.empty());
  4052. EXPECT_EQ("42", trace_id);
  4053. }
  4054. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4055. auto result = GetThroughRedirectToDifferentPort(
  4056. [](const Request &, Response &res) {
  4057. res.set_content(std::string(2048, 'x'), "text/plain");
  4058. },
  4059. [](Client &cli) { cli.set_payload_max_length(1024); });
  4060. EXPECT_FALSE(result);
  4061. }
  4062. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4063. auto result = GetThroughRedirectToDifferentPort(
  4064. [](const Request &req, Response &res) {
  4065. // Answer after a second, or once the client gives up.
  4066. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4067. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4068. }
  4069. res.set_content("late", "text/plain");
  4070. },
  4071. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4072. ASSERT_FALSE(result);
  4073. EXPECT_EQ(Error::Read, result.error());
  4074. }
  4075. #ifdef CPPHTTPLIB_SSL_ENABLED
  4076. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4077. auto result = GetThroughRedirectToDifferentPort(
  4078. [](const Request &, Response &res) {
  4079. res.status = StatusCode::Unauthorized_401;
  4080. res.set_header("WWW-Authenticate",
  4081. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4082. },
  4083. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4084. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4085. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4086. }
  4087. #endif
  4088. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4089. Server svr;
  4090. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4091. // Port number that overflows int — should not crash
  4092. res.set_redirect("http://localhost:99999999999999999999/target");
  4093. });
  4094. auto port = svr.bind_to_any_port(HOST);
  4095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4096. auto se = detail::scope_exit([&] {
  4097. svr.stop();
  4098. thread.join();
  4099. ASSERT_FALSE(svr.is_running());
  4100. });
  4101. svr.wait_until_ready();
  4102. Client cli(HOST, port);
  4103. cli.set_follow_location(true);
  4104. auto res = cli.Get("/redir");
  4105. // Should fail gracefully, not crash (no valid response due to bad port)
  4106. EXPECT_FALSE(res);
  4107. }
  4108. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4109. Server svr;
  4110. auto port = svr.bind_to_any_port(HOST);
  4111. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4112. // The server's own port followed by junk must not be followed
  4113. res.set_redirect("http://" + std::string(HOST) + ":" +
  4114. std::to_string(port) + "junk/target");
  4115. });
  4116. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4117. res.set_content("target", "text/plain");
  4118. });
  4119. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4120. auto se = detail::scope_exit([&] {
  4121. svr.stop();
  4122. thread.join();
  4123. ASSERT_FALSE(svr.is_running());
  4124. });
  4125. svr.wait_until_ready();
  4126. Client cli(HOST, port);
  4127. cli.set_follow_location(true);
  4128. auto res = cli.Get("/redir");
  4129. EXPECT_FALSE(res);
  4130. }
  4131. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4132. Server target_svr;
  4133. std::atomic<int> target_hits{0};
  4134. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4135. target_hits++;
  4136. res.set_content("target", "text/plain");
  4137. });
  4138. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4139. res.set_content("target", "text/plain");
  4140. });
  4141. int target_port = 0;
  4142. auto target_thread = std::thread([&]() {
  4143. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4144. target_svr.listen_after_bind();
  4145. });
  4146. Server origin_svr;
  4147. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4148. res.set_redirect(req.get_param_value("to"));
  4149. });
  4150. int origin_port = 0;
  4151. auto origin_thread = std::thread([&]() {
  4152. origin_port = origin_svr.bind_to_any_port(HOST);
  4153. origin_svr.listen_after_bind();
  4154. });
  4155. auto se = detail::scope_exit([&] {
  4156. origin_svr.stop();
  4157. origin_thread.join();
  4158. target_svr.stop();
  4159. target_thread.join();
  4160. ASSERT_FALSE(origin_svr.is_running());
  4161. ASSERT_FALSE(target_svr.is_running());
  4162. });
  4163. target_svr.wait_until_ready();
  4164. origin_svr.wait_until_ready();
  4165. auto port = std::to_string(target_port);
  4166. for (const auto &to :
  4167. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4168. Client cli(HOST, origin_port);
  4169. cli.set_follow_location(true);
  4170. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4171. EXPECT_FALSE(res) << to;
  4172. }
  4173. EXPECT_EQ(0, target_hits);
  4174. Client cli(HOST, origin_port);
  4175. cli.set_follow_location(true);
  4176. auto res = cli.Get("/redir?to=" +
  4177. encode_query_component("//127.0.0.1:" + port + "/target"));
  4178. ASSERT_TRUE(res) << to_string(res.error());
  4179. EXPECT_EQ(StatusCode::OK_200, res->status);
  4180. EXPECT_EQ("target", res->body);
  4181. }
  4182. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4183. Server svr;
  4184. std::atomic<bool> followed{false};
  4185. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4186. res.status = StatusCode::NotModified_304;
  4187. res.set_header("Location", "/target");
  4188. });
  4189. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4190. res.status = StatusCode::UseProxy_305;
  4191. res.set_header("Location", "/target");
  4192. });
  4193. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4194. followed = true;
  4195. res.set_content("target", "text/plain");
  4196. });
  4197. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4198. auto se = detail::scope_exit([&] {
  4199. svr.stop();
  4200. th.join();
  4201. ASSERT_FALSE(svr.is_running());
  4202. });
  4203. svr.wait_until_ready();
  4204. Client cli("localhost", PORT);
  4205. cli.set_follow_location(true);
  4206. auto res = cli.Get("/304");
  4207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4208. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4209. res = cli.Get("/305");
  4210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4211. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4212. EXPECT_FALSE(followed);
  4213. }
  4214. TEST(RedirectFromPageWithContent, Redirect) {
  4215. Server svr;
  4216. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4217. res.set_content("___", "text/plain");
  4218. res.set_redirect("/2");
  4219. });
  4220. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4221. res.set_content("Hello World!", "text/plain");
  4222. });
  4223. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4224. auto se = detail::scope_exit([&] {
  4225. svr.stop();
  4226. th.join();
  4227. ASSERT_FALSE(svr.is_running());
  4228. });
  4229. svr.wait_until_ready();
  4230. {
  4231. Client cli("localhost", PORT);
  4232. cli.set_follow_location(true);
  4233. std::string body;
  4234. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4235. body.append(data, data_length);
  4236. return true;
  4237. });
  4238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4239. EXPECT_EQ(StatusCode::OK_200, res->status);
  4240. EXPECT_EQ("Hello World!", body);
  4241. }
  4242. {
  4243. Client cli("localhost", PORT);
  4244. std::string body;
  4245. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4246. body.append(data, data_length);
  4247. return true;
  4248. });
  4249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4250. EXPECT_EQ(StatusCode::Found_302, res->status);
  4251. EXPECT_EQ("___", body);
  4252. }
  4253. }
  4254. // A server can close the connection after a request with "Connection: close"
  4255. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4256. // redirected request must go out on a new connection.
  4257. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4258. #ifndef _WIN32
  4259. signal(SIGPIPE, SIG_IGN);
  4260. #endif
  4261. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4262. default_socket_options(srv);
  4263. sockaddr_in addr{};
  4264. addr.sin_family = AF_INET;
  4265. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4266. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4267. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4268. ASSERT_EQ(0, ::listen(srv, 2));
  4269. auto send_text = [](socket_t sock, const std::string &text) {
  4270. ::send(sock,
  4271. #ifdef _WIN32
  4272. static_cast<const char *>(text.c_str()),
  4273. static_cast<int>(text.size()),
  4274. #else
  4275. text.c_str(), text.size(),
  4276. #endif
  4277. 0);
  4278. };
  4279. auto reused = false;
  4280. auto server_thread = std::thread([&] {
  4281. char buf[4096];
  4282. auto first = ::accept(srv, nullptr, nullptr);
  4283. if (first == INVALID_SOCKET) { return; }
  4284. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4285. ::recv(first, buf, sizeof(buf), 0);
  4286. send_text(
  4287. first,
  4288. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4289. auto next = first;
  4290. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4291. reused = true;
  4292. } else {
  4293. detail::close_socket(first);
  4294. next = ::accept(srv, nullptr, nullptr);
  4295. if (next == INVALID_SOCKET) { return; }
  4296. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4297. ::recv(next, buf, sizeof(buf), 0);
  4298. }
  4299. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4300. "Connection: close\r\n\r\nok");
  4301. detail::close_socket(next);
  4302. });
  4303. Client cli("127.0.0.1", PORT + 2);
  4304. cli.set_follow_location(true);
  4305. cli.set_read_timeout(5, 0);
  4306. auto res = cli.Get("/1");
  4307. server_thread.join();
  4308. detail::close_socket(srv);
  4309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4310. EXPECT_EQ(StatusCode::OK_200, res->status);
  4311. EXPECT_EQ("ok", res->body);
  4312. EXPECT_FALSE(reused);
  4313. }
  4314. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4315. Server svr;
  4316. auto port_str = std::to_string(PORT);
  4317. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4318. auto expected_host = "[::1]:" + port_str;
  4319. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4320. res.set_content("___", "text/plain");
  4321. // res.set_redirect("/2");
  4322. res.set_redirect(redirect_url);
  4323. });
  4324. svr.Get("/2", [&](const Request &req, Response &res) {
  4325. auto host_header = req.headers.find("Host");
  4326. ASSERT_TRUE(host_header != req.headers.end());
  4327. EXPECT_EQ(expected_host, host_header->second);
  4328. res.set_content("Hello World!", "text/plain");
  4329. });
  4330. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4331. auto se = detail::scope_exit([&] {
  4332. svr.stop();
  4333. th.join();
  4334. ASSERT_FALSE(svr.is_running());
  4335. });
  4336. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4337. // actually starts anything, so the condition !svr.is_running() will
  4338. // always remain true, and the loop never stops.
  4339. // This basically counts how many milliseconds have passed since the
  4340. // call to svr.listen(), and if after 5 seconds nothing started yet
  4341. // aborts the test.
  4342. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4343. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4344. ASSERT_LT(milliseconds, 5000U);
  4345. }
  4346. {
  4347. Client cli("::1", PORT);
  4348. cli.set_follow_location(true);
  4349. std::string body;
  4350. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4351. body.append(data, data_length);
  4352. return true;
  4353. });
  4354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4355. EXPECT_EQ(StatusCode::OK_200, res->status);
  4356. EXPECT_EQ("Hello World!", body);
  4357. }
  4358. {
  4359. Client cli("::1", PORT);
  4360. std::string body;
  4361. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4362. body.append(data, data_length);
  4363. return true;
  4364. });
  4365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4366. EXPECT_EQ(StatusCode::Found_302, res->status);
  4367. EXPECT_EQ("___", body);
  4368. }
  4369. }
  4370. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4371. Server svr;
  4372. svr.Get("/foo", [](const Request &req, Response &res) {
  4373. auto a = req.params.find("a");
  4374. if (a != req.params.end()) {
  4375. res.set_content((*a).second, "text/plain");
  4376. res.status = StatusCode::OK_200;
  4377. } else {
  4378. res.status = StatusCode::BadRequest_400;
  4379. }
  4380. });
  4381. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4382. auto se = detail::scope_exit([&] {
  4383. svr.stop();
  4384. thread.join();
  4385. ASSERT_FALSE(svr.is_running());
  4386. });
  4387. svr.wait_until_ready();
  4388. {
  4389. Client cli(HOST, PORT);
  4390. cli.set_path_encode(false);
  4391. auto res = cli.Get("/foo?a=explicitly+encoded");
  4392. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4393. EXPECT_EQ(StatusCode::OK_200, res->status);
  4394. // This expects it back with a space, as the `+` won't have been
  4395. // url-encoded, and server-side the params get decoded turning `+`
  4396. // into spaces.
  4397. EXPECT_EQ("explicitly encoded", res->body);
  4398. }
  4399. }
  4400. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4401. // When path encoding is disabled the client must transmit the supplied
  4402. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4403. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4404. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4405. // than a space (0x20). Assert on the raw wire target to catch this.
  4406. Server svr;
  4407. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4408. svr.Get("/foo", [&](const Request &req, Response &res) {
  4409. EXPECT_EQ(expected_target, req.target);
  4410. res.status = StatusCode::OK_200;
  4411. });
  4412. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4413. auto se = detail::scope_exit([&] {
  4414. svr.stop();
  4415. thread.join();
  4416. ASSERT_FALSE(svr.is_running());
  4417. });
  4418. svr.wait_until_ready();
  4419. {
  4420. Client cli(HOST, PORT);
  4421. cli.set_path_encode(false);
  4422. auto res = cli.Get(expected_target.c_str());
  4423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4424. EXPECT_EQ(StatusCode::OK_200, res->status);
  4425. }
  4426. }
  4427. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4428. // `open_stream()` used to skip the path encoding that the buffered send
  4429. // path applies, so the same `path` produced different bytes in the request
  4430. // line depending on which API was used. Assert the two agree.
  4431. Server svr;
  4432. std::string target;
  4433. svr.Get(".*", [&](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. struct {
  4446. const char *path;
  4447. const char *expected;
  4448. } cases[] = {
  4449. {"/a b?x=1", "/a%20b?x=1"},
  4450. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4451. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4452. };
  4453. for (const auto &c : cases) {
  4454. Client cli(HOST, port);
  4455. target.clear();
  4456. auto res = cli.Get(c.path);
  4457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4458. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4459. auto buffered_target = target;
  4460. target.clear();
  4461. auto handle = cli.open_stream("GET", c.path);
  4462. EXPECT_TRUE(handle.is_valid())
  4463. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4464. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4465. }
  4466. }
  4467. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4468. // The `set_path_encode(false)` contract — transmit the supplied target
  4469. // verbatim — must hold for the streaming API too.
  4470. Server svr;
  4471. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4472. std::string target;
  4473. svr.Get("/foo", [&](const Request &req, Response &res) {
  4474. target = req.target;
  4475. res.status = StatusCode::OK_200;
  4476. });
  4477. auto port = svr.bind_to_any_port(HOST);
  4478. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4479. auto se = detail::scope_exit([&] {
  4480. svr.stop();
  4481. thread.join();
  4482. ASSERT_FALSE(svr.is_running());
  4483. });
  4484. svr.wait_until_ready();
  4485. {
  4486. Client cli(HOST, port);
  4487. cli.set_path_encode(false);
  4488. auto handle = cli.open_stream("GET", expected_target);
  4489. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4490. EXPECT_EQ(expected_target, target);
  4491. }
  4492. }
  4493. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4494. // With path encoding enabled a CR/LF in the target is percent-encoded
  4495. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4496. // write_request_line still backstops `set_path_encode(false)`, which is
  4497. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4498. Server svr;
  4499. // Captured before routing: the decoded path contains a newline, which a
  4500. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4501. std::string target;
  4502. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4503. target = req.target;
  4504. res.status = StatusCode::OK_200;
  4505. return Server::HandlerResponse::Handled;
  4506. });
  4507. auto port = svr.bind_to_any_port(HOST);
  4508. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4509. auto se = detail::scope_exit([&] {
  4510. svr.stop();
  4511. thread.join();
  4512. ASSERT_FALSE(svr.is_running());
  4513. });
  4514. svr.wait_until_ready();
  4515. {
  4516. Client cli(HOST, port);
  4517. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4518. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4519. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4520. }
  4521. }
  4522. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4523. // Every control character is percent-encoded, not just CR/LF, so the target
  4524. // passes the request-target check in write_request_line.
  4525. Server svr;
  4526. std::string target;
  4527. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4528. target = req.target;
  4529. res.status = StatusCode::OK_200;
  4530. return Server::HandlerResponse::Handled;
  4531. });
  4532. auto port = svr.bind_to_any_port(HOST);
  4533. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4534. auto se = detail::scope_exit([&] {
  4535. svr.stop();
  4536. thread.join();
  4537. ASSERT_FALSE(svr.is_running());
  4538. });
  4539. svr.wait_until_ready();
  4540. {
  4541. Client cli(HOST, port);
  4542. auto res = cli.Get("/a\tb\x1b\x7f");
  4543. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4544. EXPECT_EQ("/a%09b%1B%7F", target);
  4545. }
  4546. }
  4547. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4548. // Nothing may reach the wire: a raw CR/LF target would split the request
  4549. // line and inject headers.
  4550. Server svr;
  4551. // Pre-routing so that "not called" means nothing reached the server at all,
  4552. // rather than merely failing to match a handler pattern.
  4553. auto handler_called = false;
  4554. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4555. handler_called = true;
  4556. res.status = StatusCode::OK_200;
  4557. return Server::HandlerResponse::Handled;
  4558. });
  4559. auto port = svr.bind_to_any_port(HOST);
  4560. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4561. auto se = detail::scope_exit([&] {
  4562. svr.stop();
  4563. thread.join();
  4564. ASSERT_FALSE(svr.is_running());
  4565. });
  4566. svr.wait_until_ready();
  4567. {
  4568. Client cli(HOST, port);
  4569. cli.set_path_encode(false);
  4570. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4571. EXPECT_FALSE(handle.is_valid());
  4572. EXPECT_EQ(Error::Write, handle.error);
  4573. EXPECT_FALSE(handler_called);
  4574. }
  4575. }
  4576. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4577. // Which of the two branches runs is decided by whether the query component
  4578. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4579. // an empty query and must still fall back to building one from
  4580. // `req.params`, while a non-empty query must win over `req.params`.
  4581. Server svr;
  4582. std::string target;
  4583. svr.Get("/foo", [&](const Request &req, Response &res) {
  4584. target = req.target;
  4585. res.status = StatusCode::OK_200;
  4586. });
  4587. auto port = svr.bind_to_any_port(HOST);
  4588. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4589. auto se = detail::scope_exit([&] {
  4590. svr.stop();
  4591. thread.join();
  4592. ASSERT_FALSE(svr.is_running());
  4593. });
  4594. svr.wait_until_ready();
  4595. {
  4596. // Trailing `?` -> empty query component -> `req.params` is used.
  4597. Client cli(HOST, port);
  4598. Request req;
  4599. req.method = "GET";
  4600. req.path = "/foo?";
  4601. req.params.emplace("a", "1");
  4602. target.clear();
  4603. auto res = cli.send(req);
  4604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4605. EXPECT_EQ("/foo?a=1", target);
  4606. }
  4607. {
  4608. // Non-empty query in `req.path` -> `req.params` is not appended.
  4609. Client cli(HOST, port);
  4610. Request req;
  4611. req.method = "GET";
  4612. req.path = "/foo?b=2";
  4613. req.params.emplace("a", "1");
  4614. target.clear();
  4615. auto res = cli.send(req);
  4616. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4617. EXPECT_EQ("/foo?b=2", target);
  4618. }
  4619. }
  4620. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4621. Server svr;
  4622. svr.Get("/", [](const Request &req, Response &) {
  4623. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4624. });
  4625. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4626. auto se = detail::scope_exit([&] {
  4627. svr.stop();
  4628. thread.join();
  4629. ASSERT_FALSE(svr.is_running());
  4630. });
  4631. svr.wait_until_ready();
  4632. {
  4633. Client cli(HOST, PORT);
  4634. cli.set_path_encode(false);
  4635. auto res = cli.Get("/?something=%0A");
  4636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4637. EXPECT_EQ(StatusCode::OK_200, res->status);
  4638. }
  4639. }
  4640. TEST(BindServerTest, BindDualStack) {
  4641. Server svr;
  4642. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4643. res.set_content("Hello World!", "text/plain");
  4644. });
  4645. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4646. auto se = detail::scope_exit([&] {
  4647. svr.stop();
  4648. thread.join();
  4649. ASSERT_FALSE(svr.is_running());
  4650. });
  4651. svr.wait_until_ready();
  4652. {
  4653. Client cli("127.0.0.1", PORT);
  4654. auto res = cli.Get("/1");
  4655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4656. EXPECT_EQ(StatusCode::OK_200, res->status);
  4657. EXPECT_EQ("Hello World!", res->body);
  4658. }
  4659. {
  4660. Client cli("::1", PORT);
  4661. auto res = cli.Get("/1");
  4662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4663. EXPECT_EQ(StatusCode::OK_200, res->status);
  4664. EXPECT_EQ("Hello World!", res->body);
  4665. }
  4666. }
  4667. TEST(BindServerTest, BindAndListenSeparately) {
  4668. Server svr;
  4669. int port = svr.bind_to_any_port("0.0.0.0");
  4670. ASSERT_TRUE(svr.is_valid());
  4671. ASSERT_TRUE(port > 0);
  4672. svr.stop();
  4673. }
  4674. // Reports whether anything is still listening on a loopback port. A plain
  4675. // connect() is used instead of a Client request because a socket left bound by
  4676. // mistake accepts the connection into its backlog and never answers, which
  4677. // would hang the test instead of failing it.
  4678. static bool is_loopback_port_accepting(int port) {
  4679. sockaddr_in addr{};
  4680. addr.sin_family = AF_INET;
  4681. addr.sin_port = htons(static_cast<uint16_t>(port));
  4682. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4683. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4684. EXPECT_NE(sock, INVALID_SOCKET);
  4685. if (sock == INVALID_SOCKET) { return false; }
  4686. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4687. static_cast<socklen_t>(sizeof(addr)));
  4688. detail::close_socket(sock);
  4689. return ret == 0;
  4690. }
  4691. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4692. Server svr;
  4693. auto port = svr.bind_to_any_port("127.0.0.1");
  4694. ASSERT_TRUE(port > 0);
  4695. svr.stop();
  4696. // bind_to_any_port() already called listen(2), so until stop() closed the
  4697. // descriptor the port kept accepting connections into the backlog. ASSERT
  4698. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4699. // below blocks forever in the accept loop.
  4700. ASSERT_FALSE(is_loopback_port_accepting(port));
  4701. // Nothing is left to accept on, so listen_after_bind() must report failure
  4702. // instead of returning success without ever serving.
  4703. EXPECT_FALSE(svr.listen_after_bind());
  4704. // The failed listen marks the server decommissioned, so a waiter returns
  4705. // instead of spinning forever.
  4706. svr.wait_until_ready();
  4707. }
  4708. #ifdef CPPHTTPLIB_SSL_ENABLED
  4709. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4710. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4711. CLIENT_CA_CERT_DIR);
  4712. int port = svr.bind_to_any_port("0.0.0.0");
  4713. ASSERT_TRUE(svr.is_valid());
  4714. ASSERT_TRUE(port > 0);
  4715. svr.stop();
  4716. }
  4717. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4718. // or a rejected CustomRoute() registration would not stop the server binding.
  4719. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4720. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4721. CLIENT_CA_CERT_DIR);
  4722. ASSERT_TRUE(svr.is_valid());
  4723. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4724. EXPECT_FALSE(svr.is_valid());
  4725. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4726. }
  4727. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4728. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4729. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4730. int port = svr.bind_to_any_port("0.0.0.0");
  4731. ASSERT_TRUE(svr.is_valid());
  4732. ASSERT_TRUE(port > 0);
  4733. svr.stop();
  4734. }
  4735. TEST(BindServerTest, UpdateCertsPem) {
  4736. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4737. int port = svr.bind_to_any_port("0.0.0.0");
  4738. ASSERT_TRUE(svr.is_valid());
  4739. ASSERT_TRUE(port > 0);
  4740. // Read PEM files
  4741. std::string cert_pem, key_pem, ca_pem;
  4742. read_file(SERVER_CERT_FILE, cert_pem);
  4743. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4744. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4745. // Update server certificates using PEM API
  4746. ASSERT_TRUE(
  4747. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4748. ASSERT_TRUE(svr.is_valid());
  4749. svr.stop();
  4750. }
  4751. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4752. // Start server with client CA (enables client auth)
  4753. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4754. ASSERT_TRUE(svr.is_valid());
  4755. bool handler_called = false;
  4756. svr.Get("/test", [&](const Request &req, Response &res) {
  4757. handler_called = true;
  4758. // Verify client certificate is present
  4759. auto cert = req.peer_cert();
  4760. EXPECT_TRUE(static_cast<bool>(cert));
  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. // Read PEM files
  4771. std::string cert_pem, key_pem, ca_pem;
  4772. read_file(SERVER_CERT_FILE, cert_pem);
  4773. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4774. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4775. // Update server certificates and client CA using PEM API while server running
  4776. ASSERT_TRUE(
  4777. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4778. // Connect with client certificate
  4779. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4780. cli.enable_server_certificate_verification(false);
  4781. cli.set_connection_timeout(30);
  4782. auto res = cli.Get("/test");
  4783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4784. ASSERT_EQ(StatusCode::OK_200, res->status);
  4785. ASSERT_TRUE(handler_called);
  4786. EXPECT_EQ("ok", res->body);
  4787. }
  4788. // Puts a CA that did not sign the client's certificate in the old one's place.
  4789. static bool replace_client_ca(SSLServer &svr) {
  4790. std::string cert_pem, key_pem, ca_pem;
  4791. read_file(SERVER_CERT_FILE, cert_pem);
  4792. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4793. read_file(SERVER_CERT2_FILE, ca_pem);
  4794. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4795. ca_pem.c_str());
  4796. }
  4797. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4798. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4799. ASSERT_TRUE(svr.is_valid());
  4800. svr.Get("/test", [](const Request &, Response &res) {
  4801. res.set_content("ok", "text/plain");
  4802. });
  4803. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4804. auto se = detail::scope_exit([&] {
  4805. svr.stop();
  4806. t.join();
  4807. ASSERT_FALSE(svr.is_running());
  4808. });
  4809. svr.wait_until_ready();
  4810. auto get = [] {
  4811. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4812. cli.enable_server_certificate_verification(false);
  4813. return cli.Get("/test");
  4814. };
  4815. ASSERT_TRUE(get());
  4816. ASSERT_TRUE(replace_client_ca(svr));
  4817. EXPECT_FALSE(get());
  4818. }
  4819. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4820. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4821. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4822. ASSERT_TRUE(svr.is_valid());
  4823. tls::set_verify_callback(svr.tls_context(),
  4824. [](const tls::VerifyContext &) -> bool {
  4825. throw std::runtime_error("verify");
  4826. });
  4827. svr.Get("/test", [](const Request &, Response &res) {
  4828. res.set_content("ok", "text/plain");
  4829. });
  4830. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4831. auto se = detail::scope_exit([&] {
  4832. svr.stop();
  4833. t.join();
  4834. ASSERT_FALSE(svr.is_running());
  4835. });
  4836. svr.wait_until_ready();
  4837. auto get = [] {
  4838. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4839. cli.enable_server_certificate_verification(false);
  4840. return cli.Get("/test");
  4841. };
  4842. EXPECT_FALSE(get());
  4843. // The handshake is over, so an update does not wait for it.
  4844. std::string cert_pem, key_pem;
  4845. read_file(SERVER_CERT_FILE, cert_pem);
  4846. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4847. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4848. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4849. return v.preverify_ok;
  4850. });
  4851. auto res = get();
  4852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4853. EXPECT_EQ("ok", res->body);
  4854. }
  4855. #endif
  4856. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4857. // Sends each request over a new connection with a client certificate,
  4858. // resuming the session of the one before when there is one.
  4859. class ResumingClient {
  4860. public:
  4861. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4862. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4863. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4864. SSL_FILETYPE_PEM);
  4865. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4866. // callback, not through SSL_get1_session().
  4867. SSL_CTX_set_app_data(ctx_, this);
  4868. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4869. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4870. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4871. auto self = static_cast<ResumingClient *>(
  4872. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4873. SSL_SESSION_free(self->session_);
  4874. self->session_ = session;
  4875. return 1; // Keeps the reference
  4876. });
  4877. }
  4878. ~ResumingClient() {
  4879. SSL_SESSION_free(session_);
  4880. SSL_CTX_free(ctx_);
  4881. }
  4882. // Tells whether the request was answered.
  4883. bool get() {
  4884. auto error = Error::Success;
  4885. auto sock = detail::create_client_socket(
  4886. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4887. /*connection_timeout_sec=*/5, 0,
  4888. /*read_timeout_sec=*/5, 0,
  4889. /*write_timeout_sec=*/5, 0, std::string(), error);
  4890. if (sock == INVALID_SOCKET) { return false; }
  4891. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4892. auto ssl = SSL_new(ctx_);
  4893. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4894. SSL_set_fd(ssl, static_cast<int>(sock));
  4895. if (session_) { SSL_set_session(ssl, session_); }
  4896. if (SSL_connect(ssl) != 1) { return false; }
  4897. reused_ = SSL_session_reused(ssl) == 1;
  4898. // Reading the response also takes in a TLS 1.3 session ticket.
  4899. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4900. "Connection: close\r\n\r\n";
  4901. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4902. std::string res;
  4903. char buf[256];
  4904. int n;
  4905. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4906. res.append(buf, static_cast<size_t>(n));
  4907. }
  4908. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4909. SSL_shutdown(ssl);
  4910. return res.find("200 OK") != std::string::npos;
  4911. }
  4912. // Whether the last connection resumed a session
  4913. bool reused() const { return reused_; }
  4914. private:
  4915. SSL_CTX *ctx_;
  4916. SSL_SESSION *session_ = nullptr;
  4917. bool reused_ = false;
  4918. };
  4919. // A client that resumes its session gets through, but not once the client CA
  4920. // has changed, as a resumed session does not show the certificate again.
  4921. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4922. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4923. ASSERT_TRUE(svr.is_valid());
  4924. svr.Get("/test", [](const Request &, Response &res) {
  4925. res.set_content("ok", "text/plain");
  4926. });
  4927. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4928. auto se = detail::scope_exit([&] {
  4929. svr.stop();
  4930. t.join();
  4931. ASSERT_FALSE(svr.is_running());
  4932. });
  4933. svr.wait_until_ready();
  4934. ResumingClient cli;
  4935. ASSERT_TRUE(cli.get());
  4936. ASSERT_TRUE(cli.get());
  4937. EXPECT_TRUE(cli.reused());
  4938. ASSERT_TRUE(replace_client_ca(svr));
  4939. EXPECT_FALSE(cli.get());
  4940. }
  4941. // A resumed session does not show the certificate again, so the server does
  4942. // not resume one with a verify callback to run on it.
  4943. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4944. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4945. ASSERT_TRUE(svr.is_valid());
  4946. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4947. return v.preverify_ok;
  4948. });
  4949. svr.Get("/test", [](const Request &, Response &res) {
  4950. res.set_content("ok", "text/plain");
  4951. });
  4952. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4953. auto se = detail::scope_exit([&] {
  4954. svr.stop();
  4955. t.join();
  4956. ASSERT_FALSE(svr.is_running());
  4957. });
  4958. svr.wait_until_ready();
  4959. ResumingClient cli;
  4960. ASSERT_TRUE(cli.get());
  4961. ASSERT_TRUE(cli.get());
  4962. EXPECT_FALSE(cli.reused());
  4963. }
  4964. #endif
  4965. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4966. // wolfSSL shares its session cache between contexts, so a resumed session
  4967. // could carry a client certificate checked against another server's CA, or
  4968. // against a client CA since replaced.
  4969. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4970. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4971. ASSERT_TRUE(svr.is_valid());
  4972. // Trusts a CA that did not sign the client's certificate.
  4973. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4974. ASSERT_TRUE(other.is_valid());
  4975. for (auto s : {&svr, &other}) {
  4976. s->Get("/test", [](const Request &, Response &res) {
  4977. res.set_content("ok", "text/plain");
  4978. });
  4979. }
  4980. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4981. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4982. auto se = detail::scope_exit([&] {
  4983. other.stop();
  4984. svr.stop();
  4985. t2.join();
  4986. t.join();
  4987. });
  4988. svr.wait_until_ready();
  4989. other.wait_until_ready();
  4990. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4991. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4992. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4993. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4994. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4995. ASSERT_EQ(WOLFSSL_SUCCESS,
  4996. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4997. WOLFSSL_FILETYPE_PEM));
  4998. WOLFSSL_SESSION *session = nullptr;
  4999. auto session_se = detail::scope_exit([&] {
  5000. if (session) { wolfSSL_SESSION_free(session); }
  5001. });
  5002. // A request over a new connection, resuming `session` when there is one and
  5003. // keeping the connection's own in its place. Tells whether it was answered.
  5004. auto get = [&](int port) {
  5005. auto error = Error::Success;
  5006. auto sock = detail::create_client_socket(
  5007. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  5008. /*connection_timeout_sec=*/5, 0,
  5009. /*read_timeout_sec=*/5, 0,
  5010. /*write_timeout_sec=*/5, 0, std::string(), error);
  5011. if (sock == INVALID_SOCKET) { return false; }
  5012. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  5013. auto ssl = wolfSSL_new(ctx);
  5014. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  5015. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  5016. if (session) { wolfSSL_set_session(ssl, session); }
  5017. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  5018. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  5019. "Connection: close\r\n\r\n";
  5020. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  5021. std::string res;
  5022. char buf[256];
  5023. int n;
  5024. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  5025. res.append(buf, static_cast<size_t>(n));
  5026. }
  5027. wolfSSL_shutdown(ssl);
  5028. if (session) { wolfSSL_SESSION_free(session); }
  5029. session = wolfSSL_get1_session(ssl);
  5030. return res.find("200 OK") != std::string::npos;
  5031. };
  5032. ASSERT_TRUE(get(PORT));
  5033. EXPECT_FALSE(get(PORT + 1));
  5034. ASSERT_TRUE(get(PORT));
  5035. ASSERT_TRUE(replace_client_ca(svr));
  5036. EXPECT_FALSE(get(PORT));
  5037. }
  5038. #endif
  5039. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  5040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5041. ASSERT_TRUE(svr.is_valid());
  5042. // Keep-alive parking would wait for the ClientHello without a handshake.
  5043. svr.set_keep_alive_parking(false);
  5044. svr.Get("/test", [](const Request &, Response &res) {
  5045. res.set_content("ok", "text/plain");
  5046. });
  5047. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5048. auto se = detail::scope_exit([&] {
  5049. svr.stop();
  5050. t.join();
  5051. ASSERT_FALSE(svr.is_running());
  5052. });
  5053. svr.wait_until_ready();
  5054. // A connection that sends no ClientHello keeps its handshake in progress,
  5055. // once the server has had a moment to start it.
  5056. auto error = Error::Success;
  5057. auto sock = detail::create_client_socket(
  5058. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5059. /*connection_timeout_sec=*/5, 0,
  5060. /*read_timeout_sec=*/5, 0,
  5061. /*write_timeout_sec=*/5, 0, std::string(), error);
  5062. ASSERT_NE(INVALID_SOCKET, sock);
  5063. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5064. std::string cert_pem, key_pem;
  5065. read_file(SERVER_CERT_FILE, cert_pem);
  5066. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5067. auto update = std::async(std::launch::async, [&]() {
  5068. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5069. });
  5070. EXPECT_EQ(std::future_status::timeout,
  5071. update.wait_for(std::chrono::milliseconds(200)));
  5072. detail::close_socket(sock);
  5073. EXPECT_TRUE(update.get());
  5074. SSLClient cli(HOST, PORT);
  5075. cli.enable_server_certificate_verification(false);
  5076. auto res = cli.Get("/test");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::OK_200, res->status);
  5079. }
  5080. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5082. ASSERT_TRUE(svr.is_valid());
  5083. // Keep-alive parking would wait for the ClientHello without a handshake.
  5084. svr.set_keep_alive_parking(false);
  5085. svr.set_read_timeout(10, 0);
  5086. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5087. auto se = detail::scope_exit([&] {
  5088. svr.stop();
  5089. if (t.joinable()) { t.join(); }
  5090. });
  5091. svr.wait_until_ready();
  5092. // A connection that sends no ClientHello keeps its handshake in progress,
  5093. // once the server has had a moment to start it.
  5094. auto error = Error::Success;
  5095. auto sock = detail::create_client_socket(
  5096. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5097. /*connection_timeout_sec=*/5, 0,
  5098. /*read_timeout_sec=*/5, 0,
  5099. /*write_timeout_sec=*/5, 0, std::string(), error);
  5100. ASSERT_NE(INVALID_SOCKET, sock);
  5101. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5102. auto start = std::chrono::steady_clock::now();
  5103. svr.stop();
  5104. t.join();
  5105. auto elapsed = std::chrono::steady_clock::now() - start;
  5106. detail::close_socket(sock);
  5107. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5108. }
  5109. #endif
  5110. TEST(ErrorHandlerTest, ContentLength) {
  5111. Server svr;
  5112. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5113. res.status = StatusCode::OK_200;
  5114. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5115. "text/html"); // <= Content-Length still 13
  5116. });
  5117. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5118. res.set_content("Hello World!\n", "text/plain");
  5119. res.status = 524;
  5120. });
  5121. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5122. auto se = detail::scope_exit([&] {
  5123. svr.stop();
  5124. thread.join();
  5125. ASSERT_FALSE(svr.is_running());
  5126. });
  5127. svr.wait_until_ready();
  5128. {
  5129. Client cli(HOST, PORT);
  5130. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5132. EXPECT_EQ(StatusCode::OK_200, res->status);
  5133. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5134. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5135. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5136. }
  5137. }
  5138. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5139. TEST(ExceptionTest, WithoutExceptionHandler) {
  5140. Server svr;
  5141. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5142. throw std::runtime_error("exception...");
  5143. });
  5144. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5145. throw std::runtime_error("exception\r\n...");
  5146. });
  5147. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5148. auto se = detail::scope_exit([&] {
  5149. svr.stop();
  5150. listen_thread.join();
  5151. ASSERT_FALSE(svr.is_running());
  5152. });
  5153. svr.wait_until_ready();
  5154. Client cli("localhost", PORT);
  5155. {
  5156. auto res = cli.Get("/exception");
  5157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5158. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5159. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5160. }
  5161. {
  5162. auto res = cli.Get("/unknown");
  5163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5164. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5165. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5166. }
  5167. }
  5168. TEST(ExceptionTest, WithExceptionHandler) {
  5169. Server svr;
  5170. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5171. std::exception_ptr ep) {
  5172. EXPECT_FALSE(ep == nullptr);
  5173. try {
  5174. std::rethrow_exception(ep);
  5175. } catch (std::exception &e) {
  5176. EXPECT_EQ("abc", std::string(e.what()));
  5177. } catch (...) {}
  5178. res.status = StatusCode::InternalServerError_500;
  5179. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5180. "text/html"); // <= Content-Length still 13 at this point
  5181. });
  5182. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5183. res.set_content("Hello World!\n", "text/plain");
  5184. throw std::runtime_error("abc");
  5185. });
  5186. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5187. auto se = detail::scope_exit([&] {
  5188. svr.stop();
  5189. thread.join();
  5190. ASSERT_FALSE(svr.is_running());
  5191. });
  5192. svr.wait_until_ready();
  5193. for (size_t i = 0; i < 10; i++) {
  5194. Client cli(HOST, PORT);
  5195. for (size_t j = 0; j < 100; j++) {
  5196. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5198. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5199. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5200. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5201. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5202. }
  5203. cli.set_keep_alive(true);
  5204. for (size_t j = 0; j < 100; j++) {
  5205. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5207. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5208. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5209. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5210. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5211. }
  5212. }
  5213. }
  5214. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5215. Server svr;
  5216. svr.set_exception_handler(
  5217. [](const Request &, Response &res, std::exception_ptr) {
  5218. res.set_content("oops", "text/plain");
  5219. });
  5220. svr.Get("/throw", [](const Request &, Response &) {
  5221. throw std::runtime_error("throw");
  5222. });
  5223. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5224. res.status = StatusCode::Created_201;
  5225. throw std::runtime_error("created-then-throw");
  5226. });
  5227. auto port = svr.bind_to_any_port(HOST);
  5228. ASSERT_GT(port, 0);
  5229. thread t = thread([&] { svr.listen_after_bind(); });
  5230. auto se = detail::scope_exit([&] {
  5231. svr.stop();
  5232. t.join();
  5233. ASSERT_FALSE(svr.is_running());
  5234. });
  5235. svr.wait_until_ready();
  5236. Client cli(HOST, port);
  5237. for (auto path : {"/throw", "/created-then-throw"}) {
  5238. auto res = cli.Get(path);
  5239. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5240. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5241. }
  5242. }
  5243. TEST(ExceptionTest, AndErrorHandler) {
  5244. Server svr;
  5245. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5246. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5247. });
  5248. svr.set_exception_handler(
  5249. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5250. EXPECT_FALSE(ep == nullptr);
  5251. try {
  5252. std::rethrow_exception(ep);
  5253. } catch (std::exception &e) {
  5254. res.set_content(e.what(), "text/html");
  5255. } catch (...) {}
  5256. res.status = StatusCode::InternalServerError_500;
  5257. });
  5258. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5259. throw std::runtime_error("EXCEPTION");
  5260. });
  5261. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5262. res.set_content("ERROR", "text/html");
  5263. res.status = StatusCode::InternalServerError_500;
  5264. });
  5265. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5266. auto se = detail::scope_exit([&] {
  5267. svr.stop();
  5268. thread.join();
  5269. ASSERT_FALSE(svr.is_running());
  5270. });
  5271. svr.wait_until_ready();
  5272. Client cli(HOST, PORT);
  5273. {
  5274. auto res = cli.Get("/exception");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5277. EXPECT_EQ("EXCEPTION", res->body);
  5278. }
  5279. {
  5280. auto res = cli.Get("/error");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5283. EXPECT_EQ("ERROR", res->body);
  5284. }
  5285. {
  5286. auto res = cli.Get("/invalid");
  5287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5288. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5289. EXPECT_EQ("NOT_FOUND", res->body);
  5290. }
  5291. }
  5292. #endif
  5293. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5294. // An exception from a user callback outside process_request()'s try/catch
  5295. // used to unwind into the task queue - which does not catch - and terminate
  5296. // the process. Each test below runs the server on a single worker thread: a
  5297. // guard that catches the exception but still loses the thread would otherwise
  5298. // be hidden by a spare worker serving the follow-up request. Note that a
  5299. // regression here aborts the whole test binary rather than failing one test.
  5300. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5301. Server svr;
  5302. svr.new_task_queue = [] { return new ThreadPool(1); };
  5303. std::atomic<int> reported{0};
  5304. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5305. if (err == Error::UserCallbackException) { reported++; }
  5306. });
  5307. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5308. res.set_content_provider(
  5309. 1024, "text/plain",
  5310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5311. sink.write("hello", 5);
  5312. throw std::runtime_error("from the content provider");
  5313. });
  5314. });
  5315. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5316. res.set_content("ok", "text/plain");
  5317. });
  5318. auto port = svr.bind_to_any_port(HOST);
  5319. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5320. auto se = detail::scope_exit([&] {
  5321. svr.stop();
  5322. listen_thread.join();
  5323. ASSERT_FALSE(svr.is_running());
  5324. });
  5325. svr.wait_until_ready();
  5326. {
  5327. Client cli(HOST, port);
  5328. cli.set_read_timeout(5, 0);
  5329. EXPECT_FALSE(cli.Get("/throw"));
  5330. }
  5331. EXPECT_TRUE(svr.is_running());
  5332. EXPECT_EQ(1, reported.load());
  5333. // A request on a fresh connection is still served.
  5334. {
  5335. Client cli(HOST, port);
  5336. auto res = cli.Get("/ok");
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. EXPECT_EQ(StatusCode::OK_200, res->status);
  5339. EXPECT_EQ("ok", res->body);
  5340. }
  5341. }
  5342. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5343. Server svr;
  5344. svr.new_task_queue = [] { return new ThreadPool(1); };
  5345. std::atomic<bool> should_throw{true};
  5346. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5347. res.set_content("hi", "text/plain");
  5348. });
  5349. svr.set_post_routing_handler(
  5350. [&](const Request & /*req*/, Response & /*res*/) {
  5351. if (should_throw) {
  5352. throw std::runtime_error("from the post-routing handler");
  5353. }
  5354. });
  5355. auto port = svr.bind_to_any_port(HOST);
  5356. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5357. auto se = detail::scope_exit([&] {
  5358. svr.stop();
  5359. listen_thread.join();
  5360. ASSERT_FALSE(svr.is_running());
  5361. });
  5362. svr.wait_until_ready();
  5363. {
  5364. Client cli(HOST, port);
  5365. cli.set_read_timeout(5, 0);
  5366. EXPECT_FALSE(cli.Get("/hi"));
  5367. }
  5368. EXPECT_TRUE(svr.is_running());
  5369. should_throw = false;
  5370. {
  5371. Client cli(HOST, port);
  5372. auto res = cli.Get("/hi");
  5373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5374. EXPECT_EQ(StatusCode::OK_200, res->status);
  5375. EXPECT_EQ("hi", res->body);
  5376. }
  5377. }
  5378. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5379. // The guard reports the caught exception through the error logger, which is
  5380. // a user callback too. A logger that throws has to be contained as well, or
  5381. // the process would terminate from inside the catch.
  5382. Server svr;
  5383. svr.new_task_queue = [] { return new ThreadPool(1); };
  5384. std::atomic<int> reported{0};
  5385. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5386. if (err == Error::UserCallbackException) {
  5387. reported++;
  5388. throw std::runtime_error("from the error logger");
  5389. }
  5390. });
  5391. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5392. res.set_content_provider(
  5393. 1024, "text/plain",
  5394. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5395. sink.write("hello", 5);
  5396. throw std::runtime_error("from the content provider");
  5397. });
  5398. });
  5399. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5400. res.set_content("ok", "text/plain");
  5401. });
  5402. auto port = svr.bind_to_any_port(HOST);
  5403. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5404. auto se = detail::scope_exit([&] {
  5405. svr.stop();
  5406. listen_thread.join();
  5407. ASSERT_FALSE(svr.is_running());
  5408. });
  5409. svr.wait_until_ready();
  5410. {
  5411. Client cli(HOST, port);
  5412. cli.set_read_timeout(5, 0);
  5413. EXPECT_FALSE(cli.Get("/throw"));
  5414. }
  5415. EXPECT_TRUE(svr.is_running());
  5416. EXPECT_EQ(1, reported.load());
  5417. {
  5418. Client cli(HOST, port);
  5419. auto res = cli.Get("/ok");
  5420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5421. EXPECT_EQ(StatusCode::OK_200, res->status);
  5422. EXPECT_EQ("ok", res->body);
  5423. }
  5424. }
  5425. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5426. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5427. // so the exception unwinds through the ws::WebSocket object on its way to
  5428. // the guard. None of the HTTP cases above cross that.
  5429. Server svr;
  5430. svr.new_task_queue = [] { return new ThreadPool(1); };
  5431. std::atomic<int> reported{0};
  5432. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5433. if (err == Error::UserCallbackException) { reported++; }
  5434. });
  5435. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5436. throw std::runtime_error("from the WebSocket handler");
  5437. });
  5438. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5439. res.set_content("ok", "text/plain");
  5440. });
  5441. auto port = svr.bind_to_any_port(HOST);
  5442. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5443. auto se = detail::scope_exit([&] {
  5444. svr.stop();
  5445. listen_thread.join();
  5446. ASSERT_FALSE(svr.is_running());
  5447. });
  5448. svr.wait_until_ready();
  5449. {
  5450. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5451. "/ws");
  5452. auto res = client.connect();
  5453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5454. // The server dropped the connection instead of dying.
  5455. std::string msg;
  5456. EXPECT_FALSE(client.read(msg));
  5457. client.close();
  5458. }
  5459. EXPECT_TRUE(svr.is_running());
  5460. EXPECT_EQ(1, reported.load());
  5461. {
  5462. Client cli(HOST, port);
  5463. auto res = cli.Get("/ok");
  5464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5465. EXPECT_EQ(StatusCode::OK_200, res->status);
  5466. EXPECT_EQ("ok", res->body);
  5467. }
  5468. }
  5469. #ifdef CPPHTTPLIB_SSL_ENABLED
  5470. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5471. // SSLServer::process_and_close_socket() is a separate overload with its own
  5472. // guard, so it is exercised on its own.
  5473. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5474. ASSERT_TRUE(svr.is_valid());
  5475. svr.new_task_queue = [] { return new ThreadPool(1); };
  5476. std::atomic<int> reported{0};
  5477. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5478. if (err == Error::UserCallbackException) { reported++; }
  5479. });
  5480. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5481. res.set_content_provider(
  5482. 1024, "text/plain",
  5483. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5484. sink.write("hello", 5);
  5485. throw std::runtime_error("from the content provider");
  5486. });
  5487. });
  5488. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5489. res.set_content("ok", "text/plain");
  5490. });
  5491. auto port = svr.bind_to_any_port(HOST);
  5492. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5493. auto se = detail::scope_exit([&] {
  5494. svr.stop();
  5495. listen_thread.join();
  5496. ASSERT_FALSE(svr.is_running());
  5497. });
  5498. svr.wait_until_ready();
  5499. {
  5500. SSLClient cli(HOST, port);
  5501. cli.enable_server_certificate_verification(false);
  5502. cli.set_read_timeout(5, 0);
  5503. EXPECT_FALSE(cli.Get("/throw"));
  5504. }
  5505. EXPECT_TRUE(svr.is_running());
  5506. EXPECT_EQ(1, reported.load());
  5507. {
  5508. SSLClient cli(HOST, port);
  5509. cli.enable_server_certificate_verification(false);
  5510. auto res = cli.Get("/ok");
  5511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5512. EXPECT_EQ(StatusCode::OK_200, res->status);
  5513. EXPECT_EQ("ok", res->body);
  5514. }
  5515. }
  5516. #endif
  5517. #endif
  5518. TEST(NoContentTest, ContentLength) {
  5519. Server svr;
  5520. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5521. res.status = StatusCode::NoContent_204;
  5522. });
  5523. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5524. auto se = detail::scope_exit([&] {
  5525. svr.stop();
  5526. thread.join();
  5527. ASSERT_FALSE(svr.is_running());
  5528. });
  5529. svr.wait_until_ready();
  5530. {
  5531. Client cli(HOST, PORT);
  5532. auto res = cli.Get("/hi");
  5533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5534. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5535. // RFC 9110 8.6: none in a 204 response
  5536. EXPECT_FALSE(res->has_header("Content-Length"));
  5537. }
  5538. }
  5539. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5540. Server svr;
  5541. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5542. res.set_header("Content-Length", "5");
  5543. res.set_content("hello world", "text/plain");
  5544. });
  5545. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5546. // A body that reads as the last chunk, were it taken as chunked
  5547. res.set_header("Transfer-Encoding", "chunked");
  5548. res.set_content("0\r\n\r\n", "text/plain");
  5549. });
  5550. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5551. res.set_header("Content-Length", "2");
  5552. res.set_content_provider(5, "text/plain",
  5553. [](size_t offset, size_t length, DataSink &sink) {
  5554. sink.write(&"hello"[offset], length);
  5555. return true;
  5556. });
  5557. });
  5558. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5559. res.set_header("Content-Length", "1234");
  5560. });
  5561. thread t = thread([&] { svr.listen(HOST, PORT); });
  5562. auto se = detail::scope_exit([&] {
  5563. svr.stop();
  5564. t.join();
  5565. ASSERT_FALSE(svr.is_running());
  5566. });
  5567. svr.wait_until_ready();
  5568. Client cli(HOST, PORT);
  5569. cli.set_read_timeout(1, 0);
  5570. auto expect_body = [&](const Result &res, const std::string &body) {
  5571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5572. EXPECT_EQ(body, res->body);
  5573. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5574. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5575. };
  5576. Headers identity{{"Accept-Encoding", ""}};
  5577. expect_body(cli.Get("/body", identity), "hello world");
  5578. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5579. expect_body(cli.Get("/body",
  5580. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5581. "he");
  5582. expect_body(cli.Get("/provider", identity), "hello");
  5583. expect_body(cli.Get("/empty", identity), "");
  5584. // A HEAD response may give the length of the body a GET would get.
  5585. auto res = cli.Head("/empty");
  5586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5587. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5588. }
  5589. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5590. Server svr;
  5591. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5592. res.set_content("short", "text/plain");
  5593. });
  5594. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5595. res.body += " with a footer";
  5596. res.set_header("Transfer-Encoding", "chunked");
  5597. });
  5598. thread t = thread([&] { svr.listen(HOST, PORT); });
  5599. auto se = detail::scope_exit([&] {
  5600. svr.stop();
  5601. t.join();
  5602. ASSERT_FALSE(svr.is_running());
  5603. });
  5604. svr.wait_until_ready();
  5605. Client cli(HOST, PORT);
  5606. cli.set_read_timeout(1, 0);
  5607. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5609. EXPECT_EQ("short with a footer", res->body);
  5610. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5611. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5612. }
  5613. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5614. Server svr;
  5615. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5616. res.set_header("Content-Length", "3");
  5617. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5618. sink.write("abc", 3);
  5619. sink.done();
  5620. return true;
  5621. });
  5622. });
  5623. thread t = thread([&] { svr.listen(HOST, PORT); });
  5624. auto se = detail::scope_exit([&] {
  5625. svr.stop();
  5626. t.join();
  5627. ASSERT_FALSE(svr.is_running());
  5628. });
  5629. svr.wait_until_ready();
  5630. Client cli(HOST, PORT);
  5631. cli.set_keep_alive(true);
  5632. auto res = cli.Get("/");
  5633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5634. EXPECT_EQ("abc", res->body);
  5635. EXPECT_FALSE(res->has_header("Content-Length"));
  5636. EXPECT_EQ("close", res->get_header_value("Connection"));
  5637. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5638. // No body to delimit
  5639. auto head = cli.Head("/");
  5640. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5641. EXPECT_FALSE(head->has_header("Connection"));
  5642. }
  5643. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5644. #ifdef CPPHTTPLIB_SSL_ENABLED
  5645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5646. ASSERT_TRUE(svr.is_valid());
  5647. #else
  5648. Server svr;
  5649. #endif
  5650. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5651. if (req.path == "/routing_handler") {
  5652. res.set_header("PRE_ROUTING", "on");
  5653. res.set_content("Routing Handler", "text/plain");
  5654. return httplib::Server::HandlerResponse::Handled;
  5655. }
  5656. return httplib::Server::HandlerResponse::Unhandled;
  5657. });
  5658. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5659. res.set_content("Error", "text/html");
  5660. });
  5661. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5662. if (req.path == "/routing_handler") {
  5663. res.set_header("POST_ROUTING", "on");
  5664. }
  5665. });
  5666. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5667. res.set_content("Hello World!\n", "text/plain");
  5668. });
  5669. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5670. auto se = detail::scope_exit([&] {
  5671. svr.stop();
  5672. thread.join();
  5673. ASSERT_FALSE(svr.is_running());
  5674. });
  5675. svr.wait_until_ready();
  5676. {
  5677. #ifdef CPPHTTPLIB_SSL_ENABLED
  5678. SSLClient cli(HOST, PORT);
  5679. cli.enable_server_certificate_verification(false);
  5680. #else
  5681. Client cli(HOST, PORT);
  5682. #endif
  5683. auto res = cli.Get("/routing_handler");
  5684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5685. EXPECT_EQ(StatusCode::OK_200, res->status);
  5686. EXPECT_EQ("Routing Handler", res->body);
  5687. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5688. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5689. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5690. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5691. }
  5692. {
  5693. #ifdef CPPHTTPLIB_SSL_ENABLED
  5694. SSLClient cli(HOST, PORT);
  5695. cli.enable_server_certificate_verification(false);
  5696. #else
  5697. Client cli(HOST, PORT);
  5698. #endif
  5699. auto res = cli.Get("/hi");
  5700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5701. EXPECT_EQ(StatusCode::OK_200, res->status);
  5702. EXPECT_EQ("Hello World!\n", res->body);
  5703. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5704. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5705. }
  5706. {
  5707. #ifdef CPPHTTPLIB_SSL_ENABLED
  5708. SSLClient cli(HOST, PORT);
  5709. cli.enable_server_certificate_verification(false);
  5710. #else
  5711. Client cli(HOST, PORT);
  5712. #endif
  5713. auto res = cli.Get("/aaa");
  5714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5715. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5716. EXPECT_EQ("Error", res->body);
  5717. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5718. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5719. }
  5720. }
  5721. TEST(RequestHandlerTest, PreRequestHandler) {
  5722. auto route_path = "/user/:user";
  5723. Server svr;
  5724. svr.Get("/hi", [](const Request &, Response &res) {
  5725. res.set_content("hi", "text/plain");
  5726. });
  5727. svr.Get(route_path, [](const Request &req, Response &res) {
  5728. res.set_content(req.path_params.at("user"), "text/plain");
  5729. });
  5730. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5731. if (req.matched_route == route_path) {
  5732. auto user = req.path_params.at("user");
  5733. if (user != "john") {
  5734. res.status = StatusCode::Forbidden_403;
  5735. res.set_content("error", "text/html");
  5736. return Server::HandlerResponse::Handled;
  5737. }
  5738. }
  5739. return Server::HandlerResponse::Unhandled;
  5740. });
  5741. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5742. auto se = detail::scope_exit([&] {
  5743. svr.stop();
  5744. thread.join();
  5745. ASSERT_FALSE(svr.is_running());
  5746. });
  5747. svr.wait_until_ready();
  5748. Client cli(HOST, PORT);
  5749. {
  5750. auto res = cli.Get("/hi");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("hi", res->body);
  5754. }
  5755. {
  5756. auto res = cli.Get("/user/john");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. EXPECT_EQ(StatusCode::OK_200, res->status);
  5759. EXPECT_EQ("john", res->body);
  5760. }
  5761. {
  5762. auto res = cli.Get("/user/invalid-user");
  5763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5764. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5765. EXPECT_EQ("error", res->body);
  5766. }
  5767. }
  5768. // The pre-request handler must run before the request body is read, so a
  5769. // rejected request never forces the server to buffer a (potentially large)
  5770. // body. Here the posted body is larger than the payload limit: if the body
  5771. // were read first the server would answer 413, but because the pre-request
  5772. // handler runs first it answers 403 and the body is never read.
  5773. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5774. Server svr;
  5775. svr.set_payload_max_length(8);
  5776. auto handler_ran = false;
  5777. svr.Post("/reject", [&](const Request &req, Response &res) {
  5778. handler_ran = true;
  5779. res.set_content(req.body, "text/plain");
  5780. });
  5781. svr.Post("/accept", [](const Request &req, Response &res) {
  5782. res.set_content(req.body, "text/plain");
  5783. });
  5784. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5785. if (req.matched_route == "/reject") {
  5786. res.status = StatusCode::Forbidden_403;
  5787. res.set_content("denied", "text/plain");
  5788. return Server::HandlerResponse::Handled;
  5789. }
  5790. return Server::HandlerResponse::Unhandled;
  5791. });
  5792. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5793. auto se = detail::scope_exit([&] {
  5794. svr.stop();
  5795. thread.join();
  5796. ASSERT_FALSE(svr.is_running());
  5797. });
  5798. svr.wait_until_ready();
  5799. Client cli(HOST, PORT);
  5800. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5801. // rejects with 403 before the body is read, so 413 is never reached.
  5802. {
  5803. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5805. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5806. EXPECT_EQ("denied", res->body);
  5807. EXPECT_FALSE(handler_ran);
  5808. }
  5809. // An approved route still reads the body and enforces the payload limit.
  5810. {
  5811. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5813. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5814. }
  5815. }
  5816. TEST(UserDataTest, BasicOperations) {
  5817. httplib::UserData ud;
  5818. // Initially empty
  5819. EXPECT_FALSE(ud.has("key"));
  5820. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5821. // set and get
  5822. ud.set("key", 42);
  5823. EXPECT_TRUE(ud.has("key"));
  5824. auto *p = ud.get<int>("key");
  5825. ASSERT_NE(nullptr, p);
  5826. EXPECT_EQ(42, *p);
  5827. // Type mismatch → nullptr
  5828. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5829. // Overwrite with different type
  5830. ud.set("key", std::string("hello"));
  5831. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5832. auto *s = ud.get<std::string>("key");
  5833. ASSERT_NE(nullptr, s);
  5834. EXPECT_EQ("hello", *s);
  5835. // erase
  5836. ud.erase("key");
  5837. EXPECT_FALSE(ud.has("key"));
  5838. // clear
  5839. ud.set("a", 1);
  5840. ud.set("b", 2);
  5841. ud.clear();
  5842. EXPECT_FALSE(ud.has("a"));
  5843. EXPECT_FALSE(ud.has("b"));
  5844. }
  5845. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5846. struct AuthCtx {
  5847. std::string user_id;
  5848. };
  5849. Server svr;
  5850. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5851. res.user_data.set("auth", AuthCtx{"alice"});
  5852. return Server::HandlerResponse::Unhandled;
  5853. });
  5854. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5855. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5856. ASSERT_NE(nullptr, ctx);
  5857. res.set_content("Hello " + ctx->user_id, "text/plain");
  5858. });
  5859. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5860. auto se = detail::scope_exit([&] {
  5861. svr.stop();
  5862. thread.join();
  5863. ASSERT_FALSE(svr.is_running());
  5864. });
  5865. svr.wait_until_ready();
  5866. Client cli(HOST, PORT);
  5867. auto res = cli.Get("/me");
  5868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5869. EXPECT_EQ(StatusCode::OK_200, res->status);
  5870. EXPECT_EQ("Hello alice", res->body);
  5871. }
  5872. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5873. struct RoleCtx {
  5874. std::string role;
  5875. };
  5876. Server svr;
  5877. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5878. res.user_data.set("role", RoleCtx{"admin"});
  5879. return Server::HandlerResponse::Unhandled;
  5880. });
  5881. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5882. auto *ctx = res.user_data.get<RoleCtx>("role");
  5883. ASSERT_NE(nullptr, ctx);
  5884. res.set_content(ctx->role, "text/plain");
  5885. });
  5886. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5887. auto se = detail::scope_exit([&] {
  5888. svr.stop();
  5889. thread.join();
  5890. ASSERT_FALSE(svr.is_running());
  5891. });
  5892. svr.wait_until_ready();
  5893. Client cli(HOST, PORT);
  5894. auto res = cli.Get("/role");
  5895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5896. EXPECT_EQ(StatusCode::OK_200, res->status);
  5897. EXPECT_EQ("admin", res->body);
  5898. }
  5899. TEST(InvalidFormatTest, StatusCode) {
  5900. Server svr;
  5901. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5902. res.set_content("Hello World!\n", "text/plain");
  5903. res.status = 9999; // Status should be a three-digit code...
  5904. });
  5905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5906. auto se = detail::scope_exit([&] {
  5907. svr.stop();
  5908. thread.join();
  5909. ASSERT_FALSE(svr.is_running());
  5910. });
  5911. svr.wait_until_ready();
  5912. {
  5913. Client cli(HOST, PORT);
  5914. auto res = cli.Get("/hi");
  5915. ASSERT_FALSE(res);
  5916. }
  5917. }
  5918. TEST(URLFragmentTest, WithFragment) {
  5919. Server svr;
  5920. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5921. EXPECT_TRUE(req.target == "/hi");
  5922. });
  5923. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5924. auto se = detail::scope_exit([&] {
  5925. svr.stop();
  5926. thread.join();
  5927. ASSERT_FALSE(svr.is_running());
  5928. });
  5929. svr.wait_until_ready();
  5930. {
  5931. Client cli(HOST, PORT);
  5932. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5933. EXPECT_TRUE(res);
  5934. EXPECT_EQ(StatusCode::OK_200, res->status);
  5935. res = cli.Get("/hi%23key1=val1=key2=val2");
  5936. EXPECT_TRUE(res);
  5937. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5938. }
  5939. }
  5940. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5941. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5942. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5943. Server svr;
  5944. std::vector<std::string> targets;
  5945. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5946. targets.push_back(req.target);
  5947. });
  5948. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5949. auto se = detail::scope_exit([&] {
  5950. svr.stop();
  5951. thread.join();
  5952. ASSERT_FALSE(svr.is_running());
  5953. });
  5954. svr.wait_until_ready();
  5955. Client cli(HOST, PORT);
  5956. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5957. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5958. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5959. // A '?' after the '#' belongs to the fragment, not to the query.
  5960. Request req;
  5961. req.method = "GET";
  5962. req.path = "/hi#f?x=1";
  5963. req.params.emplace("a", "1");
  5964. Response res;
  5965. auto error = Error::Success;
  5966. EXPECT_TRUE(cli.send(req, res, error));
  5967. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5968. "/hi?a=1"}),
  5969. targets);
  5970. }
  5971. TEST(HeaderWriter, SetHeaderWriter) {
  5972. Server svr;
  5973. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5974. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5975. return detail::write_headers(strm, hdrs);
  5976. });
  5977. svr.Get("/hi", [](const Request &req, Response &res) {
  5978. auto it = req.headers.find("CustomClientHeader");
  5979. EXPECT_TRUE(it != req.headers.end());
  5980. EXPECT_EQ(it->second, "CustomClientValue");
  5981. res.set_content("Hello World!\n", "text/plain");
  5982. });
  5983. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5984. auto se = detail::scope_exit([&] {
  5985. svr.stop();
  5986. thread.join();
  5987. ASSERT_FALSE(svr.is_running());
  5988. });
  5989. svr.wait_until_ready();
  5990. {
  5991. Client cli(HOST, PORT);
  5992. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5993. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5994. return detail::write_headers(strm, hdrs);
  5995. });
  5996. auto res = cli.Get("/hi");
  5997. EXPECT_TRUE(res);
  5998. EXPECT_EQ(StatusCode::OK_200, res->status);
  5999. auto it = res->headers.find("CustomServerHeader");
  6000. EXPECT_TRUE(it != res->headers.end());
  6001. EXPECT_EQ(it->second, "CustomServerValue");
  6002. }
  6003. }
  6004. class ServerTest : public ::testing::Test {
  6005. protected:
  6006. ServerTest()
  6007. : cli_(HOST, PORT)
  6008. #ifdef CPPHTTPLIB_SSL_ENABLED
  6009. ,
  6010. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6011. #endif
  6012. {
  6013. #ifdef CPPHTTPLIB_SSL_ENABLED
  6014. cli_.enable_server_certificate_verification(false);
  6015. #endif
  6016. // Allow LARGE_DATA (100MB) responses
  6017. cli_.set_payload_max_length(200 * 1024 * 1024);
  6018. }
  6019. virtual void SetUp() {
  6020. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  6021. svr_.set_payload_max_length(200 * 1024 * 1024);
  6022. svr_.set_mount_point("/", "./www");
  6023. svr_.set_mount_point("/mount", "./www2");
  6024. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  6025. svr_.Get("/hi",
  6026. [&](const Request & /*req*/, Response &res) {
  6027. res.set_content("Hello World!", "text/plain");
  6028. })
  6029. .Get("/file_content",
  6030. [&](const Request & /*req*/, Response &res) {
  6031. res.set_file_content("./www/dir/test.html");
  6032. })
  6033. .Get("/file_content_with_content_type",
  6034. [&](const Request & /*req*/, Response &res) {
  6035. res.set_file_content("./www/file", "text/plain");
  6036. })
  6037. .Get("/invalid_file_content",
  6038. [&](const Request & /*req*/, Response &res) {
  6039. res.set_file_content("./www/dir/invalid_file_path");
  6040. })
  6041. .Get("/http_response_splitting",
  6042. [&](const Request & /*req*/, Response &res) {
  6043. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6044. EXPECT_EQ(0U, res.headers.size());
  6045. EXPECT_FALSE(res.has_header("a"));
  6046. res.set_header("a", "1\nSet-Cookie: a=1");
  6047. EXPECT_EQ(0U, res.headers.size());
  6048. EXPECT_FALSE(res.has_header("a"));
  6049. res.set_header("a", "1\rSet-Cookie: a=1");
  6050. EXPECT_EQ(0U, res.headers.size());
  6051. EXPECT_FALSE(res.has_header("a"));
  6052. res.set_header("a\r\nb", "0");
  6053. EXPECT_EQ(0U, res.headers.size());
  6054. EXPECT_FALSE(res.has_header("a"));
  6055. res.set_header("a\rb", "0");
  6056. EXPECT_EQ(0U, res.headers.size());
  6057. EXPECT_FALSE(res.has_header("a"));
  6058. res.set_header("a\nb", "0");
  6059. EXPECT_EQ(0U, res.headers.size());
  6060. EXPECT_FALSE(res.has_header("a"));
  6061. res.set_redirect("1\r\nSet-Cookie: a=1");
  6062. EXPECT_EQ(0U, res.headers.size());
  6063. EXPECT_FALSE(res.has_header("Location"));
  6064. })
  6065. .Get("/slow",
  6066. [&](const Request & /*req*/, Response &res) {
  6067. std::this_thread::sleep_for(std::chrono::seconds(4));
  6068. res.set_content("slow", "text/plain");
  6069. })
  6070. #if 0
  6071. .Post("/slowpost",
  6072. [&](const Request & /*req*/, Response &res) {
  6073. std::this_thread::sleep_for(std::chrono::seconds(2));
  6074. res.set_content("slow", "text/plain");
  6075. })
  6076. #endif
  6077. .Get("/remote_addr",
  6078. [&](const Request &req, Response &res) {
  6079. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6080. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6081. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6082. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6083. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6084. #endif
  6085. res.set_content(req.remote_addr, "text/plain");
  6086. })
  6087. .Get("/local_addr",
  6088. [&](const Request &req, Response &res) {
  6089. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6090. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6091. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6092. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6093. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6094. #endif
  6095. auto local_addr = req.local_addr;
  6096. auto local_port = std::to_string(req.local_port);
  6097. res.set_content(local_addr.append(":").append(local_port),
  6098. "text/plain");
  6099. })
  6100. .Get("/endwith%",
  6101. [&](const Request & /*req*/, Response &res) {
  6102. res.set_content("Hello World!", "text/plain");
  6103. })
  6104. .Get("/a\\+\\+b",
  6105. [&](const Request &req, Response &res) {
  6106. ASSERT_TRUE(req.has_param("a +b"));
  6107. auto val = req.get_param_value("a +b");
  6108. res.set_content(val, "text/plain");
  6109. })
  6110. .Get("/", [&](const Request & /*req*/,
  6111. Response &res) { res.set_redirect("/hi"); })
  6112. .Post("/1",
  6113. [](const Request & /*req*/, Response &res) {
  6114. res.set_redirect("/2", StatusCode::SeeOther_303);
  6115. })
  6116. .Get("/2",
  6117. [](const Request & /*req*/, Response &res) {
  6118. res.set_content("redirected.", "text/plain");
  6119. res.status = StatusCode::OK_200;
  6120. })
  6121. .Post("/person",
  6122. [&](const Request &req, Response &res) {
  6123. if (req.has_param("name") && req.has_param("note")) {
  6124. persons_[req.get_param_value("name")] =
  6125. req.get_param_value("note");
  6126. } else {
  6127. res.status = StatusCode::BadRequest_400;
  6128. }
  6129. })
  6130. .Put("/person",
  6131. [&](const Request &req, Response &res) {
  6132. if (req.has_param("name") && req.has_param("note")) {
  6133. persons_[req.get_param_value("name")] =
  6134. req.get_param_value("note");
  6135. } else {
  6136. res.status = StatusCode::BadRequest_400;
  6137. }
  6138. })
  6139. .Get("/person/(.*)",
  6140. [&](const Request &req, Response &res) {
  6141. string name = req.matches[1];
  6142. if (persons_.find(name) != persons_.end()) {
  6143. auto note = persons_[name];
  6144. res.set_content(note, "text/plain");
  6145. } else {
  6146. res.status = StatusCode::NotFound_404;
  6147. }
  6148. })
  6149. .Delete("/person",
  6150. [&](const Request &req, Response &res) {
  6151. if (req.has_param("name")) {
  6152. string name = req.get_param_value("name");
  6153. if (persons_.find(name) != persons_.end()) {
  6154. persons_.erase(name);
  6155. res.set_content("DELETED", "text/plain");
  6156. } else {
  6157. res.status = StatusCode::NotFound_404;
  6158. }
  6159. } else {
  6160. res.status = StatusCode::BadRequest_400;
  6161. }
  6162. })
  6163. .Post("/x-www-form-urlencoded-json",
  6164. [&](const Request &req, Response &res) {
  6165. auto json = req.get_param_value("json");
  6166. ASSERT_EQ(JSON_DATA, json);
  6167. res.set_content(json, "appliation/json");
  6168. res.status = StatusCode::OK_200;
  6169. })
  6170. .Get("/streamed-chunked",
  6171. [&](const Request & /*req*/, Response &res) {
  6172. res.set_chunked_content_provider(
  6173. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6174. sink.os << "123";
  6175. sink.os << "456";
  6176. sink.os << "789";
  6177. sink.done();
  6178. return true;
  6179. });
  6180. })
  6181. .Get("/streamed-chunked-with-prohibited-trailer",
  6182. [&](const Request & /*req*/, Response &res) {
  6183. auto i = new int(0);
  6184. // Declare both a prohibited trailer (Content-Length) and an
  6185. // allowed one
  6186. res.set_header("Trailer", "Content-Length, X-Allowed");
  6187. res.set_chunked_content_provider(
  6188. "text/plain",
  6189. [i](size_t /*offset*/, DataSink &sink) {
  6190. switch (*i) {
  6191. case 0: sink.os << "123"; break;
  6192. case 1: sink.os << "456"; break;
  6193. case 2: sink.os << "789"; break;
  6194. case 3: {
  6195. sink.done_with_trailer(
  6196. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6197. } break;
  6198. }
  6199. (*i)++;
  6200. return true;
  6201. },
  6202. [i](bool success) {
  6203. EXPECT_TRUE(success);
  6204. delete i;
  6205. });
  6206. })
  6207. .Get("/streamed-chunked2",
  6208. [&](const Request & /*req*/, Response &res) {
  6209. auto i = new int(0);
  6210. res.set_chunked_content_provider(
  6211. "text/plain",
  6212. [i](size_t /*offset*/, DataSink &sink) {
  6213. switch (*i) {
  6214. case 0: sink.os << "123"; break;
  6215. case 1: sink.os << "456"; break;
  6216. case 2: sink.os << "789"; break;
  6217. case 3: sink.done(); break;
  6218. }
  6219. (*i)++;
  6220. return true;
  6221. },
  6222. [i](bool success) {
  6223. EXPECT_TRUE(success);
  6224. delete i;
  6225. });
  6226. })
  6227. .Get("/streamed-chunked-with-trailer",
  6228. [&](const Request & /*req*/, Response &res) {
  6229. auto i = new int(0);
  6230. res.set_header("Trailer", "Dummy1, Dummy2");
  6231. res.set_chunked_content_provider(
  6232. "text/plain",
  6233. [i](size_t /*offset*/, DataSink &sink) {
  6234. switch (*i) {
  6235. case 0: sink.os << "123"; break;
  6236. case 1: sink.os << "456"; break;
  6237. case 2: sink.os << "789"; break;
  6238. case 3: {
  6239. sink.done_with_trailer(
  6240. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6241. } break;
  6242. }
  6243. (*i)++;
  6244. return true;
  6245. },
  6246. [i](bool success) {
  6247. EXPECT_TRUE(success);
  6248. delete i;
  6249. });
  6250. })
  6251. .Get("/streamed",
  6252. [&](const Request & /*req*/, Response &res) {
  6253. res.set_content_provider(
  6254. 6, "text/plain",
  6255. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6256. sink.os << (offset < 3 ? "a" : "b");
  6257. return true;
  6258. });
  6259. })
  6260. .Get("/streamed-without-length",
  6261. [&](const Request & /*req*/, Response &res) {
  6262. auto data = new std::string("abcdefg");
  6263. res.set_content_provider(
  6264. "text/plain",
  6265. [data](size_t offset, DataSink &sink) {
  6266. if (offset < data->size()) {
  6267. sink.os << data->substr(offset);
  6268. }
  6269. sink.done();
  6270. return true;
  6271. },
  6272. [data](bool success) {
  6273. EXPECT_TRUE(success);
  6274. delete data;
  6275. });
  6276. })
  6277. .Get("/streamed-with-range",
  6278. [&](const Request &req, Response &res) {
  6279. auto data = new std::string("abcdefg");
  6280. // An explicit status keeps the server from picking the 206 it
  6281. // would otherwise choose for a ranged request, so the response
  6282. // is not a partial representation.
  6283. auto status = req.get_param_value("status");
  6284. if (status == "200") {
  6285. res.status = StatusCode::OK_200;
  6286. } else if (status == "403") {
  6287. res.status = StatusCode::Forbidden_403;
  6288. }
  6289. res.set_content_provider(
  6290. data->size(), "text/plain",
  6291. [data](size_t offset, size_t length, DataSink &sink) {
  6292. size_t DATA_CHUNK_SIZE = 4;
  6293. const auto &d = *data;
  6294. auto out_len =
  6295. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6296. auto ret =
  6297. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6298. EXPECT_TRUE(ret);
  6299. return true;
  6300. },
  6301. [data, &req](bool success) {
  6302. EXPECT_EQ(success, !req.has_param("error"));
  6303. delete data;
  6304. });
  6305. })
  6306. .Get("/streamed-cancel",
  6307. [&](const Request & /*req*/, Response &res) {
  6308. res.set_content_provider(
  6309. size_t(-1), "text/plain",
  6310. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6311. sink.os << "data_chunk";
  6312. return true;
  6313. });
  6314. })
  6315. .Get("/regex-with-delimiter",
  6316. [&](const Request &req, Response & /*res*/) {
  6317. ASSERT_TRUE(req.has_param("key"));
  6318. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6319. })
  6320. .Get("/with-range",
  6321. [&](const Request & /*req*/, Response &res) {
  6322. res.set_content("abcdefg", "text/plain");
  6323. })
  6324. .Get("/test-start-time",
  6325. [&](const Request &req, Response & /*res*/) {
  6326. EXPECT_NE(req.start_time_,
  6327. std::chrono::steady_clock::time_point::min());
  6328. })
  6329. .Get("/with-range-customized-response",
  6330. [&](const Request & /*req*/, Response &res) {
  6331. res.status = StatusCode::BadRequest_400;
  6332. res.set_content(JSON_DATA, "application/json");
  6333. })
  6334. .Post("/chunked",
  6335. [&](const Request &req, Response & /*res*/) {
  6336. EXPECT_EQ(req.body, "dechunked post body");
  6337. })
  6338. .Post("/large-chunked",
  6339. [&](const Request &req, Response & /*res*/) {
  6340. std::string expected(6 * 30 * 1024u, 'a');
  6341. EXPECT_EQ(req.body, expected);
  6342. })
  6343. .Post("/multipart",
  6344. [&](const Request &req, Response & /*res*/) {
  6345. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6346. req.form.get_field_count("text2") +
  6347. req.form.get_field_count("file3") +
  6348. req.form.get_field_count("file4"));
  6349. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6350. req.form.get_file_count("file2"));
  6351. ASSERT_TRUE(!req.form.has_file("???"));
  6352. ASSERT_TRUE(!req.form.has_field("???"));
  6353. ASSERT_TRUE(req.body.empty());
  6354. {
  6355. const auto &text = req.form.get_field("text1");
  6356. EXPECT_EQ("text default", text);
  6357. }
  6358. {
  6359. const auto &text = req.form.get_field("text2");
  6360. EXPECT_EQ("aωb", text);
  6361. }
  6362. {
  6363. const auto &file = req.form.get_file("file1");
  6364. EXPECT_EQ("hello.txt", file.filename);
  6365. EXPECT_EQ("text/plain", file.content_type);
  6366. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6367. }
  6368. {
  6369. const auto &file = req.form.get_file("file2");
  6370. EXPECT_EQ("world.json", file.filename);
  6371. EXPECT_EQ("application/json", file.content_type);
  6372. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6373. }
  6374. {
  6375. const auto &text = req.form.get_field("file3");
  6376. EXPECT_EQ(0u, text.size());
  6377. }
  6378. {
  6379. const auto &text = req.form.get_field("file4");
  6380. EXPECT_EQ(0u, text.size());
  6381. }
  6382. })
  6383. .Post("/multipart/multi_file_values",
  6384. [&](const Request &req, Response & /*res*/) {
  6385. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6386. req.form.get_field_count("multi_text1"));
  6387. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6388. ASSERT_TRUE(!req.form.has_file("???"));
  6389. ASSERT_TRUE(!req.form.has_field("???"));
  6390. ASSERT_TRUE(req.body.empty());
  6391. {
  6392. const auto &text = req.form.get_field("text");
  6393. EXPECT_EQ("default text", text);
  6394. }
  6395. {
  6396. const auto &text1_values = req.form.get_fields("multi_text1");
  6397. EXPECT_EQ(2u, text1_values.size());
  6398. EXPECT_EQ("aaaaa", text1_values[0]);
  6399. EXPECT_EQ("bbbbb", text1_values[1]);
  6400. }
  6401. {
  6402. const auto &file1_values = req.form.get_files("multi_file1");
  6403. EXPECT_EQ(2u, file1_values.size());
  6404. auto file1 = file1_values[0];
  6405. EXPECT_EQ(file1.filename, "hello.txt");
  6406. EXPECT_EQ(file1.content_type, "text/plain");
  6407. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6408. auto file2 = file1_values[1];
  6409. EXPECT_EQ(file2.filename, "world.json");
  6410. EXPECT_EQ(file2.content_type, "application/json");
  6411. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6412. }
  6413. })
  6414. .Post("/empty",
  6415. [&](const Request &req, Response &res) {
  6416. EXPECT_EQ(req.body, "");
  6417. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6418. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6419. res.set_content("empty", "text/plain");
  6420. })
  6421. .Post("/empty-no-content-type",
  6422. [&](const Request &req, Response &res) {
  6423. EXPECT_EQ(req.body, "");
  6424. EXPECT_FALSE(req.has_header("Content-Type"));
  6425. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6426. res.set_content("empty-no-content-type", "text/plain");
  6427. })
  6428. .Post("/path-only",
  6429. [&](const Request &req, Response &res) {
  6430. EXPECT_EQ(req.body, "");
  6431. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6432. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6433. res.set_content("path-only", "text/plain");
  6434. })
  6435. .Post("/path-headers-only",
  6436. [&](const Request &req, Response &res) {
  6437. EXPECT_EQ(req.body, "");
  6438. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6439. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6440. EXPECT_EQ("world", req.get_header_value("hello"));
  6441. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6442. res.set_content("path-headers-only", "text/plain");
  6443. })
  6444. .Post("/post-large",
  6445. [&](const Request &req, Response &res) {
  6446. EXPECT_EQ(req.body, LARGE_DATA);
  6447. res.set_content(req.body, "text/plain");
  6448. })
  6449. .Post("/post-loopback",
  6450. [&](const Request &, Response &res,
  6451. ContentReader const &content_reader) {
  6452. std::string body;
  6453. content_reader([&](const char *data, size_t data_length) {
  6454. body.append(data, data_length);
  6455. return true;
  6456. });
  6457. res.set_content(body, "text/plain");
  6458. })
  6459. .Put("/put-loopback",
  6460. [&](const Request &, Response &res,
  6461. ContentReader const &content_reader) {
  6462. std::string body;
  6463. content_reader([&](const char *data, size_t data_length) {
  6464. body.append(data, data_length);
  6465. return true;
  6466. });
  6467. res.set_content(body, "text/plain");
  6468. })
  6469. .Patch("/patch-loopback",
  6470. [&](const Request &, Response &res,
  6471. ContentReader const &content_reader) {
  6472. std::string body;
  6473. content_reader([&](const char *data, size_t data_length) {
  6474. body.append(data, data_length);
  6475. return true;
  6476. });
  6477. res.set_content(body, "text/plain");
  6478. })
  6479. .Put("/empty-no-content-type",
  6480. [&](const Request &req, Response &res) {
  6481. EXPECT_EQ(req.body, "");
  6482. EXPECT_FALSE(req.has_header("Content-Type"));
  6483. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6484. res.set_content("empty-no-content-type", "text/plain");
  6485. })
  6486. .Put("/put",
  6487. [&](const Request &req, Response &res) {
  6488. EXPECT_EQ(req.body, "PUT");
  6489. res.set_content(req.body, "text/plain");
  6490. })
  6491. .Put("/put-large",
  6492. [&](const Request &req, Response &res) {
  6493. EXPECT_EQ(req.body, LARGE_DATA);
  6494. res.set_content(req.body, "text/plain");
  6495. })
  6496. .Patch("/patch",
  6497. [&](const Request &req, Response &res) {
  6498. EXPECT_EQ(req.body, "PATCH");
  6499. res.set_content(req.body, "text/plain");
  6500. })
  6501. .Delete("/delete",
  6502. [&](const Request & /*req*/, Response &res) {
  6503. res.set_content("DELETE", "text/plain");
  6504. })
  6505. .Delete("/delete-body",
  6506. [&](const Request &req, Response &res) {
  6507. EXPECT_EQ(req.body, "content");
  6508. res.set_content(req.body, "text/plain");
  6509. })
  6510. .Options(R"(\*)",
  6511. [&](const Request & /*req*/, Response &res) {
  6512. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6513. })
  6514. .CustomRoute("PROPFIND", "/dav/:id",
  6515. [&](const Request &req, Response &res) {
  6516. res.set_header("x-body-size",
  6517. std::to_string(req.body.size()));
  6518. res.set_header("x-matched-route", req.matched_route);
  6519. res.set_header("x-dav-id", req.path_params.at("id"));
  6520. res.status = StatusCode::MultiStatus_207;
  6521. res.set_content(req.body, "application/xml");
  6522. })
  6523. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6524. [&](const Request &req, Response &res) {
  6525. res.set_header("x-dav-match", req.matches[1]);
  6526. res.status = StatusCode::MultiStatus_207;
  6527. })
  6528. .CustomRoute("MKCOL", "/dav-mkcol",
  6529. [&](const Request &req, Response &res) {
  6530. EXPECT_TRUE(req.body.empty());
  6531. res.status = StatusCode::Created_201;
  6532. })
  6533. .CustomRoute(
  6534. "REPORT", "/dav-report",
  6535. [&](const Request & /*req*/, Response &res,
  6536. const ContentReader &content_reader) {
  6537. std::string body;
  6538. content_reader([&](const char *data, size_t data_length) {
  6539. body.append(data, data_length);
  6540. return true;
  6541. });
  6542. res.set_header("x-body-size", std::to_string(body.size()));
  6543. res.status = StatusCode::MultiStatus_207;
  6544. res.set_content(body, "application/xml");
  6545. })
  6546. .Get("/request-target",
  6547. [&](const Request &req, Response & /*res*/) {
  6548. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6549. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6550. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6551. })
  6552. .Get("/long-query-value",
  6553. [&](const Request &req, Response & /*res*/) {
  6554. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6555. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6556. })
  6557. .Get("/too-long-query-value",
  6558. [&](const Request &req, Response & /*res*/) {
  6559. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6560. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6561. })
  6562. .Get("/array-param",
  6563. [&](const Request &req, Response & /*res*/) {
  6564. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6565. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6566. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6567. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6568. })
  6569. .Get("/array-param-values",
  6570. [&](const Request &req, Response & /*res*/) {
  6571. auto values = req.get_param_values("array");
  6572. EXPECT_EQ(3u, values.size());
  6573. EXPECT_EQ("value1", values[0]);
  6574. EXPECT_EQ("value2", values[1]);
  6575. EXPECT_EQ("value3", values[2]);
  6576. auto empty = req.get_param_values("nonexistent");
  6577. EXPECT_TRUE(empty.empty());
  6578. })
  6579. .Post("/validate-no-multiple-headers",
  6580. [&](const Request &req, Response & /*res*/) {
  6581. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6582. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6583. })
  6584. .Post("/content_receiver",
  6585. [&](const Request &req, Response &res,
  6586. const ContentReader &content_reader) {
  6587. if (req.is_multipart_form_data()) {
  6588. std::vector<FormData> items;
  6589. content_reader(
  6590. [&](const FormData &file) {
  6591. items.push_back(file);
  6592. return true;
  6593. },
  6594. [&](const char *data, size_t data_length) {
  6595. items.back().content.append(data, data_length);
  6596. return true;
  6597. });
  6598. EXPECT_EQ(5u, items.size());
  6599. {
  6600. const auto &file = get_file_value(items, "text1");
  6601. EXPECT_TRUE(file.filename.empty());
  6602. EXPECT_EQ("text default", file.content);
  6603. }
  6604. {
  6605. const auto &file = get_file_value(items, "text2");
  6606. EXPECT_TRUE(file.filename.empty());
  6607. EXPECT_EQ("aωb", file.content);
  6608. }
  6609. {
  6610. const auto &file = get_file_value(items, "file1");
  6611. EXPECT_EQ("hello.txt", file.filename);
  6612. EXPECT_EQ("text/plain", file.content_type);
  6613. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6614. }
  6615. {
  6616. const auto &file = get_file_value(items, "file2");
  6617. EXPECT_EQ("world.json", file.filename);
  6618. EXPECT_EQ("application/json", file.content_type);
  6619. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6620. }
  6621. {
  6622. const auto &file = get_file_value(items, "file3");
  6623. EXPECT_TRUE(file.filename.empty());
  6624. EXPECT_EQ("application/octet-stream", file.content_type);
  6625. EXPECT_EQ(0u, file.content.size());
  6626. }
  6627. } else {
  6628. std::string body;
  6629. content_reader([&](const char *data, size_t data_length) {
  6630. EXPECT_EQ(7U, data_length);
  6631. body.append(data, data_length);
  6632. return true;
  6633. });
  6634. EXPECT_EQ(body, "content");
  6635. res.set_content(body, "text/plain");
  6636. }
  6637. })
  6638. .Put("/content_receiver",
  6639. [&](const Request & /*req*/, Response &res,
  6640. const ContentReader &content_reader) {
  6641. std::string body;
  6642. content_reader([&](const char *data, size_t data_length) {
  6643. body.append(data, data_length);
  6644. return true;
  6645. });
  6646. EXPECT_EQ(body, "content");
  6647. res.set_content(body, "text/plain");
  6648. })
  6649. .Patch("/content_receiver",
  6650. [&](const Request & /*req*/, Response &res,
  6651. const ContentReader &content_reader) {
  6652. std::string body;
  6653. content_reader([&](const char *data, size_t data_length) {
  6654. body.append(data, data_length);
  6655. return true;
  6656. });
  6657. EXPECT_EQ(body, "content");
  6658. res.set_content(body, "text/plain");
  6659. })
  6660. .Post("/query-string-and-body",
  6661. [&](const Request &req, Response & /*res*/) {
  6662. ASSERT_TRUE(req.has_param("key"));
  6663. EXPECT_EQ(req.get_param_value("key"), "value");
  6664. EXPECT_EQ(req.body, "content");
  6665. })
  6666. .Get("/last-request",
  6667. [&](const Request &req, Response & /*res*/) {
  6668. EXPECT_EQ("close", req.get_header_value("Connection"));
  6669. })
  6670. .Get(R"(/redirect/(\d+))",
  6671. [&](const Request &req, Response &res) {
  6672. auto num = std::stoi(req.matches[1]) + 1;
  6673. std::string url = "/redirect/" + std::to_string(num);
  6674. res.set_redirect(url);
  6675. })
  6676. .Post("/binary",
  6677. [&](const Request &req, Response &res) {
  6678. EXPECT_EQ(4U, req.body.size());
  6679. EXPECT_EQ("application/octet-stream",
  6680. req.get_header_value("Content-Type"));
  6681. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6682. res.set_content(req.body, "application/octet-stream");
  6683. })
  6684. .Put("/binary",
  6685. [&](const Request &req, Response &res) {
  6686. EXPECT_EQ(4U, req.body.size());
  6687. EXPECT_EQ("application/octet-stream",
  6688. req.get_header_value("Content-Type"));
  6689. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6690. res.set_content(req.body, "application/octet-stream");
  6691. })
  6692. .Patch("/binary",
  6693. [&](const Request &req, Response &res) {
  6694. EXPECT_EQ(4U, req.body.size());
  6695. EXPECT_EQ("application/octet-stream",
  6696. req.get_header_value("Content-Type"));
  6697. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6698. res.set_content(req.body, "application/octet-stream");
  6699. })
  6700. .Delete("/binary",
  6701. [&](const Request &req, Response &res) {
  6702. EXPECT_EQ(4U, req.body.size());
  6703. EXPECT_EQ("application/octet-stream",
  6704. req.get_header_value("Content-Type"));
  6705. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6706. res.set_content(req.body, "application/octet-stream");
  6707. })
  6708. .Get("/issue1772",
  6709. [&](const Request & /*req*/, Response &res) {
  6710. res.status = 401;
  6711. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6712. })
  6713. .Delete("/issue609",
  6714. [](const httplib::Request &, httplib::Response &res,
  6715. const httplib::ContentReader &) {
  6716. res.set_content("ok", "text/plain");
  6717. })
  6718. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6719. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6720. .Get("/compress",
  6721. [&](const Request & /*req*/, Response &res) {
  6722. res.set_content(
  6723. "12345678901234567890123456789012345678901234567890123456789"
  6724. "01234567890123456789012345678901234567890",
  6725. "text/plain");
  6726. })
  6727. .Get("/compress-with-charset",
  6728. [&](const Request & /*req*/, Response &res) {
  6729. res.set_content(
  6730. "12345678901234567890123456789012345678901234567890123456789"
  6731. "01234567890123456789012345678901234567890",
  6732. "application/json; charset=utf-8");
  6733. })
  6734. .Get("/nocompress",
  6735. [&](const Request & /*req*/, Response &res) {
  6736. res.set_content(
  6737. "12345678901234567890123456789012345678901234567890123456789"
  6738. "01234567890123456789012345678901234567890",
  6739. "application/octet-stream");
  6740. })
  6741. .Post("/compress-multipart",
  6742. [&](const Request &req, Response & /*res*/) {
  6743. EXPECT_EQ(2u, req.form.fields.size());
  6744. ASSERT_TRUE(!req.form.has_field("???"));
  6745. {
  6746. const auto &text = req.form.get_field("key1");
  6747. EXPECT_EQ("test", text);
  6748. }
  6749. {
  6750. const auto &text = req.form.get_field("key2");
  6751. EXPECT_EQ("--abcdefg123", text);
  6752. }
  6753. })
  6754. #endif
  6755. ;
  6756. persons_["john"] = "programmer";
  6757. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6758. svr_.wait_until_ready();
  6759. }
  6760. virtual void TearDown() {
  6761. svr_.stop();
  6762. if (!request_threads_.empty()) {
  6763. std::this_thread::sleep_for(std::chrono::seconds(1));
  6764. for (auto &t : request_threads_) {
  6765. t.join();
  6766. }
  6767. }
  6768. t_.join();
  6769. }
  6770. map<string, string> persons_;
  6771. #ifdef CPPHTTPLIB_SSL_ENABLED
  6772. SSLClient cli_;
  6773. SSLServer svr_;
  6774. #else
  6775. Client cli_;
  6776. Server svr_;
  6777. #endif
  6778. thread t_;
  6779. std::vector<thread> request_threads_;
  6780. };
  6781. TEST_F(ServerTest, GetMethod200) {
  6782. auto res = cli_.Get("/hi");
  6783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6784. EXPECT_EQ("HTTP/1.1", res->version);
  6785. EXPECT_EQ(StatusCode::OK_200, res->status);
  6786. EXPECT_EQ("OK", res->reason);
  6787. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6788. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6789. EXPECT_EQ("Hello World!", res->body);
  6790. }
  6791. TEST_F(ServerTest, GetEmptyFile) {
  6792. auto res = cli_.Get("/empty_file");
  6793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6794. EXPECT_EQ(StatusCode::OK_200, res->status);
  6795. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6796. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6797. EXPECT_EQ("", res->body);
  6798. }
  6799. TEST_F(ServerTest, GetFileContent) {
  6800. auto res = cli_.Get("/file_content");
  6801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6802. EXPECT_EQ(StatusCode::OK_200, res->status);
  6803. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6804. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6805. EXPECT_EQ("test.html", res->body);
  6806. }
  6807. TEST_F(ServerTest, GetFileContentWithRange) {
  6808. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6810. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6811. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6812. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6813. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6814. EXPECT_EQ("est", res->body);
  6815. }
  6816. TEST_F(ServerTest, GetFileContentWithContentType) {
  6817. auto res = cli_.Get("/file_content_with_content_type");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6821. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6822. EXPECT_EQ("file\n", res->body);
  6823. }
  6824. TEST_F(ServerTest, GetInvalidFileContent) {
  6825. auto res = cli_.Get("/invalid_file_content");
  6826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6827. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6828. }
  6829. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6830. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6832. EXPECT_EQ("HTTP/1.1", res->version);
  6833. EXPECT_EQ(StatusCode::OK_200, res->status);
  6834. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6835. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6836. EXPECT_EQ("Hello World!", res->body);
  6837. }
  6838. TEST_F(ServerTest, GetMethod302) {
  6839. auto res = cli_.Get("/");
  6840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6841. EXPECT_EQ(StatusCode::Found_302, res->status);
  6842. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6843. }
  6844. TEST_F(ServerTest, GetMethod302Redirect) {
  6845. cli_.set_follow_location(true);
  6846. auto res = cli_.Get("/");
  6847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6848. EXPECT_EQ(StatusCode::OK_200, res->status);
  6849. EXPECT_EQ("Hello World!", res->body);
  6850. EXPECT_EQ("/hi", res->location);
  6851. }
  6852. TEST_F(ServerTest, GetMethod404) {
  6853. auto res = cli_.Get("/invalid");
  6854. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6855. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6856. }
  6857. TEST_F(ServerTest, HeadMethod200) {
  6858. auto res = cli_.Head("/hi");
  6859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6860. EXPECT_EQ(StatusCode::OK_200, res->status);
  6861. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6862. EXPECT_TRUE(res->body.empty());
  6863. }
  6864. TEST_F(ServerTest, HeadMethod200Static) {
  6865. auto res = cli_.Head("/mount/dir/index.html");
  6866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6867. EXPECT_EQ(StatusCode::OK_200, res->status);
  6868. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6869. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6870. EXPECT_TRUE(res->body.empty());
  6871. }
  6872. TEST_F(ServerTest, HeadMethod404) {
  6873. auto res = cli_.Head("/invalid");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6876. EXPECT_TRUE(res->body.empty());
  6877. }
  6878. TEST_F(ServerTest, GetMethodPersonJohn) {
  6879. auto res = cli_.Get("/person/john");
  6880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6881. EXPECT_EQ(StatusCode::OK_200, res->status);
  6882. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6883. EXPECT_EQ("programmer", res->body);
  6884. }
  6885. TEST_F(ServerTest, PostMethod1) {
  6886. auto res = cli_.Get("/person/john1");
  6887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6888. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6889. res = cli_.Post("/person", "name=john1&note=coder",
  6890. "application/x-www-form-urlencoded");
  6891. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6892. ASSERT_EQ(StatusCode::OK_200, res->status);
  6893. res = cli_.Get("/person/john1");
  6894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6895. ASSERT_EQ(StatusCode::OK_200, res->status);
  6896. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6897. ASSERT_EQ("coder", res->body);
  6898. }
  6899. TEST_F(ServerTest, PostMethod2) {
  6900. auto res = cli_.Get("/person/john2");
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6903. Params params;
  6904. params.emplace("name", "john2");
  6905. params.emplace("note", "coder");
  6906. res = cli_.Post("/person", params);
  6907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6908. ASSERT_EQ(StatusCode::OK_200, res->status);
  6909. res = cli_.Get("/person/john2");
  6910. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6911. ASSERT_EQ(StatusCode::OK_200, res->status);
  6912. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6913. ASSERT_EQ("coder", res->body);
  6914. }
  6915. TEST_F(ServerTest, PutMethod3) {
  6916. auto res = cli_.Get("/person/john3");
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6919. Params params;
  6920. params.emplace("name", "john3");
  6921. params.emplace("note", "coder");
  6922. res = cli_.Put("/person", params);
  6923. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6924. ASSERT_EQ(StatusCode::OK_200, res->status);
  6925. res = cli_.Get("/person/john3");
  6926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6927. ASSERT_EQ(StatusCode::OK_200, res->status);
  6928. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6929. ASSERT_EQ("coder", res->body);
  6930. }
  6931. TEST_F(ServerTest, DeleteMethod1) {
  6932. auto res = cli_.Get("/person/john4");
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6935. Params params;
  6936. params.emplace("name", "john4");
  6937. params.emplace("note", "coder");
  6938. res = cli_.Post("/person", params);
  6939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6940. ASSERT_EQ(StatusCode::OK_200, res->status);
  6941. res = cli_.Get("/person/john4");
  6942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6943. ASSERT_EQ(StatusCode::OK_200, res->status);
  6944. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6945. ASSERT_EQ("coder", res->body);
  6946. Params delete_params;
  6947. delete_params.emplace("name", "john4");
  6948. res = cli_.Delete("/person", delete_params);
  6949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6950. ASSERT_EQ(StatusCode::OK_200, res->status);
  6951. ASSERT_EQ("DELETED", res->body);
  6952. res = cli_.Get("/person/john4");
  6953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6954. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6955. }
  6956. TEST_F(ServerTest, DeleteMethod2) {
  6957. auto res = cli_.Get("/person/john5");
  6958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6959. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6960. Params params;
  6961. params.emplace("name", "john5");
  6962. params.emplace("note", "developer");
  6963. res = cli_.Post("/person", params);
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. ASSERT_EQ(StatusCode::OK_200, res->status);
  6966. res = cli_.Get("/person/john5");
  6967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6968. ASSERT_EQ(StatusCode::OK_200, res->status);
  6969. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6970. ASSERT_EQ("developer", res->body);
  6971. Params delete_params;
  6972. delete_params.emplace("name", "john5");
  6973. Headers headers;
  6974. headers.emplace("Custom-Header", "test-value");
  6975. res = cli_.Delete("/person", headers, delete_params);
  6976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6977. ASSERT_EQ(StatusCode::OK_200, res->status);
  6978. ASSERT_EQ("DELETED", res->body);
  6979. res = cli_.Get("/person/john5");
  6980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6981. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6982. }
  6983. TEST_F(ServerTest, DeleteMethod3) {
  6984. auto res = cli_.Get("/person/john6");
  6985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6986. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6987. Params params;
  6988. params.emplace("name", "john6");
  6989. params.emplace("note", "tester");
  6990. res = cli_.Post("/person", params);
  6991. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6992. ASSERT_EQ(StatusCode::OK_200, res->status);
  6993. res = cli_.Get("/person/john6");
  6994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6995. ASSERT_EQ(StatusCode::OK_200, res->status);
  6996. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6997. ASSERT_EQ("tester", res->body);
  6998. Params delete_params;
  6999. delete_params.emplace("name", "john6");
  7000. Headers headers;
  7001. headers.emplace("Custom-Header", "test-value");
  7002. res = cli_.Delete("/person", headers, delete_params, nullptr);
  7003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7004. ASSERT_EQ(StatusCode::OK_200, res->status);
  7005. ASSERT_EQ("DELETED", res->body);
  7006. res = cli_.Get("/person/john6");
  7007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7008. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7009. }
  7010. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  7011. Params params;
  7012. params.emplace("json", JSON_DATA);
  7013. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. ASSERT_EQ(StatusCode::OK_200, res->status);
  7016. ASSERT_EQ(JSON_DATA, res->body);
  7017. }
  7018. TEST_F(ServerTest, PostEmptyContent) {
  7019. auto res = cli_.Post("/empty", "", "text/plain");
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. ASSERT_EQ(StatusCode::OK_200, res->status);
  7022. ASSERT_EQ("empty", res->body);
  7023. }
  7024. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  7025. auto res = cli_.Post("/empty-no-content-type");
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. ASSERT_EQ(StatusCode::OK_200, res->status);
  7028. ASSERT_EQ("empty-no-content-type", res->body);
  7029. }
  7030. TEST_F(ServerTest, PostPathOnly) {
  7031. auto res = cli_.Post("/path-only");
  7032. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7033. ASSERT_EQ(StatusCode::OK_200, res->status);
  7034. ASSERT_EQ("path-only", res->body);
  7035. }
  7036. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  7037. auto res = cli_.Post("/path-headers-only",
  7038. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. ASSERT_EQ(StatusCode::OK_200, res->status);
  7041. ASSERT_EQ("path-headers-only", res->body);
  7042. }
  7043. TEST_F(ServerTest, PostLarge) {
  7044. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7046. ASSERT_EQ(StatusCode::OK_200, res->status);
  7047. EXPECT_EQ(LARGE_DATA, res->body);
  7048. }
  7049. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7050. auto res = cli_.Put("/empty-no-content-type");
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. ASSERT_EQ(StatusCode::OK_200, res->status);
  7053. ASSERT_EQ("empty-no-content-type", res->body);
  7054. }
  7055. TEST_F(ServerTest, GetMethodDir) {
  7056. auto res = cli_.Get("/dir/");
  7057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7058. EXPECT_EQ(StatusCode::OK_200, res->status);
  7059. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7060. auto body = R"(<html>
  7061. <head>
  7062. </head>
  7063. <body>
  7064. <a href="/dir/test.html">Test</a>
  7065. <a href="/hi">hi</a>
  7066. </body>
  7067. </html>
  7068. )";
  7069. EXPECT_EQ(body, res->body);
  7070. }
  7071. TEST_F(ServerTest, GetMethodDirTest) {
  7072. auto res = cli_.Get("/dir/test.html");
  7073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7074. EXPECT_EQ(StatusCode::OK_200, res->status);
  7075. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7076. EXPECT_EQ("test.html", res->body);
  7077. }
  7078. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7079. auto res = cli_.Get("/dir/../dir/test.html");
  7080. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7081. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7082. }
  7083. TEST_F(ServerTest, GetMethodInvalidPath) {
  7084. auto res = cli_.Get("/dir/../test.html");
  7085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7086. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7087. }
  7088. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7089. auto res = cli_.Get("/../www/dir/test.html");
  7090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7092. }
  7093. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7094. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7095. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7096. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7097. }
  7098. TEST_F(ServerTest, GetMethodDirMountTest) {
  7099. auto res = cli_.Get("/mount/dir/test.html");
  7100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7101. EXPECT_EQ(StatusCode::OK_200, res->status);
  7102. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7103. EXPECT_EQ("test.html", res->body);
  7104. }
  7105. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7106. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7109. }
  7110. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7111. auto res = cli_.Get("/mount/dir/../test.html");
  7112. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7113. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7114. }
  7115. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7116. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7118. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7119. }
  7120. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7121. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7123. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7124. }
  7125. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7126. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7128. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7129. }
  7130. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7131. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7133. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7134. }
  7135. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7136. auto res = cli_.Get("/mount/dir");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7139. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7140. }
  7141. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7142. auto res = cli_.Get("//dir");
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7145. EXPECT_FALSE(res->has_header("Location"));
  7146. }
  7147. TEST_F(ServerTest, PostMethod303) {
  7148. auto res = cli_.Post("/1", "body", "text/plain");
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7151. EXPECT_EQ("/2", res->get_header_value("Location"));
  7152. }
  7153. TEST_F(ServerTest, PostMethod303Redirect) {
  7154. cli_.set_follow_location(true);
  7155. auto res = cli_.Post("/1", "body", "text/plain");
  7156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7157. EXPECT_EQ(StatusCode::OK_200, res->status);
  7158. EXPECT_EQ("redirected.", res->body);
  7159. EXPECT_EQ("/2", res->location);
  7160. }
  7161. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7162. auto res = cli_.Get("/dir/test.abcde");
  7163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7164. EXPECT_EQ(StatusCode::OK_200, res->status);
  7165. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7166. EXPECT_EQ("abcde", res->body);
  7167. }
  7168. TEST_F(ServerTest, StaticFileRange) {
  7169. auto res =
  7170. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7171. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7172. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7173. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7174. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7175. EXPECT_EQ(true, res->has_header("Content-Range"));
  7176. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7177. EXPECT_EQ(std::string("cd"), res->body);
  7178. }
  7179. TEST_F(ServerTest, StaticFileRanges) {
  7180. auto res = cli_.Get("/dir/test.abcde",
  7181. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7183. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7184. EXPECT_TRUE(
  7185. res->get_header_value("Content-Type")
  7186. .find(
  7187. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7188. 0);
  7189. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7190. }
  7191. TEST_F(ServerTest, StaticFileRangeHead) {
  7192. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7194. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7195. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7196. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7197. EXPECT_EQ(true, res->has_header("Content-Range"));
  7198. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7199. }
  7200. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7201. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7202. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7203. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7204. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7205. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7206. EXPECT_EQ(true, res->has_header("Content-Range"));
  7207. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7208. res->get_header_value("Content-Range"));
  7209. EXPECT_EQ("LAST\n", res->body);
  7210. }
  7211. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7212. auto res =
  7213. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7215. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7217. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7218. EXPECT_EQ(true, res->has_header("Content-Range"));
  7219. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7220. }
  7221. TEST_F(ServerTest, StaticFileBigFile) {
  7222. auto res = cli_.Get("/dir/1MB.txt");
  7223. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7224. EXPECT_EQ(StatusCode::OK_200, res->status);
  7225. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7226. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7227. }
  7228. TEST_F(ServerTest, InvalidBaseDirMount) {
  7229. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7230. }
  7231. TEST_F(ServerTest, Binary) {
  7232. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7233. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7234. "application/octet-stream");
  7235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7236. ASSERT_EQ(StatusCode::OK_200, res->status);
  7237. ASSERT_EQ(4U, res->body.size());
  7238. res = cli_.Put("/binary", binary.data(), binary.size(),
  7239. "application/octet-stream");
  7240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7241. ASSERT_EQ(StatusCode::OK_200, res->status);
  7242. ASSERT_EQ(4U, res->body.size());
  7243. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7244. "application/octet-stream");
  7245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7246. ASSERT_EQ(StatusCode::OK_200, res->status);
  7247. ASSERT_EQ(4U, res->body.size());
  7248. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7249. "application/octet-stream");
  7250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7251. ASSERT_EQ(StatusCode::OK_200, res->status);
  7252. ASSERT_EQ(4U, res->body.size());
  7253. }
  7254. TEST_F(ServerTest, BinaryString) {
  7255. auto binary = std::string("\x00\x01\x02\x03", 4);
  7256. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7258. ASSERT_EQ(StatusCode::OK_200, res->status);
  7259. ASSERT_EQ(4U, res->body.size());
  7260. res = cli_.Put("/binary", binary, "application/octet-stream");
  7261. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7262. ASSERT_EQ(StatusCode::OK_200, res->status);
  7263. ASSERT_EQ(4U, res->body.size());
  7264. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7265. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7266. ASSERT_EQ(StatusCode::OK_200, res->status);
  7267. ASSERT_EQ(4U, res->body.size());
  7268. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7270. ASSERT_EQ(StatusCode::OK_200, res->status);
  7271. ASSERT_EQ(4U, res->body.size());
  7272. }
  7273. TEST_F(ServerTest, EmptyRequest) {
  7274. auto res = cli_.Get("");
  7275. ASSERT_TRUE(!res);
  7276. EXPECT_EQ(Error::Connection, res.error());
  7277. }
  7278. TEST_F(ServerTest, LongRequest) {
  7279. std::string request;
  7280. for (size_t i = 0; i < 545; i++) {
  7281. request += "/TooLongRequest";
  7282. }
  7283. request += "OK";
  7284. auto res = cli_.Get(request.c_str());
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7287. }
  7288. TEST_F(ServerTest, TooLongRequest) {
  7289. std::string request;
  7290. for (size_t i = 0; i < 546; i++) {
  7291. request += "/TooLongRequest";
  7292. }
  7293. request += "_NG";
  7294. auto start = std::chrono::high_resolution_clock::now();
  7295. cli_.set_keep_alive(true);
  7296. auto res = cli_.Get(request.c_str());
  7297. auto end = std::chrono::high_resolution_clock::now();
  7298. auto elapsed =
  7299. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7300. .count();
  7301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7302. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7303. EXPECT_LE(elapsed, 1000);
  7304. EXPECT_EQ("close", res->get_header_value("Connection"));
  7305. EXPECT_FALSE(cli_.is_socket_open());
  7306. }
  7307. TEST_F(ServerTest, AlmostTooLongRequest) {
  7308. // test for #2046 - URI length check shouldn't include other content on req
  7309. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7310. // leading /, space, HTTP/1.1)
  7311. std::string request =
  7312. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7313. auto res = cli_.Get(request.c_str());
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7316. }
  7317. TEST_F(ServerTest, LongHeader) {
  7318. Request req;
  7319. req.method = "GET";
  7320. req.path = "/hi";
  7321. std::string host_and_port;
  7322. host_and_port += HOST;
  7323. host_and_port += ":";
  7324. host_and_port += std::to_string(PORT);
  7325. req.headers.emplace("Host", host_and_port.c_str());
  7326. req.headers.emplace("Accept", "*/*");
  7327. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7328. req.headers.emplace(
  7329. "Header-Name",
  7330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7342. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7343. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7352. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7353. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7354. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7355. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7356. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7357. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7358. "@@@@@@@@@@@@@@@@");
  7359. auto res = std::make_shared<Response>();
  7360. auto error = Error::Success;
  7361. auto ret = cli_.send(req, *res, error);
  7362. ASSERT_TRUE(ret);
  7363. EXPECT_EQ(StatusCode::OK_200, res->status);
  7364. }
  7365. TEST_F(ServerTest, LongQueryValue) {
  7366. auto start = std::chrono::high_resolution_clock::now();
  7367. cli_.set_keep_alive(true);
  7368. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7369. auto end = std::chrono::high_resolution_clock::now();
  7370. auto elapsed =
  7371. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7372. .count();
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7375. EXPECT_LE(elapsed, 1000);
  7376. EXPECT_EQ("close", res->get_header_value("Connection"));
  7377. EXPECT_FALSE(cli_.is_socket_open());
  7378. }
  7379. TEST_F(ServerTest, TooLongQueryValue) {
  7380. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7381. ASSERT_FALSE(res);
  7382. EXPECT_EQ(Error::Read, res.error());
  7383. }
  7384. TEST_F(ServerTest, TooLongHeader) {
  7385. Request req;
  7386. req.method = "GET";
  7387. req.path = "/hi";
  7388. std::string host_and_port;
  7389. host_and_port += HOST;
  7390. host_and_port += ":";
  7391. host_and_port += std::to_string(PORT);
  7392. req.headers.emplace("Host", host_and_port.c_str());
  7393. req.headers.emplace("Accept", "*/*");
  7394. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7395. req.headers.emplace(
  7396. "Header-Name",
  7397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7406. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7407. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7419. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7420. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7421. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7422. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7423. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7424. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7425. "@@@@@@@@@@@@@@@@@");
  7426. auto res = std::make_shared<Response>();
  7427. auto error = Error::Success;
  7428. auto ret = cli_.send(req, *res, error);
  7429. ASSERT_TRUE(ret);
  7430. EXPECT_EQ(StatusCode::OK_200, res->status);
  7431. }
  7432. TEST_F(ServerTest, HeaderCountAtLimit) {
  7433. // Test with headers just under the 100 limit
  7434. httplib::Headers headers;
  7435. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7436. // This should keep us just under the 100 header limit
  7437. for (int i = 0; i < 95; i++) {
  7438. std::string name = "X-Test-Header-" + std::to_string(i);
  7439. std::string value = "value" + std::to_string(i);
  7440. headers.emplace(name, value);
  7441. }
  7442. // This should work fine as we're under the limit
  7443. auto res = cli_.Get("/hi", headers);
  7444. EXPECT_TRUE(res);
  7445. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7446. }
  7447. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7448. // Test with many headers to exceed the 100 limit
  7449. httplib::Headers headers;
  7450. // Add 150 headers to definitely exceed the 100 limit
  7451. for (int i = 0; i < 150; i++) {
  7452. std::string name = "X-Test-Header-" + std::to_string(i);
  7453. std::string value = "value" + std::to_string(i);
  7454. headers.emplace(name, value);
  7455. }
  7456. // This should fail due to exceeding header count limit
  7457. cli_.set_keep_alive(true);
  7458. auto res = cli_.Get("/hi", headers);
  7459. // The server should respond with 400 Bad Request
  7460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7461. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7462. EXPECT_EQ("close", res->get_header_value("Connection"));
  7463. EXPECT_FALSE(cli_.is_socket_open());
  7464. }
  7465. TEST_F(ServerTest, PercentEncoding) {
  7466. auto res = cli_.Get("/e%6edwith%");
  7467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7468. EXPECT_EQ(StatusCode::OK_200, res->status);
  7469. }
  7470. TEST_F(ServerTest, PercentEncodingUnicode) {
  7471. auto res = cli_.Get("/e%u006edwith%");
  7472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7473. EXPECT_EQ(StatusCode::OK_200, res->status);
  7474. }
  7475. TEST_F(ServerTest, InvalidPercentEncoding) {
  7476. auto res = cli_.Get("/%endwith%");
  7477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7478. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7479. }
  7480. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7481. auto res = cli_.Get("/%uendwith%");
  7482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7484. }
  7485. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7486. auto res = cli_.Get("/hello?aaa=bbb%");
  7487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7488. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7489. }
  7490. TEST_F(ServerTest, PlusSignEncoding) {
  7491. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7493. EXPECT_EQ(StatusCode::OK_200, res->status);
  7494. EXPECT_EQ("a +b", res->body);
  7495. }
  7496. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7497. // This test simulates a potential DoS attack using many headers
  7498. // to verify our security fix prevents memory exhaustion
  7499. httplib::Headers attack_headers;
  7500. // Attempt to add many headers like an attacker would (200 headers to far
  7501. // exceed limit)
  7502. for (int i = 0; i < 200; i++) {
  7503. std::string name = "X-Attack-Header-" + std::to_string(i);
  7504. std::string value = "attack_payload_" + std::to_string(i);
  7505. attack_headers.emplace(name, value);
  7506. }
  7507. // Try to POST with excessive headers
  7508. cli_.set_keep_alive(true);
  7509. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7510. // Should either fail or return 400 Bad Request due to security limit
  7511. if (res) {
  7512. // If we get a response, it should be 400 Bad Request
  7513. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7514. EXPECT_EQ("close", res->get_header_value("Connection"));
  7515. }
  7516. EXPECT_FALSE(cli_.is_socket_open());
  7517. }
  7518. TEST_F(ServerTest, MultipartFormData) {
  7519. UploadFormDataItems items = {
  7520. {"text1", "text default", "", ""},
  7521. {"text2", "aωb", "", ""},
  7522. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7523. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7524. {"file3", "", "", "application/octet-stream"},
  7525. {"file4", "", "", " application/json tmp-string "}};
  7526. auto res = cli_.Post("/multipart", items);
  7527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7528. EXPECT_EQ(StatusCode::OK_200, res->status);
  7529. }
  7530. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7531. UploadFormDataItems items = {
  7532. {"text", "default text", "", ""},
  7533. {"multi_text1", "aaaaa", "", ""},
  7534. {"multi_text1", "bbbbb", "", ""},
  7535. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7536. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7537. "application/json"},
  7538. };
  7539. auto res = cli_.Post("/multipart/multi_file_values", items);
  7540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7541. EXPECT_EQ(StatusCode::OK_200, res->status);
  7542. }
  7543. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7544. auto res = cli_.Get("/hi");
  7545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7548. EXPECT_EQ("Hello World!", res->body);
  7549. }
  7550. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7551. Request req;
  7552. req.method = "POST";
  7553. req.path = "/chunked";
  7554. std::string host_and_port;
  7555. host_and_port += HOST;
  7556. host_and_port += ":";
  7557. host_and_port += std::to_string(PORT);
  7558. req.headers.emplace("Host", host_and_port.c_str());
  7559. req.headers.emplace("Accept", "*/*");
  7560. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7561. req.headers.emplace("Content-Type", "text/plain");
  7562. req.headers.emplace("Content-Length", "0");
  7563. req.headers.emplace(
  7564. "Transfer-Encoding",
  7565. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7566. // Client does not chunk, so make a chunked body manually.
  7567. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7568. auto res = std::make_shared<Response>();
  7569. auto error = Error::Success;
  7570. auto ret = cli_.send(req, *res, error);
  7571. ASSERT_TRUE(ret);
  7572. EXPECT_EQ(StatusCode::OK_200, res->status);
  7573. }
  7574. template <typename ClientT>
  7575. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7576. int expected_status) {
  7577. Request req;
  7578. req.method = "POST";
  7579. req.path = "/chunked";
  7580. std::string host_and_port;
  7581. host_and_port += HOST;
  7582. host_and_port += ":";
  7583. host_and_port += std::to_string(PORT);
  7584. req.headers.emplace("Host", host_and_port.c_str());
  7585. req.headers.emplace("Content-Length", "0");
  7586. req.headers.emplace("Transfer-Encoding", "chunked");
  7587. req.body = body;
  7588. auto res = std::make_shared<Response>();
  7589. auto error = Error::Success;
  7590. ASSERT_TRUE(cli.send(req, *res, error));
  7591. EXPECT_EQ(expected_status, res->status);
  7592. }
  7593. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7594. // rather than treat them as valid lengths.
  7595. template <typename ClientT>
  7596. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7597. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7598. }
  7599. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7600. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7601. }
  7602. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7603. expect_chunked_body_rejected(
  7604. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7605. }
  7606. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7607. // chunk-size line carries no CR, LF or other control character ahead of its
  7608. // terminator. Such a line must be refused rather than read as extension text.
  7609. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7610. expect_chunked_body_rejected(
  7611. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7612. }
  7613. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7614. expect_chunked_body_rejected(
  7615. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7616. }
  7617. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7618. expect_chunked_body_rejected(
  7619. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7620. }
  7621. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7622. // The literal stays split: a hex escape consumes every hex digit that
  7623. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7624. expect_chunked_body_rejected(
  7625. cli_, "4;a\x01"
  7626. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7627. }
  7628. // The bytes around chunk data are no payload, so they cannot ride on the
  7629. // payload limit
  7630. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7631. // Small enough that the whole request is sent before the server turns it
  7632. // down, yet past the limit by the last chunks
  7633. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7634. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7635. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7636. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7637. SCOPED_TRACE(size_line.substr(0, 2));
  7638. std::string body;
  7639. for (auto c : std::string("dechunked post body")) {
  7640. body += size_line + "\r\n" + c + "\r\n";
  7641. }
  7642. body += "0\r\n\r\n";
  7643. expect_chunked_body_rejected(cli_, body.c_str());
  7644. }
  7645. }
  7646. TEST_F(ServerTest, AcceptsChunkExtension) {
  7647. expect_chunked_body_status(cli_,
  7648. "4;name=value\r\ndech\r\n"
  7649. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7650. "0;last\r\n\r\n",
  7651. StatusCode::OK_200);
  7652. }
  7653. TEST_F(ServerTest, GetStreamed2) {
  7654. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7655. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7656. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7657. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7658. EXPECT_EQ(true, res->has_header("Content-Range"));
  7659. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7660. EXPECT_EQ(std::string("ab"), res->body);
  7661. }
  7662. TEST_F(ServerTest, GetStreamed) {
  7663. auto res = cli_.Get("/streamed");
  7664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7665. EXPECT_EQ(StatusCode::OK_200, res->status);
  7666. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7667. EXPECT_EQ(std::string("aaabbb"), res->body);
  7668. }
  7669. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7670. auto res = cli_.Get("/streamed-without-length",
  7671. Headers{make_range_header({{0, -1}})});
  7672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7673. EXPECT_EQ(StatusCode::OK_200, res->status);
  7674. EXPECT_EQ(false, res->has_header("Content-Length"));
  7675. EXPECT_EQ(false, res->has_header("Content-Range"));
  7676. EXPECT_EQ(std::string("abcdefg"), res->body);
  7677. }
  7678. TEST_F(ServerTest, GetStreamedWithRange1) {
  7679. auto res =
  7680. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7681. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7682. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7683. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7684. EXPECT_EQ(true, res->has_header("Content-Range"));
  7685. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7686. EXPECT_EQ(std::string("def"), res->body);
  7687. }
  7688. TEST_F(ServerTest, GetStreamedWithRange2) {
  7689. auto res =
  7690. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7692. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7693. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7694. EXPECT_EQ(true, res->has_header("Content-Range"));
  7695. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7696. EXPECT_EQ(std::string("bcdefg"), res->body);
  7697. }
  7698. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7699. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7700. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7701. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7702. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7703. EXPECT_EQ(true, res->has_header("Content-Range"));
  7704. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7705. EXPECT_EQ(std::string("efg"), res->body);
  7706. }
  7707. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7708. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7709. // the entire representation.
  7710. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7711. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7712. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7713. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7714. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7715. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7716. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7717. }
  7718. }
  7719. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7720. auto res =
  7721. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7723. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7724. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7725. EXPECT_EQ(false, res->has_header("Content-Range"));
  7726. EXPECT_EQ(0U, res->body.size());
  7727. }
  7728. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7729. // Only a 206 is served as a partial representation. Under any other status
  7730. // `apply_ranges()` reported the full content length, so the body must match
  7731. // that header, and the content provider must never be asked for an offset
  7732. // outside the representation.
  7733. auto check = [&](int status, const char *range) {
  7734. auto path =
  7735. std::string("/streamed-with-range?status=") + std::to_string(status);
  7736. auto ctx = path + " Range: " + range;
  7737. auto res = cli_.Get(path, Headers{{"Range", range}});
  7738. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7739. EXPECT_EQ(status, res->status) << ctx;
  7740. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7741. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7742. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7743. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7744. };
  7745. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7746. check(403, "bytes=3-5");
  7747. // The offset is far past the representation.
  7748. check(403, "bytes=100000-100200");
  7749. // `first_pos` is still -1 here, and the bounds asserts in
  7750. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7751. check(403, "bytes=-3");
  7752. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7753. // multipart branch would have written one that is empty.
  7754. check(403, "bytes=1-2, 4-5");
  7755. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7756. // covers the whole representation.
  7757. check(200, "bytes=3-5");
  7758. check(200, "bytes=1-2, 4-5");
  7759. }
  7760. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7761. auto res =
  7762. cli_.Get("/streamed-with-range",
  7763. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7764. "92233720368547758079223372036854775807"}});
  7765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7766. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7767. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7768. EXPECT_EQ(false, res->has_header("Content-Range"));
  7769. EXPECT_EQ(0U, res->body.size());
  7770. }
  7771. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7772. auto res = cli_.Get(
  7773. "/with-range",
  7774. Headers{{"Range",
  7775. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7776. {"Accept-Encoding", ""}});
  7777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7778. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7779. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7780. EXPECT_EQ(true, res->has_header("Content-Range"));
  7781. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7782. EXPECT_EQ(std::string("abcdefg"), res->body);
  7783. }
  7784. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7785. auto res = cli_.Get("/with-range", Headers{
  7786. {"Range", "bytes=0-"},
  7787. {"Accept-Encoding", ""},
  7788. });
  7789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7790. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7791. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7792. EXPECT_EQ(true, res->has_header("Content-Range"));
  7793. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7794. EXPECT_EQ(std::string("abcdefg"), res->body);
  7795. }
  7796. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7797. auto res = cli_.Get("/streamed-with-range",
  7798. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7800. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7801. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7802. EXPECT_EQ(false, res->has_header("Content-Range"));
  7803. EXPECT_EQ(267U, res->body.size());
  7804. // Check that both range contents are present
  7805. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7806. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7807. // Check that Content-Range headers are present for both ranges
  7808. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7809. std::string::npos);
  7810. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7811. std::string::npos);
  7812. }
  7813. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7814. Ranges ranges;
  7815. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7816. ranges.emplace_back(0, -1);
  7817. }
  7818. auto res = cli_.Get("/streamed-with-range?error",
  7819. Headers{{make_range_header(ranges)}});
  7820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7821. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7822. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7823. EXPECT_EQ(false, res->has_header("Content-Range"));
  7824. EXPECT_EQ(0U, res->body.size());
  7825. }
  7826. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7827. auto res = cli_.Get("/streamed-with-range",
  7828. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7830. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7831. EXPECT_EQ(5U, res->body.size());
  7832. // Check that overlapping ranges are coalesced into a single range
  7833. EXPECT_EQ("bcdef", res->body);
  7834. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7835. // Should be single range, not multipart
  7836. EXPECT_TRUE(res->has_header("Content-Range"));
  7837. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7838. }
  7839. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7840. auto res = cli_.Get("/streamed-with-range",
  7841. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7843. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7844. EXPECT_EQ(268U, res->body.size());
  7845. // Check that both range contents are present
  7846. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7847. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7848. // Check that Content-Range headers are present for both ranges
  7849. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7850. std::string::npos);
  7851. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7852. std::string::npos);
  7853. }
  7854. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7855. auto res = cli_.Get("/streamed-with-range",
  7856. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7858. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7859. EXPECT_EQ(269U, res->body.size());
  7860. // Check that both duplicate range contents are present
  7861. size_t first_abc = res->body.find("abc\r\n");
  7862. EXPECT_TRUE(first_abc != std::string::npos);
  7863. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7864. EXPECT_TRUE(second_abc != std::string::npos);
  7865. // Check that Content-Range headers are present for both ranges
  7866. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7867. EXPECT_TRUE(first_range != std::string::npos);
  7868. size_t second_range =
  7869. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7870. EXPECT_TRUE(second_range != std::string::npos);
  7871. }
  7872. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7873. auto res =
  7874. cli_.Get("/streamed-with-range?error",
  7875. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7877. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7878. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7879. EXPECT_EQ(false, res->has_header("Content-Range"));
  7880. EXPECT_EQ(0U, res->body.size());
  7881. }
  7882. TEST_F(ServerTest, GetStreamedEndless) {
  7883. uint64_t offset = 0;
  7884. auto res = cli_.Get("/streamed-cancel",
  7885. [&](const char * /*data*/, uint64_t data_length) {
  7886. if (offset < 100) {
  7887. offset += data_length;
  7888. return true;
  7889. }
  7890. return false;
  7891. });
  7892. ASSERT_TRUE(!res);
  7893. EXPECT_EQ(Error::Canceled, res.error());
  7894. }
  7895. TEST_F(ServerTest, ClientStop) {
  7896. std::atomic_size_t count{4};
  7897. std::vector<std::thread> threads;
  7898. for (auto i = count.load(); i != 0; --i) {
  7899. threads.emplace_back([&]() {
  7900. auto res = cli_.Get("/streamed-cancel",
  7901. [&](const char *, uint64_t) { return true; });
  7902. --count;
  7903. ASSERT_TRUE(!res);
  7904. EXPECT_TRUE(res.error() == Error::Canceled ||
  7905. res.error() == Error::Read || res.error() == Error::Write);
  7906. });
  7907. }
  7908. std::this_thread::sleep_for(std::chrono::seconds(2));
  7909. while (count != 0) {
  7910. cli_.stop();
  7911. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7912. }
  7913. for (auto &t : threads) {
  7914. t.join();
  7915. }
  7916. }
  7917. TEST_F(ServerTest, GetWithRange1) {
  7918. auto res = cli_.Get("/with-range", Headers{
  7919. make_range_header({{3, 5}}),
  7920. {"Accept-Encoding", ""},
  7921. });
  7922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7923. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7924. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7925. EXPECT_EQ(true, res->has_header("Content-Range"));
  7926. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7927. EXPECT_EQ(std::string("def"), res->body);
  7928. }
  7929. TEST_F(ServerTest, GetWithRange2) {
  7930. auto res = cli_.Get("/with-range", Headers{
  7931. make_range_header({{1, -1}}),
  7932. {"Accept-Encoding", ""},
  7933. });
  7934. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7935. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7936. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7937. EXPECT_EQ(true, res->has_header("Content-Range"));
  7938. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7939. EXPECT_EQ(std::string("bcdefg"), res->body);
  7940. }
  7941. TEST_F(ServerTest, GetWithRange3) {
  7942. auto res = cli_.Get("/with-range", Headers{
  7943. make_range_header({{0, 0}}),
  7944. {"Accept-Encoding", ""},
  7945. });
  7946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7947. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7948. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7949. EXPECT_EQ(true, res->has_header("Content-Range"));
  7950. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7951. EXPECT_EQ(std::string("a"), res->body);
  7952. }
  7953. TEST_F(ServerTest, GetWithRange4) {
  7954. auto res = cli_.Get("/with-range", Headers{
  7955. make_range_header({{-1, 2}}),
  7956. {"Accept-Encoding", ""},
  7957. });
  7958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7959. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7960. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7961. EXPECT_EQ(true, res->has_header("Content-Range"));
  7962. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7963. EXPECT_EQ(std::string("fg"), res->body);
  7964. }
  7965. TEST_F(ServerTest, GetWithRange5) {
  7966. auto res = cli_.Get("/with-range", Headers{
  7967. make_range_header({{0, 5}}),
  7968. {"Accept-Encoding", ""},
  7969. });
  7970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7971. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7972. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7973. EXPECT_EQ(true, res->has_header("Content-Range"));
  7974. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7975. EXPECT_EQ(std::string("abcdef"), res->body);
  7976. }
  7977. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7978. auto res =
  7979. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7982. }
  7983. TEST_F(ServerTest, GetWithRangeMultipart) {
  7984. auto res =
  7985. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7986. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7988. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7989. EXPECT_EQ(false, res->has_header("Content-Range"));
  7990. EXPECT_EQ(267U, res->body.size());
  7991. }
  7992. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7993. auto res = cli_.Get("/with-range",
  7994. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7996. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7997. }
  7998. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7999. auto res = cli_.Get("/with-range-customized-response",
  8000. Headers{{make_range_header({{1, 2}})}});
  8001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8002. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8003. EXPECT_EQ(true, res->has_header("Content-Length"));
  8004. EXPECT_EQ(false, res->has_header("Content-Range"));
  8005. EXPECT_EQ(JSON_DATA, res->body);
  8006. }
  8007. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  8008. auto res = cli_.Get("/with-range-customized-response",
  8009. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8011. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8012. EXPECT_EQ(true, res->has_header("Content-Length"));
  8013. EXPECT_EQ(false, res->has_header("Content-Range"));
  8014. EXPECT_EQ(JSON_DATA, res->body);
  8015. }
  8016. TEST_F(ServerTest, Issue1772) {
  8017. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  8018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8019. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  8020. }
  8021. TEST_F(ServerTest, Issue609) {
  8022. auto res = cli_.Delete("/issue609");
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. EXPECT_EQ(std::string("ok"), res->body);
  8026. }
  8027. TEST_F(ServerTest, GetStreamedChunked) {
  8028. auto res = cli_.Get("/streamed-chunked");
  8029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8030. EXPECT_EQ(StatusCode::OK_200, res->status);
  8031. EXPECT_EQ(std::string("123456789"), res->body);
  8032. }
  8033. TEST_F(ServerTest, GetStreamedChunked2) {
  8034. auto res = cli_.Get("/streamed-chunked2");
  8035. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8036. EXPECT_EQ(StatusCode::OK_200, res->status);
  8037. EXPECT_EQ(std::string("123456789"), res->body);
  8038. }
  8039. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  8040. auto res = cli_.Get("/streamed-chunked-with-trailer");
  8041. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8042. EXPECT_EQ(StatusCode::OK_200, res->status);
  8043. EXPECT_EQ(std::string("123456789"), res->body);
  8044. EXPECT_TRUE(res->has_header("Trailer"));
  8045. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8046. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8047. // Trailers are now stored separately from headers (security fix)
  8048. EXPECT_EQ(2U, res->trailers.size());
  8049. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8050. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8051. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8052. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8053. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8054. // Verify trailers are NOT in headers (security verification)
  8055. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8056. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8057. }
  8058. TEST_F(ServerTest, LargeChunkedPost) {
  8059. Request req;
  8060. req.method = "POST";
  8061. req.path = "/large-chunked";
  8062. std::string host_and_port;
  8063. host_and_port += HOST;
  8064. host_and_port += ":";
  8065. host_and_port += std::to_string(PORT);
  8066. req.headers.emplace("Host", host_and_port.c_str());
  8067. req.headers.emplace("Accept", "*/*");
  8068. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8069. req.headers.emplace("Content-Type", "text/plain");
  8070. req.headers.emplace("Content-Length", "0");
  8071. req.headers.emplace("Transfer-Encoding", "chunked");
  8072. std::string long_string(30 * 1024u, 'a');
  8073. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8074. // Attempt to make a large enough post to exceed OS buffers, to test that
  8075. // the server handles short reads if the full chunk data isn't available.
  8076. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8077. auto res = std::make_shared<Response>();
  8078. auto error = Error::Success;
  8079. auto ret = cli_.send(req, *res, error);
  8080. ASSERT_TRUE(ret);
  8081. EXPECT_EQ(StatusCode::OK_200, res->status);
  8082. }
  8083. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8084. auto res = cli_.Get("/remote_addr");
  8085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8086. EXPECT_EQ(StatusCode::OK_200, res->status);
  8087. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8088. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8089. }
  8090. TEST_F(ServerTest, GetMethodLocalAddr) {
  8091. auto res = cli_.Get("/local_addr");
  8092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8093. EXPECT_EQ(StatusCode::OK_200, res->status);
  8094. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8095. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8096. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8097. }
  8098. TEST_F(ServerTest, HTTPResponseSplitting) {
  8099. auto res = cli_.Get("/http_response_splitting");
  8100. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8101. EXPECT_EQ(StatusCode::OK_200, res->status);
  8102. }
  8103. TEST_F(ServerTest, SlowRequest) {
  8104. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8105. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8106. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8107. }
  8108. #if 0
  8109. TEST_F(ServerTest, SlowPost) {
  8110. char buffer[64 * 1024];
  8111. memset(buffer, 0x42, sizeof(buffer));
  8112. auto res = cli_.Post(
  8113. "/slowpost", 64 * 1024 * 1024,
  8114. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8115. auto ret = sink.write(buffer, sizeof(buffer));
  8116. EXPECT_TRUE(ret);
  8117. return true;
  8118. },
  8119. "text/plain");
  8120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8121. EXPECT_EQ(StatusCode::OK_200, res->status);
  8122. }
  8123. TEST_F(ServerTest, SlowPostFail) {
  8124. char buffer[64 * 1024];
  8125. memset(buffer, 0x42, sizeof(buffer));
  8126. cli_.set_write_timeout(std::chrono::seconds(0));
  8127. auto res = cli_.Post(
  8128. "/slowpost", 64 * 1024 * 1024,
  8129. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8130. sink.write(buffer, sizeof(buffer));
  8131. return true;
  8132. },
  8133. "text/plain");
  8134. ASSERT_TRUE(!res);
  8135. EXPECT_EQ(Error::Write, res.error());
  8136. }
  8137. #endif
  8138. TEST_F(ServerTest, Put) {
  8139. auto res = cli_.Put("/put", "PUT", "text/plain");
  8140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8141. EXPECT_EQ(StatusCode::OK_200, res->status);
  8142. EXPECT_EQ("PUT", res->body);
  8143. }
  8144. TEST_F(ServerTest, PutWithContentProvider) {
  8145. auto res = cli_.Put(
  8146. "/put", 3,
  8147. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8148. sink.os << "PUT";
  8149. return true;
  8150. },
  8151. "text/plain");
  8152. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8153. EXPECT_EQ(StatusCode::OK_200, res->status);
  8154. EXPECT_EQ("PUT", res->body);
  8155. }
  8156. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8157. auto res = cli_.Post(
  8158. "/post", 42,
  8159. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8160. return false;
  8161. },
  8162. "text/plain");
  8163. ASSERT_TRUE(!res);
  8164. EXPECT_EQ(Error::Canceled, res.error());
  8165. }
  8166. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8167. auto res = cli_.Put(
  8168. "/put",
  8169. [](size_t /*offset*/, DataSink &sink) {
  8170. sink.os << "PUT";
  8171. sink.done();
  8172. return true;
  8173. },
  8174. "text/plain");
  8175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8176. EXPECT_EQ(StatusCode::OK_200, res->status);
  8177. EXPECT_EQ("PUT", res->body);
  8178. }
  8179. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8180. auto res = cli_.Post(
  8181. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8182. "text/plain");
  8183. ASSERT_TRUE(!res);
  8184. EXPECT_EQ(Error::Canceled, res.error());
  8185. }
  8186. TEST_F(ServerTest, PostLoopBack) {
  8187. std::string body;
  8188. auto res = cli_.Post(
  8189. "/post-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, PutLoopBack) {
  8207. std::string body;
  8208. auto res = cli_.Put(
  8209. "/put-loopback", 9,
  8210. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8211. EXPECT_EQ(9u, length);
  8212. sink.write("123", 3);
  8213. sink.write("456", 3);
  8214. sink.write("789", 3);
  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. TEST_F(ServerTest, PatchLoopBack) {
  8227. std::string body;
  8228. auto res = cli_.Patch(
  8229. "/patch-loopback", 9,
  8230. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8231. EXPECT_EQ(9u, length);
  8232. sink.write("123", 3);
  8233. sink.write("456", 3);
  8234. sink.write("789", 3);
  8235. return true;
  8236. },
  8237. "text/plain",
  8238. [&body](const char *data, size_t data_length) {
  8239. body.append(data, data_length);
  8240. return true;
  8241. });
  8242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8243. EXPECT_EQ(StatusCode::OK_200, res->status);
  8244. EXPECT_EQ("123456789", body);
  8245. }
  8246. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8247. std::string body;
  8248. auto res = cli_.Post(
  8249. "/post-loopback",
  8250. [](size_t /*offset*/, DataSink &sink) {
  8251. sink.write("123", 3);
  8252. sink.write("456", 3);
  8253. sink.write("789", 3);
  8254. sink.done();
  8255. return true;
  8256. },
  8257. "text/plain",
  8258. [&body](const char *data, size_t data_length) {
  8259. body.append(data, data_length);
  8260. return true;
  8261. });
  8262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8263. EXPECT_EQ(StatusCode::OK_200, res->status);
  8264. EXPECT_EQ("123456789", body);
  8265. }
  8266. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8267. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8268. cli_.set_compress(true);
  8269. auto res = cli_.Put(
  8270. "/put", 3,
  8271. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8272. sink.os << "PUT";
  8273. return true;
  8274. },
  8275. "text/plain");
  8276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8277. EXPECT_EQ(StatusCode::OK_200, res->status);
  8278. EXPECT_EQ("PUT", res->body);
  8279. }
  8280. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8281. cli_.set_compress(true);
  8282. auto res = cli_.Post(
  8283. "/post", 42,
  8284. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8285. return false;
  8286. },
  8287. "text/plain");
  8288. ASSERT_TRUE(!res);
  8289. EXPECT_EQ(Error::Canceled, res.error());
  8290. }
  8291. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8292. cli_.set_compress(true);
  8293. auto res = cli_.Put(
  8294. "/put",
  8295. [](size_t /*offset*/, DataSink &sink) {
  8296. sink.os << "PUT";
  8297. sink.done();
  8298. return true;
  8299. },
  8300. "text/plain");
  8301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8302. EXPECT_EQ(StatusCode::OK_200, res->status);
  8303. EXPECT_EQ("PUT", res->body);
  8304. }
  8305. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8306. cli_.set_compress(true);
  8307. auto res = cli_.Post(
  8308. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8309. "text/plain");
  8310. ASSERT_TRUE(!res);
  8311. EXPECT_EQ(Error::Canceled, res.error());
  8312. }
  8313. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8314. cli_.set_compress(true);
  8315. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8317. EXPECT_EQ(StatusCode::OK_200, res->status);
  8318. EXPECT_EQ(LARGE_DATA, res->body);
  8319. }
  8320. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8321. #ifdef CPPHTTPLIB_SSL_ENABLED
  8322. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8323. Client cli(s.c_str());
  8324. cli.enable_server_certificate_verification(false);
  8325. #else
  8326. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8327. Client cli(s.c_str());
  8328. #endif
  8329. cli.set_compress(true);
  8330. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8332. EXPECT_EQ(StatusCode::OK_200, res->status);
  8333. EXPECT_EQ(LARGE_DATA, res->body);
  8334. // The compressed size should be less than a 10th of the original. May vary
  8335. // depending on the zlib library.
  8336. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8337. static_cast<uint64_t>(10 * 1024 * 1024));
  8338. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8339. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8340. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8341. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8342. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8343. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8344. #endif
  8345. }
  8346. TEST_F(ServerTest, PutContentWithDeflate) {
  8347. cli_.set_compress(false);
  8348. Headers headers;
  8349. headers.emplace("Content-Encoding", "deflate");
  8350. // PUT in deflate format:
  8351. auto res = cli_.Put("/put", headers,
  8352. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8354. EXPECT_EQ(StatusCode::OK_200, res->status);
  8355. EXPECT_EQ("PUT", res->body);
  8356. }
  8357. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8358. Headers headers;
  8359. headers.emplace("Accept-Encoding", "gzip, deflate");
  8360. auto res = cli_.Get("/streamed-chunked", headers);
  8361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8362. EXPECT_EQ(StatusCode::OK_200, res->status);
  8363. EXPECT_EQ(std::string("123456789"), res->body);
  8364. }
  8365. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8366. Headers headers;
  8367. headers.emplace("Accept-Encoding", "gzip, deflate");
  8368. auto res = cli_.Get("/streamed-chunked2", headers);
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. EXPECT_EQ(std::string("123456789"), res->body);
  8372. }
  8373. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8374. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8376. EXPECT_EQ(StatusCode::OK_200, res->status);
  8377. }
  8378. TEST(GzipDecompressor, ChunkedDecompression) {
  8379. std::string data;
  8380. for (size_t i = 0; i < 32 * 1024; ++i) {
  8381. data.push_back(static_cast<char>('a' + i % 26));
  8382. }
  8383. std::string compressed_data;
  8384. {
  8385. httplib::detail::gzip_compressor compressor;
  8386. bool result = compressor.compress(
  8387. data.data(), data.size(),
  8388. /*last=*/true,
  8389. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8390. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8391. compressed_data_size);
  8392. return true;
  8393. });
  8394. ASSERT_TRUE(result);
  8395. }
  8396. std::string decompressed_data;
  8397. {
  8398. httplib::detail::gzip_decompressor decompressor;
  8399. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8400. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8401. size_t chunk_size = 130;
  8402. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8403. chunk_begin += chunk_size) {
  8404. size_t current_chunk_size =
  8405. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8406. bool result = decompressor.decompress(
  8407. compressed_data.data() + chunk_begin, current_chunk_size,
  8408. [&](const char *decompressed_data_chunk,
  8409. size_t decompressed_data_chunk_size) {
  8410. decompressed_data.insert(decompressed_data.size(),
  8411. decompressed_data_chunk,
  8412. decompressed_data_chunk_size);
  8413. return true;
  8414. });
  8415. ASSERT_TRUE(result);
  8416. }
  8417. }
  8418. ASSERT_EQ(data, decompressed_data);
  8419. }
  8420. TEST(GzipDecompressor, DeflateDecompression) {
  8421. std::string original_text = "Raw deflate without gzip";
  8422. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8423. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8424. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8425. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8426. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8427. std::string decompressed_data;
  8428. {
  8429. httplib::detail::gzip_decompressor decompressor;
  8430. bool result = decompressor.decompress(
  8431. compressed_data.data(), compressed_data.size(),
  8432. [&](const char *decompressed_data_chunk,
  8433. size_t decompressed_data_chunk_size) {
  8434. decompressed_data.insert(decompressed_data.size(),
  8435. decompressed_data_chunk,
  8436. decompressed_data_chunk_size);
  8437. return true;
  8438. });
  8439. ASSERT_TRUE(result);
  8440. }
  8441. ASSERT_EQ(original_text, decompressed_data);
  8442. }
  8443. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8444. std::string original_text = "Raw deflate without gzip";
  8445. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8446. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8447. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8448. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8449. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8450. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8451. std::string decompressed_data;
  8452. {
  8453. httplib::detail::gzip_decompressor decompressor;
  8454. bool result = decompressor.decompress(
  8455. compressed_data.data(), compressed_data.size(),
  8456. [&](const char *decompressed_data_chunk,
  8457. size_t decompressed_data_chunk_size) {
  8458. decompressed_data.insert(decompressed_data.size(),
  8459. decompressed_data_chunk,
  8460. decompressed_data_chunk_size);
  8461. return true;
  8462. });
  8463. ASSERT_TRUE(result);
  8464. }
  8465. ASSERT_EQ(original_text, decompressed_data);
  8466. }
  8467. #endif
  8468. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8469. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8470. Headers headers;
  8471. headers.emplace("Accept-Encoding", "br");
  8472. auto res = cli_.Get("/streamed-chunked", headers);
  8473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8474. EXPECT_EQ(StatusCode::OK_200, res->status);
  8475. EXPECT_EQ(std::string("123456789"), res->body);
  8476. }
  8477. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8478. Headers headers;
  8479. headers.emplace("Accept-Encoding", "br");
  8480. auto res = cli_.Get("/streamed-chunked2", headers);
  8481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8482. EXPECT_EQ(StatusCode::OK_200, res->status);
  8483. EXPECT_EQ(std::string("123456789"), res->body);
  8484. }
  8485. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8486. cli_.set_compress(true);
  8487. auto res = cli_.Put(
  8488. "/put", 3,
  8489. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8490. sink.os << "PUT";
  8491. return true;
  8492. },
  8493. "text/plain");
  8494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8495. EXPECT_EQ(StatusCode::OK_200, res->status);
  8496. EXPECT_EQ("PUT", res->body);
  8497. }
  8498. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8499. cli_.set_compress(true);
  8500. auto res = cli_.Put(
  8501. "/put",
  8502. [](size_t /*offset*/, DataSink &sink) {
  8503. sink.os << "PUT";
  8504. sink.done();
  8505. return true;
  8506. },
  8507. "text/plain");
  8508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8509. EXPECT_EQ(StatusCode::OK_200, res->status);
  8510. EXPECT_EQ("PUT", res->body);
  8511. }
  8512. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8513. cli_.set_compress(true);
  8514. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8516. EXPECT_EQ(StatusCode::OK_200, res->status);
  8517. EXPECT_EQ(LARGE_DATA, res->body);
  8518. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8519. }
  8520. #endif
  8521. TEST_F(ServerTest, Patch) {
  8522. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8524. EXPECT_EQ(StatusCode::OK_200, res->status);
  8525. EXPECT_EQ("PATCH", res->body);
  8526. }
  8527. TEST_F(ServerTest, Delete) {
  8528. auto res = cli_.Delete("/delete");
  8529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8530. EXPECT_EQ(StatusCode::OK_200, res->status);
  8531. EXPECT_EQ("DELETE", res->body);
  8532. }
  8533. TEST_F(ServerTest, DeleteContentReceiver) {
  8534. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. EXPECT_EQ(StatusCode::OK_200, res->status);
  8537. EXPECT_EQ("content", res->body);
  8538. }
  8539. TEST_F(ServerTest, Options) {
  8540. auto res = cli_.Options("*");
  8541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8542. EXPECT_EQ(StatusCode::OK_200, res->status);
  8543. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8544. EXPECT_TRUE(res->body.empty());
  8545. }
  8546. TEST_F(ServerTest, URL) {
  8547. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8549. EXPECT_EQ(StatusCode::OK_200, res->status);
  8550. }
  8551. TEST_F(ServerTest, ArrayParam) {
  8552. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8554. EXPECT_EQ(StatusCode::OK_200, res->status);
  8555. }
  8556. TEST_F(ServerTest, ArrayParamValues) {
  8557. auto res =
  8558. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  8559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8560. EXPECT_EQ(StatusCode::OK_200, res->status);
  8561. }
  8562. TEST_F(ServerTest, NoMultipleHeaders) {
  8563. Headers headers = {{"Content-Length", "5"}};
  8564. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8565. "text/plain");
  8566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8567. EXPECT_EQ(StatusCode::OK_200, res->status);
  8568. }
  8569. TEST_F(ServerTest, PostContentReceiver) {
  8570. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8572. ASSERT_EQ(StatusCode::OK_200, res->status);
  8573. ASSERT_EQ("content", res->body);
  8574. }
  8575. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8576. UploadFormDataItems items = {
  8577. {"text1", "text default", "", ""},
  8578. {"text2", "aωb", "", ""},
  8579. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8580. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8581. {"file3", "", "", "application/octet-stream"},
  8582. };
  8583. auto res = cli_.Post("/content_receiver", items);
  8584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8585. EXPECT_EQ(StatusCode::OK_200, res->status);
  8586. }
  8587. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8588. UploadFormDataItems items = {
  8589. {"text1", "text default", "", ""},
  8590. {"text2", "aωb", "", ""},
  8591. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8592. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8593. {"file3", "", "", "application/octet-stream"},
  8594. };
  8595. auto boundary = std::string("+++++");
  8596. std::string body;
  8597. for (const auto &item : items) {
  8598. body += "--" + boundary + "\r\n";
  8599. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8600. if (!item.filename.empty()) {
  8601. body += "; filename=\"" + item.filename + "\"";
  8602. }
  8603. body += "\r\n";
  8604. if (!item.content_type.empty()) {
  8605. body += "Content-Type: " + item.content_type + "\r\n";
  8606. }
  8607. body += "\r\n";
  8608. body += item.content + "\r\n";
  8609. }
  8610. body += "--" + boundary + "--\r\n";
  8611. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8612. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8614. EXPECT_EQ(StatusCode::OK_200, res->status);
  8615. }
  8616. TEST(MultipartFormDataTest, FieldEscaping) {
  8617. Server svr;
  8618. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8619. const ContentReader &content_reader) {
  8620. ASSERT_TRUE(req.is_multipart_form_data());
  8621. std::vector<FormData> received;
  8622. content_reader(
  8623. [&](const FormData &file) {
  8624. received.push_back(file);
  8625. return true;
  8626. },
  8627. [&](const char *data, size_t data_length) {
  8628. received.back().content.append(data, data_length);
  8629. return true;
  8630. });
  8631. // '"', CR and LF in names and filenames are escaped following the
  8632. // WHATWG HTML standard, so each part still parses as a single part
  8633. // with no injected headers. Content types get CR/LF escaped too,
  8634. // while '"' (legal there, e.g. quoted charset) is preserved.
  8635. ASSERT_EQ(4U, received.size());
  8636. EXPECT_EQ("na%22me", received[0].name);
  8637. EXPECT_EQ("quoted name", received[0].content);
  8638. EXPECT_EQ("file", received[1].name);
  8639. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8640. received[1].filename);
  8641. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8642. EXPECT_EQ("injected", received[1].content);
  8643. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8644. EXPECT_EQ("my%22file.txt", received[2].filename);
  8645. EXPECT_EQ("cr lf name", received[2].content);
  8646. EXPECT_EQ("typed", received[3].name);
  8647. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8648. received[3].content_type);
  8649. EXPECT_EQ("typed content", received[3].content);
  8650. });
  8651. auto port = svr.bind_to_any_port("localhost");
  8652. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8653. auto se = detail::scope_exit([&] {
  8654. svr.stop();
  8655. t.join();
  8656. ASSERT_FALSE(svr.is_running());
  8657. });
  8658. svr.wait_until_ready();
  8659. Client cli("localhost", port);
  8660. UploadFormDataItems items = {
  8661. {"na\"me", "quoted name", "", ""},
  8662. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8663. "application/octet-stream"},
  8664. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8665. {"typed", "typed content", "",
  8666. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8667. };
  8668. auto res = cli.Post("/post", items);
  8669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8670. EXPECT_EQ(StatusCode::OK_200, res->status);
  8671. }
  8672. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8673. const UploadFormDataItems items = {
  8674. {"name1", "Content 1", "", ""},
  8675. {"name2", "Content 2", "file2.txt", "text/plain"},
  8676. };
  8677. Server svr;
  8678. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8679. const ContentReader &content_reader) {
  8680. ASSERT_TRUE(req.is_multipart_form_data());
  8681. std::vector<FormData> received;
  8682. content_reader(
  8683. [&](const FormData &file) {
  8684. received.push_back(file);
  8685. return true;
  8686. },
  8687. [&](const char *data, size_t data_length) {
  8688. received.back().content.append(data, data_length);
  8689. return true;
  8690. });
  8691. ASSERT_EQ(2U, received.size());
  8692. EXPECT_EQ("name1", received[0].name);
  8693. EXPECT_EQ("Content 1", received[0].content);
  8694. EXPECT_EQ("name2", received[1].name);
  8695. EXPECT_EQ("Content 2", received[1].content);
  8696. EXPECT_EQ("file2.txt", received[1].filename);
  8697. EXPECT_EQ("text/plain", received[1].content_type);
  8698. });
  8699. auto port = svr.bind_to_any_port("localhost");
  8700. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8701. auto se = detail::scope_exit([&] {
  8702. svr.stop();
  8703. t.join();
  8704. ASSERT_FALSE(svr.is_running());
  8705. });
  8706. svr.wait_until_ready();
  8707. Client cli("localhost", port);
  8708. // Whole-body serialization with a generated boundary
  8709. {
  8710. MultipartFormDataWriter writer;
  8711. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8712. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8713. writer.content_type());
  8714. auto body = writer.serialize(items);
  8715. EXPECT_EQ(body.size(), writer.content_length(items));
  8716. auto res = cli.Post("/post", body, writer.content_type());
  8717. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8718. EXPECT_EQ(StatusCode::OK_200, res->status);
  8719. }
  8720. // Per-part framing with a custom boundary via a content provider
  8721. {
  8722. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8723. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8724. MultipartFormDataWriter writer("custom-boundary_123");
  8725. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8726. std::string body;
  8727. for (const auto &item : items) {
  8728. body += writer.item_begin(item);
  8729. body += item.content;
  8730. body += MultipartFormDataWriter::item_end();
  8731. }
  8732. body += writer.finish();
  8733. EXPECT_EQ(body.size(), writer.content_length(items));
  8734. auto res = cli.Post(
  8735. "/post", body.size(),
  8736. [&](size_t offset, size_t length, DataSink &sink) {
  8737. sink.write(body.data() + offset, length);
  8738. return true;
  8739. },
  8740. writer.content_type());
  8741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8742. EXPECT_EQ(StatusCode::OK_200, res->status);
  8743. }
  8744. }
  8745. TEST_F(ServerTest, PostContentReceiverGzip) {
  8746. cli_.set_compress(true);
  8747. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8748. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8749. ASSERT_EQ(StatusCode::OK_200, res->status);
  8750. ASSERT_EQ("content", res->body);
  8751. }
  8752. TEST_F(ServerTest, PutContentReceiver) {
  8753. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8755. ASSERT_EQ(StatusCode::OK_200, res->status);
  8756. ASSERT_EQ("content", res->body);
  8757. }
  8758. TEST_F(ServerTest, PatchContentReceiver) {
  8759. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8761. ASSERT_EQ(StatusCode::OK_200, res->status);
  8762. ASSERT_EQ("content", res->body);
  8763. }
  8764. template <typename ClientType>
  8765. void TestWithHeadersAndContentReceiver(
  8766. ClientType &cli,
  8767. std::function<Result(ClientType &, const std::string &, const Headers &,
  8768. const std::string &, const std::string &,
  8769. ContentReceiver, DownloadProgress)>
  8770. request_func) {
  8771. Headers headers;
  8772. headers.emplace("X-Custom-Header", "test-value");
  8773. std::string received_body;
  8774. auto res = request_func(
  8775. cli, "/content_receiver", headers, "content", "application/json",
  8776. [&](const char *data, size_t data_length) {
  8777. received_body.append(data, data_length);
  8778. return true;
  8779. },
  8780. nullptr);
  8781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8782. EXPECT_EQ(StatusCode::OK_200, res->status);
  8783. EXPECT_EQ("content", received_body);
  8784. }
  8785. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8786. #ifdef CPPHTTPLIB_SSL_ENABLED
  8787. using ClientT = SSLClient;
  8788. #else
  8789. using ClientT = Client;
  8790. #endif
  8791. TestWithHeadersAndContentReceiver<ClientT>(
  8792. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8793. const std::string &body, const std::string &content_type,
  8794. ContentReceiver receiver, DownloadProgress progress) {
  8795. return cli.Post(path, headers, body, content_type, receiver, progress);
  8796. });
  8797. }
  8798. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8799. #ifdef CPPHTTPLIB_SSL_ENABLED
  8800. using ClientT = SSLClient;
  8801. #else
  8802. using ClientT = Client;
  8803. #endif
  8804. TestWithHeadersAndContentReceiver<ClientT>(
  8805. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8806. const std::string &body, const std::string &content_type,
  8807. ContentReceiver receiver, DownloadProgress progress) {
  8808. return cli.Put(path, headers, body, content_type, receiver, progress);
  8809. });
  8810. }
  8811. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8812. #ifdef CPPHTTPLIB_SSL_ENABLED
  8813. using ClientT = SSLClient;
  8814. #else
  8815. using ClientT = Client;
  8816. #endif
  8817. TestWithHeadersAndContentReceiver<ClientT>(
  8818. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8819. const std::string &body, const std::string &content_type,
  8820. ContentReceiver receiver, DownloadProgress progress) {
  8821. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8822. });
  8823. }
  8824. template <typename ClientType>
  8825. void TestWithHeadersAndContentReceiverWithProgress(
  8826. ClientType &cli,
  8827. std::function<Result(ClientType &, const std::string &, const Headers &,
  8828. const std::string &, const std::string &,
  8829. ContentReceiver, DownloadProgress)>
  8830. request_func) {
  8831. Headers headers;
  8832. headers.emplace("X-Test-Header", "progress-test");
  8833. std::string received_body;
  8834. auto progress_called = false;
  8835. auto res = request_func(
  8836. cli, "/content_receiver", headers, "content", "text/plain",
  8837. [&](const char *data, size_t data_length) {
  8838. received_body.append(data, data_length);
  8839. return true;
  8840. },
  8841. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8842. progress_called = true;
  8843. return true;
  8844. });
  8845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8846. EXPECT_EQ(StatusCode::OK_200, res->status);
  8847. EXPECT_EQ("content", received_body);
  8848. EXPECT_TRUE(progress_called);
  8849. }
  8850. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8851. #ifdef CPPHTTPLIB_SSL_ENABLED
  8852. using ClientT = SSLClient;
  8853. #else
  8854. using ClientT = Client;
  8855. #endif
  8856. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8857. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8858. const std::string &body, const std::string &content_type,
  8859. ContentReceiver receiver, DownloadProgress progress) {
  8860. return cli.Post(path, headers, body, content_type, receiver, progress);
  8861. });
  8862. }
  8863. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8864. #ifdef CPPHTTPLIB_SSL_ENABLED
  8865. using ClientT = SSLClient;
  8866. #else
  8867. using ClientT = Client;
  8868. #endif
  8869. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8870. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8871. const std::string &body, const std::string &content_type,
  8872. ContentReceiver receiver, DownloadProgress progress) {
  8873. return cli.Put(path, headers, body, content_type, receiver, progress);
  8874. });
  8875. }
  8876. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8877. #ifdef CPPHTTPLIB_SSL_ENABLED
  8878. using ClientT = SSLClient;
  8879. #else
  8880. using ClientT = Client;
  8881. #endif
  8882. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8883. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8884. const std::string &body, const std::string &content_type,
  8885. ContentReceiver receiver, DownloadProgress progress) {
  8886. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8887. });
  8888. }
  8889. template <typename ClientType>
  8890. void TestWithHeadersAndContentReceiverError(
  8891. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8892. const Headers &, const std::string &,
  8893. const std::string &, ContentReceiver)>
  8894. request_func) {
  8895. Headers headers;
  8896. headers.emplace("X-Error-Test", "true");
  8897. std::string received_body;
  8898. auto receiver_failed = false;
  8899. auto res =
  8900. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8901. [&](const char *data, size_t data_length) {
  8902. received_body.append(data, data_length);
  8903. receiver_failed = true;
  8904. return false;
  8905. });
  8906. ASSERT_FALSE(res);
  8907. EXPECT_TRUE(receiver_failed);
  8908. }
  8909. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8910. #ifdef CPPHTTPLIB_SSL_ENABLED
  8911. using ClientT = SSLClient;
  8912. #else
  8913. using ClientT = Client;
  8914. #endif
  8915. TestWithHeadersAndContentReceiverError<ClientT>(
  8916. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8917. const std::string &body, const std::string &content_type,
  8918. ContentReceiver receiver) {
  8919. return cli.Post(path, headers, body, content_type, receiver);
  8920. });
  8921. }
  8922. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8923. #ifdef CPPHTTPLIB_SSL_ENABLED
  8924. using ClientT = SSLClient;
  8925. #else
  8926. using ClientT = Client;
  8927. #endif
  8928. TestWithHeadersAndContentReceiverError<ClientT>(
  8929. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8930. const std::string &body, const std::string &content_type,
  8931. ContentReceiver receiver) {
  8932. return cli.Put(path, headers, body, content_type, receiver);
  8933. });
  8934. }
  8935. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8936. #ifdef CPPHTTPLIB_SSL_ENABLED
  8937. using ClientT = SSLClient;
  8938. #else
  8939. using ClientT = Client;
  8940. #endif
  8941. TestWithHeadersAndContentReceiverError<ClientT>(
  8942. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8943. const std::string &body, const std::string &content_type,
  8944. ContentReceiver receiver) {
  8945. return cli.Patch(path, headers, body, content_type, receiver);
  8946. });
  8947. }
  8948. TEST_F(ServerTest, PostQueryStringAndBody) {
  8949. auto res =
  8950. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8952. ASSERT_EQ(StatusCode::OK_200, res->status);
  8953. }
  8954. TEST_F(ServerTest, HTTP2Magic) {
  8955. Request req;
  8956. req.method = "PRI";
  8957. req.path = "*";
  8958. req.body = "SM";
  8959. auto res = std::make_shared<Response>();
  8960. auto error = Error::Success;
  8961. auto ret = cli_.send(req, *res, error);
  8962. ASSERT_TRUE(ret);
  8963. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8964. }
  8965. TEST_F(ServerTest, KeepAlive) {
  8966. auto res = cli_.Get("/hi");
  8967. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8968. EXPECT_EQ(StatusCode::OK_200, res->status);
  8969. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8970. EXPECT_EQ("Hello World!", res->body);
  8971. res = cli_.Get("/hi");
  8972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8973. EXPECT_EQ(StatusCode::OK_200, res->status);
  8974. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8975. EXPECT_EQ("Hello World!", res->body);
  8976. res = cli_.Get("/hi");
  8977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8978. EXPECT_EQ(StatusCode::OK_200, res->status);
  8979. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8980. EXPECT_EQ("Hello World!", res->body);
  8981. res = cli_.Get("/not-exist");
  8982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8983. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8984. res = cli_.Post("/empty", "", "text/plain");
  8985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8986. EXPECT_EQ(StatusCode::OK_200, res->status);
  8987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8988. EXPECT_EQ("empty", res->body);
  8989. EXPECT_EQ("close", res->get_header_value("Connection"));
  8990. res = cli_.Post(
  8991. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8992. "text/plain");
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8996. EXPECT_EQ("empty", res->body);
  8997. cli_.set_keep_alive(false);
  8998. res = cli_.Get("/last-request");
  8999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9000. EXPECT_EQ(StatusCode::OK_200, res->status);
  9001. EXPECT_EQ("close", res->get_header_value("Connection"));
  9002. }
  9003. TEST_F(ServerTest, TooManyRedirect) {
  9004. cli_.set_follow_location(true);
  9005. auto res = cli_.Get("/redirect/0");
  9006. ASSERT_TRUE(!res);
  9007. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  9008. }
  9009. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  9010. Request req;
  9011. req.method = "FOOBAR";
  9012. req.path = "/hi";
  9013. cli_.set_keep_alive(true);
  9014. auto res = cli_.send(req);
  9015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9016. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9017. EXPECT_EQ("close", res->get_header_value("Connection"));
  9018. EXPECT_FALSE(cli_.is_socket_open());
  9019. }
  9020. TEST_F(ServerTest, CustomRouteReadsBody) {
  9021. const std::string xml =
  9022. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  9023. Request req;
  9024. req.method = "PROPFIND";
  9025. req.path = "/dav/dir";
  9026. req.set_header("Depth", "1");
  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. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  9033. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  9034. }
  9035. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  9036. Request req;
  9037. req.method = "PROPFIND";
  9038. req.path = "/dav/42";
  9039. auto res = cli_.send(req);
  9040. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9041. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9042. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9043. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9044. }
  9045. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9046. Request req;
  9047. req.method = "PROPFIND";
  9048. req.path = "/dav-re/123";
  9049. auto res = cli_.send(req);
  9050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9051. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9052. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9053. }
  9054. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9055. Request req;
  9056. req.method = "MKCOL";
  9057. req.path = "/dav-mkcol";
  9058. auto res = cli_.send(req);
  9059. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9060. EXPECT_EQ(StatusCode::Created_201, res->status);
  9061. }
  9062. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9063. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9064. Request req;
  9065. req.method = "REPORT";
  9066. req.path = "/dav-report";
  9067. req.body = xml;
  9068. auto res = cli_.send(req);
  9069. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9070. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9071. EXPECT_EQ(xml, res->body);
  9072. }
  9073. // A content reader route must fire even when the request carries no body,
  9074. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9075. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9076. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9077. Request req;
  9078. req.method = "REPORT";
  9079. req.path = "/dav-report";
  9080. auto res = cli_.send(req);
  9081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9082. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9083. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9084. }
  9085. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9086. Request req;
  9087. req.method = "PROPFIND";
  9088. req.path = "/not-dav";
  9089. auto res = cli_.send(req);
  9090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9091. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9092. }
  9093. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9094. Request req;
  9095. req.method = "UNLOCK";
  9096. req.path = "/dav/dir";
  9097. cli_.set_keep_alive(true);
  9098. auto res = cli_.send(req);
  9099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9100. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9101. EXPECT_EQ("close", res->get_header_value("Connection"));
  9102. EXPECT_FALSE(cli_.is_socket_open());
  9103. }
  9104. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9105. // The mount point serves this path, but only for GET and HEAD.
  9106. auto get_res = cli_.Get("/dir/index.html");
  9107. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9108. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9109. Request req;
  9110. req.method = "PROPFIND";
  9111. req.path = "/dir/index.html";
  9112. auto res = cli_.send(req);
  9113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9114. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9115. }
  9116. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9117. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9118. cli_.set_keep_alive(true);
  9119. for (auto i = 0; i < 2; i++) {
  9120. Request req;
  9121. req.method = "PROPFIND";
  9122. req.path = "/dav/dir";
  9123. req.body = xml;
  9124. auto res = cli_.send(req);
  9125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9126. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9127. EXPECT_EQ(xml, res->body);
  9128. EXPECT_TRUE(cli_.is_socket_open());
  9129. }
  9130. // A built-in method must still be served on the same connection.
  9131. cli_.set_keep_alive(false);
  9132. auto res = cli_.Get("/hi");
  9133. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9134. EXPECT_EQ(StatusCode::OK_200, res->status);
  9135. EXPECT_EQ("close", res->get_header_value("Connection"));
  9136. }
  9137. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9138. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9139. Request req;
  9140. req.method = "PROPFIND";
  9141. req.path = "/dav/dir";
  9142. req.set_header("Expect", "100-continue");
  9143. req.body = xml;
  9144. auto res = cli_.send(req);
  9145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9146. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9147. EXPECT_EQ(xml, res->body);
  9148. }
  9149. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9150. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9151. TEST_F(ServerTest, Gzip) {
  9152. Headers headers;
  9153. headers.emplace("Accept-Encoding", "gzip, deflate");
  9154. auto res = cli_.Get("/compress", headers);
  9155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9156. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9157. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9158. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9159. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9160. "7890123456789012345678901234567890",
  9161. res->body);
  9162. EXPECT_EQ(StatusCode::OK_200, res->status);
  9163. }
  9164. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9165. Headers headers;
  9166. headers.emplace("Accept-Encoding", "gzip, deflate");
  9167. auto res = cli_.Get("/compress-with-charset", headers);
  9168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9169. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9170. EXPECT_EQ("application/json; charset=utf-8",
  9171. res->get_header_value("Content-Type"));
  9172. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9173. "7890123456789012345678901234567890",
  9174. res->body);
  9175. EXPECT_EQ(StatusCode::OK_200, res->status);
  9176. }
  9177. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9178. Headers headers;
  9179. headers.emplace("Accept-Encoding", "");
  9180. auto res = cli_.Get("/compress", headers);
  9181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9182. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9183. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9184. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9185. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9186. "7890123456789012345678901234567890",
  9187. res->body);
  9188. EXPECT_EQ(StatusCode::OK_200, res->status);
  9189. }
  9190. TEST_F(ServerTest, GzipWithContentReceiver) {
  9191. Headers headers;
  9192. headers.emplace("Accept-Encoding", "gzip, deflate");
  9193. std::string body;
  9194. auto res =
  9195. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9196. EXPECT_EQ(100U, data_length);
  9197. body.append(data, data_length);
  9198. return true;
  9199. });
  9200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9201. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9202. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9203. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9204. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9205. "7890123456789012345678901234567890",
  9206. body);
  9207. EXPECT_EQ(StatusCode::OK_200, res->status);
  9208. }
  9209. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9210. Headers headers;
  9211. headers.emplace("Accept-Encoding", "gzip, deflate");
  9212. cli_.set_decompress(false);
  9213. auto res = cli_.Get("/compress", headers);
  9214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9215. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9216. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9217. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9218. EXPECT_EQ(33U, res->body.size());
  9219. EXPECT_EQ(StatusCode::OK_200, res->status);
  9220. }
  9221. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9222. Headers headers;
  9223. headers.emplace("Accept-Encoding", "");
  9224. std::string body;
  9225. auto res =
  9226. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9227. EXPECT_EQ(100U, data_length);
  9228. body.append(data, data_length);
  9229. return true;
  9230. });
  9231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9232. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9233. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9234. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9235. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9236. "7890123456789012345678901234567890",
  9237. body);
  9238. EXPECT_EQ(StatusCode::OK_200, res->status);
  9239. }
  9240. TEST_F(ServerTest, NoGzip) {
  9241. Headers headers;
  9242. headers.emplace("Accept-Encoding", "gzip, deflate");
  9243. auto res = cli_.Get("/nocompress", headers);
  9244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9245. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9246. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9247. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9248. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9249. "7890123456789012345678901234567890",
  9250. res->body);
  9251. EXPECT_EQ(StatusCode::OK_200, res->status);
  9252. }
  9253. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9254. Headers headers;
  9255. headers.emplace("Accept-Encoding", "gzip, deflate");
  9256. std::string body;
  9257. auto res = cli_.Get("/nocompress", headers,
  9258. [&](const char *data, size_t data_length) {
  9259. EXPECT_EQ(100U, data_length);
  9260. body.append(data, data_length);
  9261. return true;
  9262. });
  9263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9264. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9265. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9266. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9267. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9268. "7890123456789012345678901234567890",
  9269. body);
  9270. EXPECT_EQ(StatusCode::OK_200, res->status);
  9271. }
  9272. TEST_F(ServerTest, MultipartFormDataGzip) {
  9273. UploadFormDataItems items = {
  9274. {"key1", "test", "", ""},
  9275. {"key2", "--abcdefg123", "", ""},
  9276. };
  9277. cli_.set_compress(true);
  9278. auto res = cli_.Post("/compress-multipart", items);
  9279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9280. EXPECT_EQ(StatusCode::OK_200, res->status);
  9281. }
  9282. #endif
  9283. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9284. // Static file compression is opt-in, so these run their own server rather than
  9285. // flipping it on for the shared ServerTest fixture, which would silently
  9286. // rewrite what every other static file test is asserting.
  9287. class StaticFileCompressionTest : public ::testing::Test {
  9288. protected:
  9289. void TearDown() override {
  9290. if (t_.joinable()) {
  9291. svr_.stop();
  9292. t_.join();
  9293. }
  9294. }
  9295. int start(const std::function<void(Server &)> &configure = nullptr) {
  9296. // Serves the same tree as a directory of build-time compressed assets
  9297. // would be served: the mount point names the coding the files are already
  9298. // stored in. Registered before "/" so it is the one that matches.
  9299. svr_.set_mount_point("/pre-encoded", "./www",
  9300. {{"Content-Encoding", "gzip"}});
  9301. svr_.set_mount_point("/", "./www");
  9302. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9303. res.set_file_content("./www/dir/index.html", "text/html");
  9304. });
  9305. svr_.Get("/pre-encoded-file-content",
  9306. [](const Request & /*req*/, Response &res) {
  9307. res.set_header("Content-Encoding", "gzip");
  9308. res.set_file_content("./www/dir/index.html", "text/html");
  9309. });
  9310. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9311. res.set_content_provider(
  9312. 6, "text/plain",
  9313. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9314. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9315. return true;
  9316. });
  9317. });
  9318. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9319. res.set_content_provider(
  9320. 1000, "text/plain",
  9321. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9322. if (offset < 100) {
  9323. std::string data(100, 'A');
  9324. sink.write(data.data(), data.size());
  9325. return true;
  9326. }
  9327. std::this_thread::sleep_for(std::chrono::seconds(2));
  9328. std::string data(900, 'B');
  9329. sink.write(data.data(), data.size());
  9330. return true;
  9331. });
  9332. });
  9333. if (configure) { configure(svr_); }
  9334. auto port = svr_.bind_to_any_port(HOST);
  9335. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9336. svr_.wait_until_ready();
  9337. return port;
  9338. }
  9339. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9340. // Every file under ./www except 1MB.txt is smaller than the default
  9341. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9342. // it out of the way.
  9343. static void enable_without_floor(Server &svr) {
  9344. svr.set_static_file_compression(true);
  9345. svr.set_static_file_compression_min_length(0);
  9346. }
  9347. Server svr_;
  9348. std::thread t_;
  9349. };
  9350. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9351. auto port = start();
  9352. Client cli(HOST, port);
  9353. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9355. EXPECT_EQ(StatusCode::OK_200, res->status);
  9356. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9357. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9358. EXPECT_EQ(1048576U, res->body.size());
  9359. }
  9360. TEST_F(StaticFileCompressionTest, MountPoint) {
  9361. auto port = start(enable);
  9362. Client cli(HOST, port);
  9363. cli.set_decompress(false);
  9364. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9366. EXPECT_EQ(StatusCode::OK_200, res->status);
  9367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9368. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9369. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9370. // The response stays self-delimiting: a length, not a chunked body.
  9371. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9372. EXPECT_EQ(std::to_string(res->body.size()),
  9373. res->get_header_value("Content-Length"));
  9374. EXPECT_LT(res->body.size(), 1048576U);
  9375. EXPECT_FALSE(res->body.empty());
  9376. }
  9377. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9378. auto port = start(enable);
  9379. Client cli(HOST, port);
  9380. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9382. EXPECT_EQ(StatusCode::OK_200, res->status);
  9383. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9384. EXPECT_EQ(1048576U, res->body.size());
  9385. }
  9386. TEST_F(StaticFileCompressionTest, FileContent) {
  9387. auto port = start(enable_without_floor);
  9388. Client cli(HOST, port);
  9389. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9391. EXPECT_EQ(StatusCode::OK_200, res->status);
  9392. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9393. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9394. EXPECT_EQ(104U, res->body.size());
  9395. }
  9396. // A handler that serves an already-encoded file names the coding itself. The
  9397. // file-backed path decided its coding from Accept-Encoding and the content
  9398. // type alone, so it compressed the stored bytes a second time and appended a
  9399. // second Content-Encoding field line.
  9400. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9401. auto port = start(enable_without_floor);
  9402. Client cli(HOST, port);
  9403. cli.set_decompress(false);
  9404. auto res = cli.Get("/pre-encoded-file-content",
  9405. Headers{{"Accept-Encoding", "gzip"}});
  9406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9407. EXPECT_EQ(StatusCode::OK_200, res->status);
  9408. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9409. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9410. // Vary belongs to a coding the server chose, and it chose none here.
  9411. EXPECT_FALSE(res->has_header("Vary"));
  9412. // The file travels exactly as it is stored on disk.
  9413. EXPECT_EQ(104U, res->body.size());
  9414. }
  9415. // The 1MB file clears the default floor, so this one runs the configuration a
  9416. // deployment would actually have.
  9417. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9418. auto port = start(enable);
  9419. Client cli(HOST, port);
  9420. cli.set_decompress(false);
  9421. auto res =
  9422. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9423. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9424. EXPECT_EQ(StatusCode::OK_200, res->status);
  9425. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9426. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9427. EXPECT_FALSE(res->has_header("Vary"));
  9428. EXPECT_EQ(1048576U, res->body.size());
  9429. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9430. }
  9431. TEST_F(StaticFileCompressionTest, Head) {
  9432. auto port = start(enable);
  9433. Client cli(HOST, port);
  9434. cli.set_decompress(false);
  9435. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9436. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9437. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9439. EXPECT_EQ(StatusCode::OK_200, res->status);
  9440. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9441. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9442. // HEAD still reports the size a GET would return.
  9443. EXPECT_EQ(get->get_header_value("Content-Length"),
  9444. res->get_header_value("Content-Length"));
  9445. EXPECT_TRUE(res->body.empty());
  9446. }
  9447. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9448. auto port = start(enable);
  9449. Client cli(HOST, port);
  9450. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9451. {"Accept-Encoding", "gzip"}});
  9452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9453. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9454. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9455. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9456. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9457. EXPECT_EQ("cd", res->body);
  9458. }
  9459. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9460. auto port = start(enable);
  9461. Client cli(HOST, port);
  9462. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9464. EXPECT_EQ(StatusCode::OK_200, res->status);
  9465. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9466. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9467. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9468. }
  9469. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9470. auto port = start(enable);
  9471. Client cli(HOST, port);
  9472. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9474. EXPECT_EQ(StatusCode::OK_200, res->status);
  9475. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9476. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9477. EXPECT_TRUE(res->body.empty());
  9478. }
  9479. TEST_F(StaticFileCompressionTest, MinLength) {
  9480. auto port = start(enable);
  9481. Client cli(HOST, port);
  9482. // 104 bytes, well under the default floor. Compressing it would add the
  9483. // gzip header and trailer to a body that already fits in one packet.
  9484. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9485. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9486. EXPECT_EQ(StatusCode::OK_200, res->status);
  9487. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9488. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9489. }
  9490. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9491. auto port = start([](Server &svr) {
  9492. svr.set_static_file_compression(true);
  9493. svr.set_static_file_compression_min_length(1);
  9494. });
  9495. Client cli(HOST, port);
  9496. cli.set_decompress(false);
  9497. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9498. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9499. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9500. // A 9-byte file comes back larger than it went in, because gzip's header and
  9501. // trailer outweigh anything deflate can save. That is the end of the range
  9502. // the floor exists to keep out.
  9503. EXPECT_GT(res->body.size(), 9U);
  9504. }
  9505. TEST_F(StaticFileCompressionTest, MaxLength) {
  9506. auto port = start([](Server &svr) {
  9507. svr.set_static_file_compression(true);
  9508. svr.set_static_file_compression_min_length(0);
  9509. svr.set_static_file_compression_max_length(1024);
  9510. });
  9511. Client cli(HOST, port);
  9512. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9513. // defines `small` as a macro on Windows.
  9514. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9515. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9516. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9517. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9518. // Under it: compressed.
  9519. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9520. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9521. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9522. }
  9523. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9524. auto port = start(enable_without_floor);
  9525. Client cli(HOST, port);
  9526. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9527. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9528. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9529. auto identity_etag = identity->get_header_value("ETag");
  9530. ASSERT_FALSE(identity_etag.empty());
  9531. auto gzipped =
  9532. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9533. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9534. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9535. auto gzip_etag = gzipped->get_header_value("ETag");
  9536. ASSERT_FALSE(gzip_etag.empty());
  9537. // Two representations, two validators.
  9538. EXPECT_NE(identity_etag, gzip_etag);
  9539. // Each one revalidates against the request that would produce it...
  9540. auto fresh =
  9541. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9542. {"If-None-Match", gzip_etag}});
  9543. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9544. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9545. auto fresh_identity =
  9546. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9547. {"If-None-Match", identity_etag}});
  9548. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9549. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9550. // ...and not against the other representation.
  9551. auto crossed =
  9552. cli.Get("/dir/index.html",
  9553. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9554. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9555. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9556. }
  9557. // The opt-in covers responses the server reads off disk itself. A caller's own
  9558. // known-length provider keeps its Content-Length and, more importantly, keeps
  9559. // delivering incrementally: routing it through a compressor would hold every
  9560. // write back until zlib's window filled.
  9561. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9562. auto port = start(enable);
  9563. Client cli(HOST, port);
  9564. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9566. EXPECT_EQ(StatusCode::OK_200, res->status);
  9567. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9568. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9569. EXPECT_EQ("aaabbb", res->body);
  9570. }
  9571. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9572. auto port = start(enable);
  9573. Client cli(HOST, port);
  9574. cli.set_read_timeout(1, 0);
  9575. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9576. Headers{{"Accept-Encoding", "gzip"}});
  9577. ASSERT_TRUE(handle.is_valid());
  9578. // The provider writes 100 bytes and then stalls for longer than the read
  9579. // timeout. Those first bytes have to arrive anyway: run the response through
  9580. // a compressor and zlib holds them until its window fills, so the read would
  9581. // come back empty instead.
  9582. char buf[256];
  9583. auto n = handle.read(buf, sizeof(buf));
  9584. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9585. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9586. }
  9587. #endif
  9588. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9589. TEST_F(ServerTest, Brotli) {
  9590. Headers headers;
  9591. headers.emplace("Accept-Encoding", "br");
  9592. auto res = cli_.Get("/compress", headers);
  9593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9594. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9595. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9596. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9597. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9598. "7890123456789012345678901234567890",
  9599. res->body);
  9600. EXPECT_EQ(StatusCode::OK_200, res->status);
  9601. }
  9602. #endif
  9603. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9604. TEST_F(ServerTest, Zstd) {
  9605. Headers headers;
  9606. headers.emplace("Accept-Encoding", "zstd");
  9607. auto res = cli_.Get("/compress", headers);
  9608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9609. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9610. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9611. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9612. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9613. "7890123456789012345678901234567890",
  9614. res->body);
  9615. EXPECT_EQ(StatusCode::OK_200, res->status);
  9616. }
  9617. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9618. Headers headers;
  9619. headers.emplace("Accept-Encoding", "");
  9620. auto res = cli_.Get("/compress", headers);
  9621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9622. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9623. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9624. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9625. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9626. "7890123456789012345678901234567890",
  9627. res->body);
  9628. EXPECT_EQ(StatusCode::OK_200, res->status);
  9629. }
  9630. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9631. Headers headers;
  9632. headers.emplace("Accept-Encoding", "zstd");
  9633. std::string body;
  9634. auto res =
  9635. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9636. EXPECT_EQ(100U, data_length);
  9637. body.append(data, data_length);
  9638. return true;
  9639. });
  9640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9641. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9642. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9643. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9644. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9645. "7890123456789012345678901234567890",
  9646. body);
  9647. EXPECT_EQ(StatusCode::OK_200, res->status);
  9648. }
  9649. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9650. Headers headers;
  9651. headers.emplace("Accept-Encoding", "zstd");
  9652. cli_.set_decompress(false);
  9653. auto res = cli_.Get("/compress", headers);
  9654. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9655. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9656. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9657. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9659. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9660. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9661. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9662. EXPECT_EQ(StatusCode::OK_200, res->status);
  9663. ASSERT_EQ(26U, res->body.size());
  9664. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9665. 0);
  9666. }
  9667. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9668. Headers headers;
  9669. headers.emplace("Accept-Encoding", "");
  9670. std::string body;
  9671. auto res =
  9672. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9673. EXPECT_EQ(100U, data_length);
  9674. body.append(data, data_length);
  9675. return true;
  9676. });
  9677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9678. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9679. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9680. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9681. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9682. "7890123456789012345678901234567890",
  9683. body);
  9684. EXPECT_EQ(StatusCode::OK_200, res->status);
  9685. }
  9686. TEST_F(ServerTest, NoZstd) {
  9687. Headers headers;
  9688. headers.emplace("Accept-Encoding", "zstd");
  9689. auto res = cli_.Get("/nocompress", headers);
  9690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9691. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9692. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9693. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9694. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9695. "7890123456789012345678901234567890",
  9696. res->body);
  9697. EXPECT_EQ(StatusCode::OK_200, res->status);
  9698. }
  9699. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9700. Headers headers;
  9701. headers.emplace("Accept-Encoding", "zstd");
  9702. std::string body;
  9703. auto res = cli_.Get("/nocompress", headers,
  9704. [&](const char *data, size_t data_length) {
  9705. EXPECT_EQ(100U, data_length);
  9706. body.append(data, data_length);
  9707. return true;
  9708. });
  9709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9710. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9711. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9712. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9713. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9714. "7890123456789012345678901234567890",
  9715. body);
  9716. EXPECT_EQ(StatusCode::OK_200, res->status);
  9717. }
  9718. // TODO: How to enable zstd ??
  9719. TEST_F(ServerTest, MultipartFormDataZstd) {
  9720. UploadFormDataItems items = {
  9721. {"key1", "test", "", ""},
  9722. {"key2", "--abcdefg123", "", ""},
  9723. };
  9724. Headers headers;
  9725. headers.emplace("Accept-Encoding", "zstd");
  9726. cli_.set_compress(true);
  9727. auto res = cli_.Post("/compress-multipart", headers, items);
  9728. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9729. EXPECT_EQ(StatusCode::OK_200, res->status);
  9730. }
  9731. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9732. Headers headers;
  9733. headers.emplace("Accept-Encoding", "zstd");
  9734. cli_.set_compress(true);
  9735. auto res = cli_.Put(
  9736. "/put", headers, 3,
  9737. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9738. sink.os << "PUT";
  9739. return true;
  9740. },
  9741. "text/plain");
  9742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9743. EXPECT_EQ(StatusCode::OK_200, res->status);
  9744. EXPECT_EQ("PUT", res->body);
  9745. }
  9746. // Pre-compression logging tests
  9747. TEST_F(ServerTest, PreCompressionLogging) {
  9748. // Test data for compression (matches the actual /compress endpoint content)
  9749. const std::string test_content =
  9750. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9751. "3456789012345678901234567890";
  9752. // Variables to capture logging data
  9753. std::string pre_compression_body;
  9754. std::string pre_compression_content_type;
  9755. std::string pre_compression_content_encoding;
  9756. std::string post_compression_body;
  9757. std::string post_compression_content_type;
  9758. std::string post_compression_content_encoding;
  9759. // Set up pre-compression logger
  9760. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9761. const Response &res) {
  9762. pre_compression_body = res.body;
  9763. pre_compression_content_type = res.get_header_value("Content-Type");
  9764. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9765. });
  9766. // Set up post-compression logger
  9767. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9768. post_compression_body = res.body;
  9769. post_compression_content_type = res.get_header_value("Content-Type");
  9770. post_compression_content_encoding =
  9771. res.get_header_value("Content-Encoding");
  9772. });
  9773. // Test with gzip compression
  9774. Headers headers;
  9775. headers.emplace("Accept-Encoding", "gzip");
  9776. auto res = cli_.Get("/compress", headers);
  9777. // Verify response was compressed
  9778. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9779. EXPECT_EQ(StatusCode::OK_200, res->status);
  9780. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9781. // Verify pre-compression logger captured uncompressed content
  9782. EXPECT_EQ(test_content, pre_compression_body);
  9783. EXPECT_EQ("text/plain", pre_compression_content_type);
  9784. EXPECT_TRUE(pre_compression_content_encoding
  9785. .empty()); // No encoding header before compression
  9786. // Verify post-compression logger captured compressed content
  9787. EXPECT_NE(test_content,
  9788. post_compression_body); // Should be different after compression
  9789. EXPECT_EQ("text/plain", post_compression_content_type);
  9790. EXPECT_EQ("gzip", post_compression_content_encoding);
  9791. // Verify compressed content is smaller
  9792. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9793. }
  9794. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9795. const std::string test_content =
  9796. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9797. "3456789012345678901234567890";
  9798. std::string pre_compression_body;
  9799. std::string post_compression_body;
  9800. svr_.set_pre_compression_logger(
  9801. [&](const Request & /*req*/, const Response &res) {
  9802. pre_compression_body = res.body;
  9803. });
  9804. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9805. post_compression_body = res.body;
  9806. });
  9807. Headers headers;
  9808. headers.emplace("Accept-Encoding", "br");
  9809. auto res = cli_.Get("/compress", headers);
  9810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9811. EXPECT_EQ(StatusCode::OK_200, res->status);
  9812. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9813. // Verify pre-compression content is uncompressed
  9814. EXPECT_EQ(test_content, pre_compression_body);
  9815. // Verify post-compression content is compressed
  9816. EXPECT_NE(test_content, post_compression_body);
  9817. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9818. }
  9819. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9820. const std::string test_content =
  9821. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9822. "3456789012345678901234567890";
  9823. std::string pre_compression_body;
  9824. std::string post_compression_body;
  9825. svr_.set_pre_compression_logger(
  9826. [&](const Request & /*req*/, const Response &res) {
  9827. pre_compression_body = res.body;
  9828. });
  9829. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9830. post_compression_body = res.body;
  9831. });
  9832. // Request without compression (use /nocompress endpoint)
  9833. Headers headers;
  9834. auto res = cli_.Get("/nocompress", headers);
  9835. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9836. EXPECT_EQ(StatusCode::OK_200, res->status);
  9837. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9838. // Pre-compression logger should not be called when no compression is applied
  9839. EXPECT_TRUE(
  9840. pre_compression_body.empty()); // Pre-compression logger not called
  9841. EXPECT_EQ(
  9842. test_content,
  9843. post_compression_body); // Post-compression logger captures final content
  9844. }
  9845. TEST_F(ServerTest, LoggerSeesContentLength) {
  9846. size_t logged_content_length = 0;
  9847. std::string logged_content_length_header;
  9848. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9849. logged_content_length = res.content_length_;
  9850. logged_content_length_header = res.get_header_value("Content-Length");
  9851. });
  9852. auto res = cli_.Get("/nocompress");
  9853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9854. EXPECT_EQ(StatusCode::OK_200, res->status);
  9855. EXPECT_EQ(res->body.size(), logged_content_length);
  9856. EXPECT_EQ(std::to_string(logged_content_length),
  9857. logged_content_length_header);
  9858. }
  9859. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9860. const std::string test_content =
  9861. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9862. "3456789012345678901234567890";
  9863. std::string pre_compression_body;
  9864. bool pre_logger_called = false;
  9865. // Set only pre-compression logger
  9866. svr_.set_pre_compression_logger(
  9867. [&](const Request & /*req*/, const Response &res) {
  9868. pre_compression_body = res.body;
  9869. pre_logger_called = true;
  9870. });
  9871. Headers headers;
  9872. headers.emplace("Accept-Encoding", "gzip");
  9873. auto res = cli_.Get("/compress", headers);
  9874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9875. EXPECT_EQ(StatusCode::OK_200, res->status);
  9876. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9877. // Verify pre-compression logger was called
  9878. EXPECT_TRUE(pre_logger_called);
  9879. EXPECT_EQ(test_content, pre_compression_body);
  9880. }
  9881. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9882. {
  9883. // Test with Expect: 100-continue header - success case
  9884. // Server returns 100 Continue, client sends body, server returns 200 OK
  9885. Request req;
  9886. req.method = "POST";
  9887. req.path = "/post-large";
  9888. req.set_header("Expect", "100-continue");
  9889. req.body = LARGE_DATA;
  9890. Response res;
  9891. auto error = Error::Success;
  9892. cli_.set_keep_alive(true);
  9893. auto ret = cli_.send(req, res, error);
  9894. EXPECT_TRUE(ret);
  9895. EXPECT_EQ(StatusCode::OK_200, res.status);
  9896. EXPECT_EQ(LARGE_DATA, res.body);
  9897. }
  9898. {
  9899. // Test with Expect: 100-continue header - error case
  9900. // Client should not send the body when server returns an error
  9901. Request req;
  9902. req.method = "POST";
  9903. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9904. req.set_header("Expect", "100-continue");
  9905. req.body = LARGE_DATA;
  9906. Response res;
  9907. auto error = Error::Success;
  9908. auto start = std::chrono::high_resolution_clock::now();
  9909. cli_.set_keep_alive(true);
  9910. auto ret = cli_.send(req, res, error);
  9911. auto end = std::chrono::high_resolution_clock::now();
  9912. auto elapsed =
  9913. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9914. .count();
  9915. // With Expect: 100-continue, request completes successfully but with error
  9916. EXPECT_TRUE(ret);
  9917. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9918. EXPECT_EQ("close", res.get_header_value("Connection"));
  9919. EXPECT_FALSE(cli_.is_socket_open());
  9920. EXPECT_LE(elapsed, 2000);
  9921. }
  9922. {
  9923. // Send an extra GET request to ensure error recovery without hanging
  9924. Request req;
  9925. req.method = "GET";
  9926. req.path = "/hi";
  9927. auto start = std::chrono::high_resolution_clock::now();
  9928. auto res = cli_.send(req);
  9929. auto end = std::chrono::high_resolution_clock::now();
  9930. auto elapsed =
  9931. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9932. .count();
  9933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9934. EXPECT_EQ(StatusCode::OK_200, res->status);
  9935. EXPECT_EQ("Hello World!", res->body);
  9936. EXPECT_LE(elapsed, 500);
  9937. }
  9938. }
  9939. TEST(ZstdDecompressor, ChunkedDecompression) {
  9940. std::string data;
  9941. for (size_t i = 0; i < 32 * 1024; ++i) {
  9942. data.push_back(static_cast<char>('a' + i % 26));
  9943. }
  9944. std::string compressed_data;
  9945. {
  9946. httplib::detail::zstd_compressor compressor;
  9947. bool result = compressor.compress(
  9948. data.data(), data.size(),
  9949. /*last=*/true,
  9950. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9951. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9952. compressed_data_size);
  9953. return true;
  9954. });
  9955. ASSERT_TRUE(result);
  9956. }
  9957. std::string decompressed_data;
  9958. {
  9959. httplib::detail::zstd_decompressor decompressor;
  9960. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9961. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9962. size_t chunk_size = 130;
  9963. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9964. chunk_begin += chunk_size) {
  9965. size_t current_chunk_size =
  9966. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9967. bool result = decompressor.decompress(
  9968. compressed_data.data() + chunk_begin, current_chunk_size,
  9969. [&](const char *decompressed_data_chunk,
  9970. size_t decompressed_data_chunk_size) {
  9971. decompressed_data.insert(decompressed_data.size(),
  9972. decompressed_data_chunk,
  9973. decompressed_data_chunk_size);
  9974. return true;
  9975. });
  9976. ASSERT_TRUE(result);
  9977. }
  9978. }
  9979. ASSERT_EQ(data, decompressed_data);
  9980. }
  9981. TEST(ZstdDecompressor, Decompress) {
  9982. std::string original_text = "Compressed with ZSTD";
  9983. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9984. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9985. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9986. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9987. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9988. std::string decompressed_data;
  9989. {
  9990. httplib::detail::zstd_decompressor decompressor;
  9991. bool result = decompressor.decompress(
  9992. compressed_data.data(), compressed_data.size(),
  9993. [&](const char *decompressed_data_chunk,
  9994. size_t decompressed_data_chunk_size) {
  9995. decompressed_data.insert(decompressed_data.size(),
  9996. decompressed_data_chunk,
  9997. decompressed_data_chunk_size);
  9998. return true;
  9999. });
  10000. ASSERT_TRUE(result);
  10001. }
  10002. ASSERT_EQ(original_text, decompressed_data);
  10003. }
  10004. #endif
  10005. // Sends a raw request to a server listening at HOST:PORT, writing it in
  10006. // separate chunks so that the server sees each part in its own read(). Used to
  10007. // place a read boundary at a specific offset of a request body.
  10008. static bool send_request_in_parts(time_t read_timeout_sec,
  10009. const std::vector<std::string> &parts,
  10010. std::string *resp = nullptr,
  10011. int port = PORT) {
  10012. auto error = Error::Success;
  10013. auto client_sock = detail::create_client_socket(
  10014. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10015. /*connection_timeout_sec=*/5, 0,
  10016. /*read_timeout_sec=*/5, 0,
  10017. /*write_timeout_sec=*/5, 0, std::string(), error);
  10018. if (client_sock == INVALID_SOCKET) { return false; }
  10019. auto ret = detail::process_client_socket(
  10020. client_sock, read_timeout_sec, 0, 0, 0, 0,
  10021. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  10022. for (size_t i = 0; i < parts.size(); i++) {
  10023. const auto &part = parts[i];
  10024. if (part.size() !=
  10025. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  10026. return false;
  10027. }
  10028. if (i + 1 < parts.size()) {
  10029. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10030. }
  10031. }
  10032. char buf[512];
  10033. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  10034. while (line_reader.getline()) {
  10035. if (resp) { *resp += line_reader.ptr(); }
  10036. }
  10037. return true;
  10038. });
  10039. detail::close_socket(client_sock);
  10040. return ret;
  10041. }
  10042. // Sends a raw request to a server listening at HOST:PORT.
  10043. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10044. std::string *resp = nullptr, int port = PORT) {
  10045. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10046. }
  10047. #ifdef CPPHTTPLIB_SSL_ENABLED
  10048. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10049. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10050. ASSERT_TRUE(svr.is_valid());
  10051. svr.set_read_timeout(1, 0);
  10052. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10053. auto se = detail::scope_exit([&] {
  10054. svr.stop();
  10055. t.join();
  10056. ASSERT_FALSE(svr.is_running());
  10057. });
  10058. svr.wait_until_ready();
  10059. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10060. // keeps each wait well within the read timeout. The server gives up a
  10061. // second in, so the bytes sent after that fail.
  10062. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10063. parts.resize(26, std::string(1, '\0'));
  10064. EXPECT_FALSE(send_request_in_parts(5, parts));
  10065. }
  10066. #endif
  10067. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10068. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10069. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10070. const std::vector<std::string> &parts,
  10071. std::string *resp = nullptr,
  10072. int port = PORT) {
  10073. auto error = Error::Success;
  10074. auto sock = detail::create_client_socket(
  10075. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10076. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10077. /*write_timeout_sec=*/5, 0, std::string(), error);
  10078. if (sock == INVALID_SOCKET) { return false; }
  10079. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10080. auto ctx = SSL_CTX_new(TLS_client_method());
  10081. auto ssl = SSL_new(ctx);
  10082. auto ssl_se = detail::scope_exit([&] {
  10083. SSL_free(ssl);
  10084. SSL_CTX_free(ctx);
  10085. });
  10086. SSL_set_fd(ssl, static_cast<int>(sock));
  10087. if (SSL_connect(ssl) != 1) { return false; }
  10088. for (size_t i = 0; i < parts.size(); i++) {
  10089. const auto &part = parts[i];
  10090. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10091. static_cast<int>(part.size())) {
  10092. return false;
  10093. }
  10094. if (i + 1 < parts.size()) {
  10095. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10096. }
  10097. }
  10098. char buf[512];
  10099. int n;
  10100. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10101. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10102. }
  10103. return true;
  10104. }
  10105. #endif
  10106. // The request line, then a header value a byte at a time.
  10107. static std::vector<std::string> slow_request_head_parts() {
  10108. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10109. parts.resize(26, "a");
  10110. parts.emplace_back("\r\n\r\n");
  10111. return parts;
  10112. }
  10113. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10114. // within the one-second read timeout. The server gives up a second in, before
  10115. // the head is complete.
  10116. static void
  10117. expect_slow_request_head_dropped(Server &svr,
  10118. const std::function<std::string()> &send) {
  10119. std::atomic<bool> handled(false);
  10120. svr.Get("/", [&](const Request &, Response &res) {
  10121. handled = true;
  10122. res.set_content("ok", "text/plain");
  10123. });
  10124. svr.set_read_timeout(1, 0);
  10125. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10126. auto se = detail::scope_exit([&] {
  10127. svr.stop();
  10128. t.join();
  10129. ASSERT_FALSE(svr.is_running());
  10130. });
  10131. svr.wait_until_ready();
  10132. auto resp = send();
  10133. EXPECT_FALSE(handled);
  10134. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10135. }
  10136. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10137. Server svr;
  10138. expect_slow_request_head_dropped(svr, [] {
  10139. std::string resp;
  10140. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10141. return resp;
  10142. });
  10143. }
  10144. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10145. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10146. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10147. ASSERT_TRUE(svr.is_valid());
  10148. expect_slow_request_head_dropped(svr, [] {
  10149. std::string resp;
  10150. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10151. return resp;
  10152. });
  10153. }
  10154. #endif
  10155. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10156. Server svr;
  10157. std::string header_value;
  10158. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10159. header_value = req.get_header_value("foo");
  10160. res.set_content("ok", "text/plain");
  10161. });
  10162. thread t = thread([&] { svr.listen(HOST, PORT); });
  10163. auto se = detail::scope_exit([&] {
  10164. svr.stop();
  10165. t.join();
  10166. ASSERT_FALSE(svr.is_running());
  10167. });
  10168. svr.wait_until_ready();
  10169. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10170. // like characters are not treated the same - use vertical tab and escape.
  10171. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10172. "foo: \t \v bar \x1B\t \r\n"
  10173. "Connection: close\r\n"
  10174. "\r\n";
  10175. std::string res;
  10176. ASSERT_TRUE(send_request(5, req, &res));
  10177. EXPECT_EQ(header_value, "");
  10178. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10179. }
  10180. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10181. Server svr;
  10182. std::string received;
  10183. svr.Get("/order", [&](const Request &req, Response &res) {
  10184. received = entries_to_string(req.headers);
  10185. res.set_content("ok", "text/plain");
  10186. });
  10187. auto port = svr.bind_to_any_port(HOST);
  10188. thread t = thread([&] { svr.listen_after_bind(); });
  10189. auto se = detail::scope_exit([&] {
  10190. svr.stop();
  10191. t.join();
  10192. ASSERT_FALSE(svr.is_running());
  10193. });
  10194. svr.wait_until_ready();
  10195. const std::string req = "GET /order HTTP/1.1\r\n"
  10196. "Host: localhost\r\n"
  10197. "X-First: 1\r\n"
  10198. "X-Dup: a\r\n"
  10199. "X-Second: 2\r\n"
  10200. "X-Dup: b\r\n"
  10201. "Connection: close\r\n"
  10202. "\r\n";
  10203. std::string res;
  10204. ASSERT_TRUE(send_request(5, req, &res, port));
  10205. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10206. EXPECT_EQ(
  10207. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10208. received);
  10209. }
  10210. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10211. Server svr;
  10212. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10213. res.set_header("Set-Cookie", "first=1");
  10214. res.set_header("X-Between", "y");
  10215. res.set_header("Set-Cookie", "second=2");
  10216. res.set_content("ok", "text/plain");
  10217. });
  10218. auto port = svr.bind_to_any_port(HOST);
  10219. thread t = thread([&] { svr.listen_after_bind(); });
  10220. auto se = detail::scope_exit([&] {
  10221. svr.stop();
  10222. t.join();
  10223. ASSERT_FALSE(svr.is_running());
  10224. });
  10225. svr.wait_until_ready();
  10226. Client cli(HOST, port);
  10227. auto res = cli.Get("/cookies");
  10228. ASSERT_TRUE(res);
  10229. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10230. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10231. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10232. }
  10233. // A stream may send a byte at a time with a small extension on each chunk,
  10234. // however long it runs
  10235. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10236. Server svr;
  10237. svr.Post("/count", [](const Request &req, Response &res) {
  10238. res.set_content(std::to_string(req.body.size()), "text/plain");
  10239. });
  10240. auto port = svr.bind_to_any_port(HOST);
  10241. ASSERT_LT(0, port);
  10242. thread t = thread([&] { svr.listen_after_bind(); });
  10243. auto se = detail::scope_exit([&] {
  10244. svr.stop();
  10245. t.join();
  10246. ASSERT_FALSE(svr.is_running());
  10247. });
  10248. svr.wait_until_ready();
  10249. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10250. "\r\nTransfer-Encoding: chunked\r\n"
  10251. "Connection: close\r\n\r\n";
  10252. for (auto i = 0; i < 4096; i++) {
  10253. req += "1;a=b\r\nx\r\n";
  10254. }
  10255. req += "0\r\n\r\n";
  10256. std::string res;
  10257. ASSERT_TRUE(send_request(5, req, &res, port));
  10258. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10259. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10260. }
  10261. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10262. Server svr;
  10263. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10264. auto i = new int(0);
  10265. res.set_header("Trailer", "X-Safe, X-Reflected");
  10266. res.set_chunked_content_provider(
  10267. "text/plain",
  10268. [i](size_t /*offset*/, DataSink &sink) {
  10269. if (*i == 0) {
  10270. sink.os << "body";
  10271. } else {
  10272. Headers trailer;
  10273. // A valid trailer that must survive.
  10274. trailer.emplace("X-Safe", "safe");
  10275. // Attacker-controlled value carrying CR/LF (response splitting).
  10276. trailer.emplace("X-Reflected",
  10277. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10278. // Attacker-controlled name carrying CR/LF.
  10279. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10280. sink.done_with_trailer(trailer);
  10281. }
  10282. (*i)++;
  10283. return true;
  10284. },
  10285. [i](bool /*success*/) { delete i; });
  10286. });
  10287. thread t = thread([&] { svr.listen(HOST, PORT); });
  10288. auto se = detail::scope_exit([&] {
  10289. svr.stop();
  10290. t.join();
  10291. ASSERT_FALSE(svr.is_running());
  10292. });
  10293. svr.wait_until_ready();
  10294. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10295. "Host: " + HOST +
  10296. "\r\n"
  10297. "Connection: close\r\n"
  10298. "\r\n";
  10299. std::string res;
  10300. ASSERT_TRUE(send_request(5, req, &res));
  10301. // The injected fields must not appear anywhere in the raw response.
  10302. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10303. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10304. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10305. // Invalid trailers are dropped entirely, matching set_header().
  10306. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10307. // The valid trailer still passes through.
  10308. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10309. }
  10310. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10311. // A custom header writer gets only the fields the default one writes
  10312. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10313. std::string s;
  10314. for (const auto &h : hdrs) {
  10315. s += h.first + ": " + h.second + "\r\n";
  10316. }
  10317. s += "\r\n";
  10318. return strm.write(s.data(), s.size());
  10319. };
  10320. for (auto custom_writer : {false, true}) {
  10321. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10322. Server svr;
  10323. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10324. svr.set_post_routing_handler([](const Request &, Response &res) {
  10325. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10326. });
  10327. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10328. // res.headers is a public field an application can populate directly,
  10329. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10330. // A valid header that must survive.
  10331. res.headers.emplace("X-Safe", "safe");
  10332. // Attacker-controlled value carrying CR/LF (response splitting).
  10333. res.headers.emplace("X-Reflected",
  10334. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10335. // Attacker-controlled name carrying CR/LF.
  10336. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10337. res.set_content("body", "text/plain");
  10338. });
  10339. thread t = thread([&] { svr.listen(HOST, PORT); });
  10340. auto se = detail::scope_exit([&] {
  10341. svr.stop();
  10342. t.join();
  10343. ASSERT_FALSE(svr.is_running());
  10344. });
  10345. svr.wait_until_ready();
  10346. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10347. "Host: " + HOST +
  10348. "\r\n"
  10349. "Connection: close\r\n"
  10350. "\r\n";
  10351. std::string res;
  10352. ASSERT_TRUE(send_request(5, req, &res));
  10353. // The injected fields must not appear anywhere in the raw response.
  10354. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10355. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10356. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10357. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10358. // Invalid headers are dropped entirely, matching set_header().
  10359. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10360. // The valid header still passes through.
  10361. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10362. }
  10363. }
  10364. // Forward declaration: in split builds split.py strips `inline` and moves the
  10365. // definition into httplib.cc, so detail::write_request_line is not visible from
  10366. // the public httplib.h. Re-declaring it here lets the tests link against the
  10367. // symbol in both header-only and split builds.
  10368. namespace httplib {
  10369. namespace detail {
  10370. ssize_t write_request_line(Stream &strm, const std::string &method,
  10371. const std::string &path);
  10372. } // namespace detail
  10373. } // namespace httplib
  10374. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10375. // A well-formed target is written verbatim.
  10376. {
  10377. detail::BufferStream strm;
  10378. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10379. EXPECT_GT(n, 0);
  10380. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10381. }
  10382. // A target carrying CR/LF, SP or other control octets must be rejected
  10383. // before anything reaches the wire, otherwise it splits the request line and
  10384. // injects a header or a whole request.
  10385. const std::string evil_targets[] = {
  10386. "/a\r\nInjected: pwned",
  10387. "/a\rInjected",
  10388. "/a\nInjected",
  10389. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10390. "/a b",
  10391. "/a\tb",
  10392. "/a\x7f",
  10393. };
  10394. for (const auto &evil : evil_targets) {
  10395. detail::BufferStream strm;
  10396. auto n = detail::write_request_line(strm, "GET", evil);
  10397. EXPECT_LT(n, 0);
  10398. EXPECT_TRUE(strm.get_buffer().empty());
  10399. }
  10400. }
  10401. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10402. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10403. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10404. // target reaches write_request. The client must fail cleanly with
  10405. // Error::Write instead of putting a request-line-less, header-injecting
  10406. // request on the wire.
  10407. Server svr;
  10408. svr.Get("/a", [](const Request &, Response &res) {
  10409. res.set_content("ok", "text/plain");
  10410. });
  10411. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10412. auto se = detail::scope_exit([&] {
  10413. svr.stop();
  10414. thread.join();
  10415. ASSERT_FALSE(svr.is_running());
  10416. });
  10417. svr.wait_until_ready();
  10418. {
  10419. Client cli(HOST, PORT);
  10420. cli.set_path_encode(false);
  10421. // The request is rejected before anything is written, so the connection
  10422. // stays silent and the subsequent response read would otherwise block for
  10423. // the full default read timeout. Shorten it -- the assertion is on the
  10424. // error, not the timeout.
  10425. cli.set_read_timeout(1, 0);
  10426. auto res = cli.Get("/a\r\nInjected: pwned");
  10427. EXPECT_FALSE(res);
  10428. EXPECT_EQ(Error::Write, res.error());
  10429. }
  10430. }
  10431. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10432. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10433. // including extension methods.
  10434. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10435. for (const auto &method : good_methods) {
  10436. detail::BufferStream strm;
  10437. auto n = detail::write_request_line(strm, method, "/");
  10438. EXPECT_GT(n, 0);
  10439. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10440. }
  10441. // A method carrying CR/LF would split the request line and smuggle a whole
  10442. // request ahead of the real one. A space or an empty method corrupts the
  10443. // request line. All must be rejected before anything reaches the wire.
  10444. const std::string evil_methods[] = {
  10445. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10446. "GET\r\nInjected: pwned",
  10447. "GET\r",
  10448. "GET\n",
  10449. "GE T",
  10450. "",
  10451. };
  10452. for (const auto &evil : evil_methods) {
  10453. detail::BufferStream strm;
  10454. auto n = detail::write_request_line(strm, evil, "/");
  10455. EXPECT_LT(n, 0);
  10456. EXPECT_TRUE(strm.get_buffer().empty());
  10457. }
  10458. }
  10459. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10460. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10461. // through Client::send must fail with Error::Write and no request, neither
  10462. // the smuggled one nor the real one, may reach the server.
  10463. Server svr;
  10464. std::atomic<int> request_count(0);
  10465. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10466. request_count++;
  10467. res.status = StatusCode::OK_200;
  10468. return Server::HandlerResponse::Handled;
  10469. });
  10470. auto port = svr.bind_to_any_port(HOST);
  10471. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10472. auto se = detail::scope_exit([&] {
  10473. svr.stop();
  10474. thread.join();
  10475. ASSERT_FALSE(svr.is_running());
  10476. });
  10477. svr.wait_until_ready();
  10478. {
  10479. Client cli(HOST, port);
  10480. const std::string evil_methods[] = {
  10481. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10482. "GE T",
  10483. "",
  10484. };
  10485. for (const auto &evil : evil_methods) {
  10486. Request req;
  10487. req.method = evil;
  10488. req.path = "/";
  10489. auto res = cli.send(req);
  10490. EXPECT_FALSE(res);
  10491. EXPECT_EQ(Error::Write, res.error());
  10492. }
  10493. auto handle =
  10494. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10495. EXPECT_FALSE(handle.is_valid());
  10496. EXPECT_EQ(Error::Write, handle.error);
  10497. // A valid request on the same client still goes through.
  10498. auto res = cli.Get("/");
  10499. ASSERT_TRUE(res);
  10500. EXPECT_EQ(StatusCode::OK_200, res->status);
  10501. }
  10502. EXPECT_EQ(1, request_count.load());
  10503. }
  10504. // Sends a raw request and verifies that there isn't a crash or exception.
  10505. static void test_raw_request(const std::string &req,
  10506. std::string *out = nullptr) {
  10507. Server svr;
  10508. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10509. res.set_content("ok", "text/plain");
  10510. });
  10511. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10512. res.set_content("ok", "text/plain");
  10513. });
  10514. svr.Get("/header_field_value_check",
  10515. [&](const Request & /*req*/, Response &res) {
  10516. res.set_content("ok", "text/plain");
  10517. });
  10518. svr.CustomRoute("PROPFIND", "/dav",
  10519. [&](const Request & /*req*/, Response &res) {
  10520. res.status = StatusCode::MultiStatus_207;
  10521. });
  10522. // Server read timeout must be longer than the client read timeout for the
  10523. // bug to reproduce, probably to force the server to process a request
  10524. // without a trailing blank line.
  10525. const time_t client_read_timeout_sec = 1;
  10526. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10527. bool listen_thread_ok = false;
  10528. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10529. auto se = detail::scope_exit([&] {
  10530. svr.stop();
  10531. t.join();
  10532. ASSERT_FALSE(svr.is_running());
  10533. EXPECT_TRUE(listen_thread_ok);
  10534. });
  10535. svr.wait_until_ready();
  10536. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10537. }
  10538. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10539. // A certain header line causes an exception if the header property is parsed
  10540. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10541. test_raw_request(
  10542. "GET /hi HTTP/1.1\r\n"
  10543. " : "
  10544. " "
  10545. " ");
  10546. }
  10547. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10548. // A certain header line causes an exception if the header property *name* is
  10549. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10550. // greedy matcher and requires backtracking when there are a lot of ":"
  10551. // characters.
  10552. // This occurs with libc++ but not libstdc++.
  10553. test_raw_request(
  10554. "GET /hi HTTP/1.1\r\n"
  10555. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10556. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10557. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10558. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10559. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10560. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10561. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10562. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10563. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10564. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10565. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10566. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10567. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10568. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10569. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10570. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10571. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10572. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10573. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10574. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10575. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10576. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10577. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10578. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10579. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10580. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10581. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10582. "&&&%%%");
  10583. }
  10584. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10585. // Make sure this doesn't crash the server.
  10586. // In a previous version of the header line regex, the "\r" rendered the line
  10587. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10588. // a new position where the leading white space ended and the field value
  10589. // began.
  10590. // The crash occurs with libc++ but not libstdc++.
  10591. test_raw_request("GET /hi HTTP/1.1\r\n"
  10592. "a:" +
  10593. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10594. "\r\n"
  10595. "\r\n");
  10596. }
  10597. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10598. const char *rejected[] = {
  10599. // RFC 9112 §3: one SP between the parts, and nothing else
  10600. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10601. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10602. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10603. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10604. // A request-target has no fragment
  10605. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10606. // An HTTP/1.1 request needs a Host
  10607. "GET /hi HTTP/1.1\r\n\r\n",
  10608. };
  10609. for (auto request : rejected) {
  10610. std::string out;
  10611. test_raw_request(request, &out);
  10612. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10613. }
  10614. std::string out;
  10615. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10616. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10617. }
  10618. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10619. // RFC 9112 §6.1
  10620. const char *requests[] = {
  10621. "PUT /put_hi HTTP/1.1\r\n"
  10622. "Host: localhost\r\n"
  10623. "Content-Length: 0\r\n"
  10624. "Transfer-Encoding: chunked\r\n"
  10625. "\r\n"
  10626. "0\r\n\r\n",
  10627. "PUT /put_hi HTTP/1.0\r\n"
  10628. "Connection: keep-alive\r\n"
  10629. "Transfer-Encoding: chunked\r\n"
  10630. "\r\n"
  10631. "0\r\n\r\n",
  10632. };
  10633. for (auto request : requests) {
  10634. std::string out;
  10635. test_raw_request(request, &out);
  10636. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10637. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10638. }
  10639. }
  10640. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10641. std::string out;
  10642. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10643. "Content-Type: text/plain\r\n"
  10644. "Transfer-Encoding: chunked\r\n"
  10645. "\r\n"
  10646. "nothex\r\n",
  10647. &out);
  10648. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10649. }
  10650. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10651. std::string out;
  10652. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10653. "Content-Type: text/plain\r\n"
  10654. "Transfer-Encoding: chunked\r\n"
  10655. "\r\n"
  10656. "3\r\n"
  10657. "xyz\r\n"
  10658. "NaN\r\n",
  10659. &out);
  10660. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10661. }
  10662. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10663. std::string out;
  10664. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10665. "Content-Type: text/plain\r\n"
  10666. "Transfer-Encoding: chunked\r\n"
  10667. "\r\n"
  10668. // Length is too large for 64 bits.
  10669. "1ffffffffffffffff\r\n"
  10670. "xyz\r\n",
  10671. &out);
  10672. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10673. }
  10674. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10675. test_raw_request("GET /hi HTTP/1.1\r\n"
  10676. "Content-Type: text/plain\r\n\r");
  10677. }
  10678. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10679. std::string out;
  10680. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10681. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10682. }
  10683. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10684. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10685. std::string out;
  10686. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10687. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10688. }
  10689. }
  10690. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10691. std::string out;
  10692. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10693. "Host: localhost\r\n"
  10694. "Connection: close\r\n\r\n",
  10695. &out);
  10696. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10697. }
  10698. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10699. Server svr;
  10700. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10701. EXPECT_TRUE(!req.remote_addr.empty());
  10702. });
  10703. thread t = thread([&] { svr.listen(HOST, PORT); });
  10704. auto se = detail::scope_exit([&] {
  10705. svr.stop();
  10706. t.join();
  10707. ASSERT_FALSE(svr.is_running());
  10708. });
  10709. svr.wait_until_ready();
  10710. // Send an invalid request line to trigger Bad Request
  10711. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10712. std::string out;
  10713. ASSERT_TRUE(send_request(5, bad_req, &out));
  10714. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10715. }
  10716. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10717. // answered right away rather than blocking on a read that waits for EOF.
  10718. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10719. std::string out;
  10720. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10721. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10722. }
  10723. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10724. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10725. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10726. for (const auto *method : methods) {
  10727. Server svr;
  10728. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10729. EXPECT_FALSE(svr.is_valid()) << method;
  10730. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10731. }
  10732. }
  10733. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10734. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10735. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10736. for (const auto *method : methods) {
  10737. Server svr;
  10738. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10739. EXPECT_FALSE(svr.is_valid()) << method;
  10740. }
  10741. }
  10742. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10743. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10744. "COPY", "MOVE", "LOCK",
  10745. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10746. Server svr;
  10747. for (const auto *method : methods) {
  10748. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10749. }
  10750. EXPECT_TRUE(svr.is_valid());
  10751. }
  10752. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10753. Server svr;
  10754. svr.CustomRoute("POST", "/x",
  10755. [](const Request &, Response &, const ContentReader &) {});
  10756. EXPECT_FALSE(svr.is_valid());
  10757. }
  10758. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10759. Server svr;
  10760. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10761. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10762. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10763. EXPECT_FALSE(svr.is_valid());
  10764. }
  10765. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10766. Server svr;
  10767. auto captured = Error::Success;
  10768. svr.set_error_logger(
  10769. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10770. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10771. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10772. }
  10773. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10774. std::string out;
  10775. std::string request(
  10776. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10777. test_raw_request(request, &out);
  10778. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10779. }
  10780. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10781. std::string out;
  10782. std::string request(
  10783. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10784. test_raw_request(request, &out);
  10785. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10786. }
  10787. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10788. std::string out;
  10789. std::string request(
  10790. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10791. test_raw_request(request, &out);
  10792. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10793. }
  10794. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10795. std::string out;
  10796. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10797. "Host: localhost\r\n"
  10798. "Test: \r\n\r\n",
  10799. &out);
  10800. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10801. }
  10802. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10803. Server svr;
  10804. std::string x_custom;
  10805. std::string cookie;
  10806. std::string xff;
  10807. std::string x_unicode;
  10808. std::string x_iis;
  10809. svr.Get("/check", [&](const Request &req, Response &res) {
  10810. x_custom = req.get_header_value("X-Custom");
  10811. cookie = req.get_header_value("Cookie");
  10812. xff = req.get_header_value("X-Forwarded-For");
  10813. x_unicode = req.get_header_value("X-Unicode");
  10814. x_iis = req.get_header_value("X-IIS");
  10815. res.set_content("ok", "text/plain");
  10816. });
  10817. thread t = thread([&] { svr.listen(HOST, PORT); });
  10818. auto se = detail::scope_exit([&] {
  10819. svr.stop();
  10820. t.join();
  10821. ASSERT_FALSE(svr.is_running());
  10822. });
  10823. svr.wait_until_ready();
  10824. const std::string req = "GET /check HTTP/1.1\r\n"
  10825. "Host: localhost\r\n"
  10826. "X-Custom: a%0D%0AInjected: b\r\n"
  10827. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10828. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10829. "X-Unicode: %E3%81%82\r\n"
  10830. "X-IIS: %u00E9\r\n"
  10831. "Connection: close\r\n"
  10832. "\r\n";
  10833. std::string res;
  10834. ASSERT_TRUE(send_request(5, req, &res));
  10835. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10836. // Every value must be returned verbatim (wire form), with no decoding.
  10837. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10838. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10839. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10840. EXPECT_EQ("%E3%81%82", x_unicode);
  10841. EXPECT_EQ("%u00E9", x_iis);
  10842. }
  10843. // Applications that previously relied on automatic percent-decoding can
  10844. // reproduce the old behavior by explicitly calling decode_path_component()
  10845. // or, for RFC 3986 conformance, decode_uri_component().
  10846. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10847. Server svr;
  10848. std::string decoded;
  10849. svr.Get("/check", [&](const Request &req, Response &res) {
  10850. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10851. res.set_content("ok", "text/plain");
  10852. });
  10853. thread t = thread([&] { svr.listen(HOST, PORT); });
  10854. auto se = detail::scope_exit([&] {
  10855. svr.stop();
  10856. t.join();
  10857. ASSERT_FALSE(svr.is_running());
  10858. });
  10859. svr.wait_until_ready();
  10860. const std::string req = "GET /check HTTP/1.1\r\n"
  10861. "Host: localhost\r\n"
  10862. "X-Custom: hello%20world\r\n"
  10863. "Connection: close\r\n"
  10864. "\r\n";
  10865. std::string res;
  10866. ASSERT_TRUE(send_request(5, req, &res));
  10867. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10868. EXPECT_EQ("hello world", decoded);
  10869. }
  10870. // Regression test for #2033. Browsers send Referer values that include
  10871. // percent-encoded characters such as %0A inside the URL. Decoding the
  10872. // header value would either trip the post-decode CR/LF/NUL guard (the
  10873. // original bug, returning 400) or, after that guard was relaxed, silently
  10874. // store a literal LF — both unacceptable. The wire form must round-trip.
  10875. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10876. Server svr;
  10877. std::string referer;
  10878. svr.Get("/check", [&](const Request &req, Response &res) {
  10879. referer = req.get_header_value("Referer");
  10880. res.set_content("ok", "text/plain");
  10881. });
  10882. thread t = thread([&] { svr.listen(HOST, PORT); });
  10883. auto se = detail::scope_exit([&] {
  10884. svr.stop();
  10885. t.join();
  10886. ASSERT_FALSE(svr.is_running());
  10887. });
  10888. svr.wait_until_ready();
  10889. const std::string req = "GET /check HTTP/1.1\r\n"
  10890. "Host: localhost\r\n"
  10891. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10892. "Connection: close\r\n"
  10893. "\r\n";
  10894. std::string res;
  10895. ASSERT_TRUE(send_request(5, req, &res));
  10896. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10897. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10898. }
  10899. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10900. Server svr;
  10901. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10902. res.set_header("Cache-Control", "no-cache");
  10903. res.set_chunked_content_provider(
  10904. "text/event-stream", [](size_t offset, DataSink &sink) {
  10905. std::string s = "data:";
  10906. s += std::to_string(offset);
  10907. s += "\n\n";
  10908. auto ret = sink.write(s.data(), s.size());
  10909. EXPECT_TRUE(ret);
  10910. std::this_thread::sleep_for(std::chrono::seconds(1));
  10911. return true;
  10912. });
  10913. });
  10914. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10915. svr.wait_until_ready();
  10916. Client client(HOST, PORT);
  10917. const Headers headers = {{"Accept", "text/event-stream"}};
  10918. auto get_thread = std::thread([&client, &headers]() {
  10919. auto res = client.Get(
  10920. "/events", headers,
  10921. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10922. });
  10923. auto se = detail::scope_exit([&] {
  10924. svr.stop();
  10925. get_thread.join();
  10926. listen_thread.join();
  10927. ASSERT_FALSE(svr.is_running());
  10928. });
  10929. // Give GET time to get a few messages.
  10930. std::this_thread::sleep_for(std::chrono::seconds(2));
  10931. }
  10932. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10933. httplib::Server svr;
  10934. svr.Post("/hi",
  10935. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10936. res.status = StatusCode::OK_200;
  10937. });
  10938. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10939. svr.wait_until_ready();
  10940. Client cli(HOST, PORT);
  10941. auto res = cli.Post("/hi", "data", "text/plain");
  10942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10943. EXPECT_EQ(StatusCode::OK_200, res->status);
  10944. svr.stop();
  10945. thread.join();
  10946. ASSERT_FALSE(svr.is_running());
  10947. res = cli.Post("/hi", "data", "text/plain");
  10948. ASSERT_FALSE(res);
  10949. }
  10950. TEST(ServerStopTest, ListenFailure) {
  10951. Server svr;
  10952. auto t = thread([&]() {
  10953. auto ret = svr.listen("????", PORT);
  10954. EXPECT_FALSE(ret);
  10955. });
  10956. svr.wait_until_ready();
  10957. svr.stop();
  10958. t.join();
  10959. }
  10960. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10961. TEST(ServerStopTest, Decommision) {
  10962. Server svr;
  10963. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10964. for (int i = 0; i < 4; i++) {
  10965. auto is_even = !(i % 2);
  10966. std::thread t{[&] {
  10967. try {
  10968. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10969. if (is_even) {
  10970. throw std::runtime_error("Some thing that happens to go wrong.");
  10971. }
  10972. svr.listen(HOST, PORT);
  10973. } catch (...) { svr.decommission(); }
  10974. }};
  10975. svr.wait_until_ready();
  10976. // Server is up
  10977. {
  10978. Client cli(HOST, PORT);
  10979. auto res = cli.Get("/hi");
  10980. if (is_even) {
  10981. EXPECT_FALSE(res);
  10982. } else {
  10983. EXPECT_TRUE(res);
  10984. EXPECT_EQ("hi...", res->body);
  10985. }
  10986. }
  10987. svr.stop();
  10988. t.join();
  10989. // Server is down...
  10990. {
  10991. Client cli(HOST, PORT);
  10992. auto res = cli.Get("/hi");
  10993. EXPECT_FALSE(res);
  10994. }
  10995. }
  10996. }
  10997. #endif
  10998. // Helper function for string body upload progress tests
  10999. template <typename SetupHandler, typename ClientCall>
  11000. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  11001. ClientCall &&client_call,
  11002. const string &body) {
  11003. Server svr;
  11004. setup_handler(svr);
  11005. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11006. auto se = detail::scope_exit([&] {
  11007. svr.stop();
  11008. t.join();
  11009. });
  11010. svr.wait_until_ready();
  11011. Client cli(HOST, PORT);
  11012. vector<uint64_t> progress_values;
  11013. bool progress_called = false;
  11014. auto res =
  11015. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11016. progress_values.push_back(current);
  11017. progress_called = true;
  11018. return true;
  11019. });
  11020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11021. EXPECT_EQ(200, res->status);
  11022. EXPECT_TRUE(progress_called);
  11023. }
  11024. TEST(UploadProgressTest, PostStringBodyBasic) {
  11025. TestStringBodyUploadProgress(
  11026. [](Server &svr) {
  11027. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11028. res.set_content("received", "text/plain");
  11029. });
  11030. },
  11031. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11032. return cli.Post("/test", body, "text/plain", progress_callback);
  11033. },
  11034. "test data for upload progress");
  11035. }
  11036. TEST(UploadProgressTest, PutStringBodyBasic) {
  11037. TestStringBodyUploadProgress(
  11038. [](Server &svr) {
  11039. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  11040. res.set_content("put received", "text/plain");
  11041. });
  11042. },
  11043. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11044. return cli.Put("/test", body, "text/plain", progress_callback);
  11045. },
  11046. "put test data for upload progress");
  11047. }
  11048. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11049. TestStringBodyUploadProgress(
  11050. [](Server &svr) {
  11051. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11052. res.set_content("patch received", "text/plain");
  11053. });
  11054. },
  11055. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11056. return cli.Patch("/test", body, "text/plain", progress_callback);
  11057. },
  11058. "patch test data for upload progress");
  11059. }
  11060. // Helper function for content provider upload progress tests
  11061. template <typename SetupHandler, typename ClientCall>
  11062. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11063. ClientCall &&client_call) {
  11064. Server svr;
  11065. setup_handler(svr);
  11066. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11067. auto se = detail::scope_exit([&] {
  11068. svr.stop();
  11069. t.join();
  11070. });
  11071. svr.wait_until_ready();
  11072. Client cli(HOST, PORT);
  11073. vector<uint64_t> progress_values;
  11074. auto res =
  11075. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11076. progress_values.push_back(current);
  11077. return true;
  11078. });
  11079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11080. EXPECT_EQ(200, res->status);
  11081. EXPECT_FALSE(progress_values.empty());
  11082. }
  11083. TEST(UploadProgressTest, PostContentProviderProgress) {
  11084. TestContentProviderUploadProgress(
  11085. [](Server &svr) {
  11086. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11087. res.set_content("provider received", "text/plain");
  11088. });
  11089. },
  11090. [](Client &cli, UploadProgress progress_callback) {
  11091. return cli.Post(
  11092. "/test", 9,
  11093. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11094. sink.os << "test data";
  11095. return true;
  11096. },
  11097. "text/plain", progress_callback);
  11098. });
  11099. }
  11100. // Helper function for multipart upload progress tests
  11101. template <typename SetupHandler, typename ClientCall>
  11102. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11103. ClientCall &&client_call,
  11104. const string &endpoint) {
  11105. Server svr;
  11106. setup_handler(svr);
  11107. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11108. auto se = detail::scope_exit([&] {
  11109. svr.stop();
  11110. t.join();
  11111. });
  11112. svr.wait_until_ready();
  11113. Client cli(HOST, PORT);
  11114. vector<uint64_t> progress_values;
  11115. UploadFormDataItems items = {
  11116. {"field1", "value1", "", ""},
  11117. {"field2", "longer value for progress tracking test", "", ""},
  11118. {"file1", "file content data for upload progress", "test.txt",
  11119. "text/plain"}};
  11120. auto res = client_call(cli, endpoint, items,
  11121. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11122. progress_values.push_back(current);
  11123. return true;
  11124. });
  11125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11126. EXPECT_EQ(200, res->status);
  11127. EXPECT_FALSE(progress_values.empty());
  11128. }
  11129. TEST(UploadProgressTest, PostMultipartProgress) {
  11130. TestMultipartUploadProgress(
  11131. [](Server &svr) {
  11132. svr.Post("/multipart", [](const Request &req, Response &res) {
  11133. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11134. res.set_content("multipart received", "text/plain");
  11135. });
  11136. },
  11137. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11138. UploadProgress progress_callback) {
  11139. return cli.Post(endpoint, items, progress_callback);
  11140. },
  11141. "/multipart");
  11142. }
  11143. // Helper function for basic download progress tests
  11144. template <typename SetupHandler, typename ClientCall>
  11145. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11146. ClientCall &&client_call, 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. auto res = client_call(cli, endpoint,
  11159. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11160. progress_values.push_back(current);
  11161. return true;
  11162. });
  11163. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11164. EXPECT_EQ(200, res->status);
  11165. EXPECT_FALSE(progress_values.empty());
  11166. EXPECT_EQ(expected_content_size, res->body.size());
  11167. }
  11168. TEST(DownloadProgressTest, GetBasic) {
  11169. TestBasicDownloadProgress(
  11170. [](Server &svr) {
  11171. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11172. string content(1000, 'D');
  11173. res.set_content(content, "text/plain");
  11174. });
  11175. },
  11176. [](Client &cli, const string &endpoint,
  11177. DownloadProgress progress_callback) {
  11178. return cli.Get(endpoint, progress_callback);
  11179. },
  11180. "/download", 1000u);
  11181. }
  11182. // Helper function for content receiver download progress tests
  11183. template <typename SetupHandler, typename ClientCall>
  11184. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11185. ClientCall &&client_call,
  11186. const string &endpoint,
  11187. size_t expected_content_size) {
  11188. Server svr;
  11189. setup_handler(svr);
  11190. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11191. auto se = detail::scope_exit([&] {
  11192. svr.stop();
  11193. t.join();
  11194. });
  11195. svr.wait_until_ready();
  11196. Client cli(HOST, PORT);
  11197. vector<uint64_t> progress_values;
  11198. string received_body;
  11199. auto res = client_call(
  11200. cli, endpoint,
  11201. [&](const char *data, size_t data_length) -> bool {
  11202. received_body.append(data, data_length);
  11203. return true;
  11204. },
  11205. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11206. progress_values.push_back(current);
  11207. return true;
  11208. });
  11209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11210. EXPECT_EQ(200, res->status);
  11211. EXPECT_FALSE(progress_values.empty());
  11212. EXPECT_EQ(expected_content_size, received_body.size());
  11213. EXPECT_TRUE(res->body.empty());
  11214. }
  11215. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11216. TestContentReceiverDownloadProgress(
  11217. [](Server &svr) {
  11218. svr.Get("/download-receiver",
  11219. [](const Request & /*req*/, Response &res) {
  11220. string content(2000, 'R');
  11221. res.set_content(content, "text/plain");
  11222. });
  11223. },
  11224. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11225. DownloadProgress progress_callback) {
  11226. return cli.Get(endpoint, content_receiver, progress_callback);
  11227. },
  11228. "/download-receiver", 2000u);
  11229. }
  11230. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11231. // A provider reaching a pass with nothing to hand over - an empty buffer
  11232. // popped off a queue, say - must not be taken to mean the body is finished.
  11233. // It used to end the loop with the terminating chunk unwritten while the
  11234. // server still considered the response complete, so the peer waited for an
  11235. // end that never arrived.
  11236. Server svr;
  11237. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11238. auto step = std::make_shared<int>(0);
  11239. res.set_chunked_content_provider("text/plain",
  11240. [step](size_t /*offset*/, DataSink &sink) {
  11241. switch ((*step)++) {
  11242. case 0: sink.write("", 0); break;
  11243. case 1: sink.write("hello", 5); break;
  11244. default: sink.done(); break;
  11245. }
  11246. return true;
  11247. });
  11248. });
  11249. auto port = svr.bind_to_any_port(HOST);
  11250. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11251. auto listen_se = detail::scope_exit([&] {
  11252. svr.stop();
  11253. listen_thread.join();
  11254. ASSERT_FALSE(svr.is_running());
  11255. });
  11256. svr.wait_until_ready();
  11257. Client cli(HOST, port);
  11258. // Without the fix the body is never terminated, so bound the wait rather
  11259. // than letting the test hang on the default read timeout.
  11260. cli.set_read_timeout(5, 0);
  11261. auto res = cli.Get("/stream");
  11262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11263. EXPECT_EQ(StatusCode::OK_200, res->status);
  11264. EXPECT_EQ("hello", res->body);
  11265. }
  11266. TEST(StreamingTest, NoContentLengthStreaming) {
  11267. Server svr;
  11268. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11269. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11270. if (offset < 6) {
  11271. sink.os << (offset < 3 ? "a" : "b");
  11272. } else {
  11273. sink.done();
  11274. }
  11275. return true;
  11276. });
  11277. });
  11278. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11279. auto listen_se = detail::scope_exit([&] {
  11280. svr.stop();
  11281. listen_thread.join();
  11282. ASSERT_FALSE(svr.is_running());
  11283. });
  11284. svr.wait_until_ready();
  11285. Client client(HOST, PORT);
  11286. auto get_thread = std::thread([&client]() {
  11287. std::string s;
  11288. auto res =
  11289. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11290. s += std::string(data, len);
  11291. return true;
  11292. });
  11293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11294. EXPECT_EQ(StatusCode::OK_200, res->status);
  11295. EXPECT_EQ("aaabbb", s);
  11296. });
  11297. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11298. // Give GET time to get a few messages.
  11299. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11300. }
  11301. TEST(MountTest, Unmount) {
  11302. Server svr;
  11303. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11304. auto se = detail::scope_exit([&] {
  11305. svr.stop();
  11306. listen_thread.join();
  11307. ASSERT_FALSE(svr.is_running());
  11308. });
  11309. svr.wait_until_ready();
  11310. Client cli("localhost", PORT);
  11311. svr.set_mount_point("/mount2", "./www2");
  11312. auto res = cli.Get("/");
  11313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11315. res = cli.Get("/mount2/dir/test.html");
  11316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11317. EXPECT_EQ(StatusCode::OK_200, res->status);
  11318. svr.set_mount_point("/", "./www");
  11319. res = cli.Get("/dir/");
  11320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11321. EXPECT_EQ(StatusCode::OK_200, res->status);
  11322. svr.remove_mount_point("/");
  11323. res = cli.Get("/dir/");
  11324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11325. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11326. svr.remove_mount_point("/mount2");
  11327. res = cli.Get("/mount2/dir/test.html");
  11328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11329. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11330. }
  11331. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11332. Server svr;
  11333. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11334. svr.Get("/api/hello", [](const Request &, Response &res) {
  11335. res.set_content("api", "text/plain");
  11336. });
  11337. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11338. auto se = detail::scope_exit([&] {
  11339. svr.stop();
  11340. listen_thread.join();
  11341. ASSERT_FALSE(svr.is_running());
  11342. });
  11343. svr.wait_until_ready();
  11344. Client cli(HOST, PORT);
  11345. auto res = cli.Get("/dir/test.html");
  11346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11347. EXPECT_EQ(StatusCode::OK_200, res->status);
  11348. res = cli.Get("/api/hello");
  11349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11350. EXPECT_EQ(StatusCode::OK_200, res->status);
  11351. EXPECT_EQ("api", res->body);
  11352. }
  11353. TEST(MountTest, PathSegmentBoundary) {
  11354. Server svr;
  11355. svr.set_mount_point("/mount2", "./www2");
  11356. svr.set_mount_point("/", "./www");
  11357. auto port = svr.bind_to_any_port(HOST);
  11358. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11359. auto se = detail::scope_exit([&] {
  11360. svr.stop();
  11361. listen_thread.join();
  11362. ASSERT_FALSE(svr.is_running());
  11363. });
  11364. svr.wait_until_ready();
  11365. Client cli(HOST, port);
  11366. auto res = cli.Get("/mount2/dir/test.html");
  11367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11368. EXPECT_EQ(StatusCode::OK_200, res->status);
  11369. // "/mount2" must not match part-way through a path segment.
  11370. res = cli.Get("/mount2dir/test.html");
  11371. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11372. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11373. // A mount point ending in '/' keeps matching every path below it.
  11374. res = cli.Get("/dir/test.html");
  11375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11376. EXPECT_EQ(StatusCode::OK_200, res->status);
  11377. }
  11378. TEST(MountTest, Redicect) {
  11379. Server svr;
  11380. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11381. auto se = detail::scope_exit([&] {
  11382. svr.stop();
  11383. listen_thread.join();
  11384. ASSERT_FALSE(svr.is_running());
  11385. });
  11386. svr.set_mount_point("/", "./www");
  11387. svr.wait_until_ready();
  11388. Client cli("localhost", PORT);
  11389. auto res = cli.Get("/dir/");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. res = cli.Get("/dir");
  11393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11394. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11395. res = cli.Get("/file");
  11396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11397. EXPECT_EQ(StatusCode::OK_200, res->status);
  11398. res = cli.Get("/file/");
  11399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11400. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11401. cli.set_follow_location(true);
  11402. res = cli.Get("/dir");
  11403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11404. EXPECT_EQ(StatusCode::OK_200, res->status);
  11405. }
  11406. TEST(MountTest, MultibytesPathName) {
  11407. Server svr;
  11408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11409. auto se = detail::scope_exit([&] {
  11410. svr.stop();
  11411. listen_thread.join();
  11412. ASSERT_FALSE(svr.is_running());
  11413. });
  11414. svr.set_mount_point("/", "./www");
  11415. svr.wait_until_ready();
  11416. Client cli("localhost", PORT);
  11417. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11419. EXPECT_EQ(StatusCode::OK_200, res->status);
  11420. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11421. }
  11422. // A mount point serves no path with an empty segment or one ending in '.' or
  11423. // a space, so a guard in the pre-routing handler sees the path of every file
  11424. // that is served
  11425. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11426. Server svr;
  11427. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11428. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11429. if (req.path == "/dir/test.html") {
  11430. res.status = StatusCode::Unauthorized_401;
  11431. return Server::HandlerResponse::Handled;
  11432. }
  11433. return Server::HandlerResponse::Unhandled;
  11434. });
  11435. auto port = svr.bind_to_any_port(HOST);
  11436. ASSERT_LT(0, port);
  11437. thread t = thread([&] { svr.listen_after_bind(); });
  11438. auto se = detail::scope_exit([&] {
  11439. svr.stop();
  11440. t.join();
  11441. ASSERT_FALSE(svr.is_running());
  11442. });
  11443. svr.wait_until_ready();
  11444. Client cli(HOST, port);
  11445. for (auto path :
  11446. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11447. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11448. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11449. "/dir/test.html%3A%3A$DATA"}) {
  11450. SCOPED_TRACE(path);
  11451. auto res = cli.Get(path);
  11452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11453. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11454. }
  11455. }
  11456. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11457. Server svr;
  11458. svr.set_mount_point("/", "./www");
  11459. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11460. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11461. auto port = svr.bind_to_any_port(HOST);
  11462. ASSERT_GT(port, 0);
  11463. thread t = thread([&] { svr.listen_after_bind(); });
  11464. auto se = detail::scope_exit([&] {
  11465. svr.stop();
  11466. t.join();
  11467. ASSERT_FALSE(svr.is_running());
  11468. });
  11469. svr.wait_until_ready();
  11470. Client cli(HOST, port);
  11471. auto res = cli.Get("/dir/test.abcde");
  11472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11473. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11474. res = cli.Get("/dir/test.html");
  11475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11476. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11477. }
  11478. #ifdef _WIN32
  11479. // Issue #2435: mmap::open() must succeed even when another handle holds
  11480. // the file open for writing (e.g. an active log file).
  11481. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11482. const char *path = "mmap_concurrent_writer_test.txt";
  11483. const char *content = "hello";
  11484. {
  11485. std::ofstream f(path, std::ios::binary);
  11486. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11487. }
  11488. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11489. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11490. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11491. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11492. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11493. detail::mmap m(path);
  11494. ASSERT_TRUE(m.is_open());
  11495. EXPECT_EQ(strlen(content), m.size());
  11496. char buf[8];
  11497. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11498. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11499. }
  11500. #endif
  11501. #ifndef _WIN32
  11502. // A directory or a device has no size to serve.
  11503. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11504. const char *path = "./mmap_not_regular_test_dir";
  11505. ASSERT_EQ(0, ::mkdir(path, 0755));
  11506. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11507. for (auto p : {path, "/dev/null"}) {
  11508. detail::mmap m(p);
  11509. EXPECT_FALSE(m.is_open()) << p;
  11510. EXPECT_EQ(0U, m.size()) << p;
  11511. }
  11512. Server svr;
  11513. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11514. res.set_file_content("/dev/null");
  11515. });
  11516. auto port = svr.bind_to_any_port(HOST);
  11517. thread t = thread([&] { svr.listen_after_bind(); });
  11518. auto se = detail::scope_exit([&] {
  11519. svr.stop();
  11520. t.join();
  11521. });
  11522. svr.wait_until_ready();
  11523. auto res = Client(HOST, port).Get("/null");
  11524. ASSERT_TRUE(res);
  11525. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11526. }
  11527. #endif
  11528. #ifdef __linux__
  11529. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11530. TEST(MmapTest, FileIsNotMapped) {
  11531. const char *path = "mmap_not_mapped_test.txt";
  11532. {
  11533. std::ofstream f(path, std::ios::binary);
  11534. f << "hello";
  11535. }
  11536. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11537. detail::mmap m(path);
  11538. ASSERT_TRUE(m.is_open());
  11539. std::ifstream maps("/proc/self/maps");
  11540. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11541. std::istreambuf_iterator<char>());
  11542. EXPECT_EQ(std::string::npos, mappings.find(path));
  11543. }
  11544. #endif
  11545. TEST(KeepAliveTest, ReadTimeout) {
  11546. Server svr;
  11547. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11548. std::this_thread::sleep_for(std::chrono::seconds(2));
  11549. res.set_content("a", "text/plain");
  11550. });
  11551. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11552. res.set_content("b", "text/plain");
  11553. });
  11554. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11555. auto se = detail::scope_exit([&] {
  11556. svr.stop();
  11557. listen_thread.join();
  11558. ASSERT_FALSE(svr.is_running());
  11559. });
  11560. svr.wait_until_ready();
  11561. Client cli("localhost", PORT);
  11562. cli.set_keep_alive(true);
  11563. cli.set_read_timeout(std::chrono::seconds(1));
  11564. auto resa = cli.Get("/a");
  11565. ASSERT_FALSE(resa);
  11566. EXPECT_EQ(Error::Read, resa.error());
  11567. auto resb = cli.Get("/b");
  11568. ASSERT_TRUE(resb);
  11569. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11570. EXPECT_EQ("b", resb->body);
  11571. }
  11572. TEST(KeepAliveTest, MaxCount) {
  11573. size_t keep_alive_max_count = 3;
  11574. Server svr;
  11575. svr.set_keep_alive_max_count(keep_alive_max_count);
  11576. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11577. res.set_content("Hello World!", "text/plain");
  11578. });
  11579. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11580. auto se = detail::scope_exit([&] {
  11581. svr.stop();
  11582. listen_thread.join();
  11583. ASSERT_FALSE(svr.is_running());
  11584. });
  11585. svr.wait_until_ready();
  11586. Client cli(HOST, PORT);
  11587. cli.set_keep_alive(true);
  11588. for (size_t i = 0; i < 5; i++) {
  11589. auto result = cli.Get("/hi");
  11590. ASSERT_TRUE(result);
  11591. EXPECT_EQ(StatusCode::OK_200, result->status);
  11592. if (i == keep_alive_max_count - 1) {
  11593. EXPECT_EQ("close", result->get_header_value("Connection"));
  11594. } else {
  11595. EXPECT_FALSE(result->has_header("Connection"));
  11596. }
  11597. }
  11598. }
  11599. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11600. // can pull the next one into the server's buffer. The server must serve it
  11601. // without waiting for the socket to become readable again. The keep-alive
  11602. // timeout outlasts the client's read timeout, so a request left waiting for it
  11603. // shows up as a missing response.
  11604. static void serve_pipelining_routes(Server &svr,
  11605. const std::function<void(int)> &client) {
  11606. svr.set_keep_alive_timeout(5);
  11607. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11608. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11609. });
  11610. svr.Post("/echo", [](const Request &req, Response &res) {
  11611. res.set_content("echo " + req.body, "text/plain");
  11612. });
  11613. auto port = svr.bind_to_any_port(HOST);
  11614. thread t = thread([&] { svr.listen_after_bind(); });
  11615. auto se = detail::scope_exit([&] {
  11616. svr.stop();
  11617. t.join();
  11618. });
  11619. svr.wait_until_ready();
  11620. client(port);
  11621. }
  11622. static std::string
  11623. send_pipelined_requests(const std::vector<std::string> &parts) {
  11624. Server svr;
  11625. std::string res;
  11626. serve_pipelining_routes(svr, [&](int port) {
  11627. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11628. });
  11629. return res;
  11630. }
  11631. static void expect_in_order(const std::string &res,
  11632. const std::vector<std::string> &bodies) {
  11633. size_t pos = 0;
  11634. for (const auto &body : bodies) {
  11635. pos = res.find(body, pos);
  11636. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11637. pos += body.size();
  11638. }
  11639. }
  11640. TEST(KeepAliveTest, PipelinedRequests) {
  11641. auto res = send_pipelined_requests(
  11642. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11643. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11644. "Content-Length: 4\r\n\r\nbody"
  11645. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11646. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11647. }
  11648. // The second request starts in the server's buffer and ends on the socket.
  11649. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11650. auto res =
  11651. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11652. "GET /hi/2 HTTP/1.1\r\nHo",
  11653. "st: localhost\r\nConnection: close\r\n\r\n"});
  11654. expect_in_order(res, {"hi 1", "hi 2"});
  11655. }
  11656. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11657. // CRLF after a body does not turn into a 400 for the next request.
  11658. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11659. auto res = send_pipelined_requests(
  11660. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11661. "Content-Length: 4\r\n\r\nbody\r\n"
  11662. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11663. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11664. expect_in_order(res, {"echo body", "hi 2"});
  11665. }
  11666. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11667. // must not be served as the next request.
  11668. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11669. auto res = send_pipelined_requests(
  11670. {"INVALID REQUEST LINE\r\n\r\n"
  11671. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11672. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11673. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11674. }
  11675. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11676. // Over TLS, the next request is held by the TLS library as already decrypted
  11677. // data rather than on the socket.
  11678. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11679. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11680. std::string res;
  11681. serve_pipelining_routes(svr, [&](int port) {
  11682. // One part, so all three requests arrive in one TLS record
  11683. EXPECT_TRUE(send_ssl_request_in_parts(
  11684. 2,
  11685. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11686. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11687. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11688. &res, port));
  11689. });
  11690. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11691. }
  11692. #endif
  11693. TEST(KeepAliveTest, Issue1041) {
  11694. Server svr;
  11695. svr.set_keep_alive_timeout(3);
  11696. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11697. res.set_content("Hello World!", "text/plain");
  11698. });
  11699. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11700. auto se = detail::scope_exit([&] {
  11701. svr.stop();
  11702. listen_thread.join();
  11703. ASSERT_FALSE(svr.is_running());
  11704. });
  11705. svr.wait_until_ready();
  11706. Client cli(HOST, PORT);
  11707. cli.set_keep_alive(true);
  11708. auto result = cli.Get("/hi");
  11709. ASSERT_TRUE(result);
  11710. EXPECT_EQ(StatusCode::OK_200, result->status);
  11711. std::this_thread::sleep_for(std::chrono::seconds(5));
  11712. result = cli.Get("/hi");
  11713. ASSERT_TRUE(result);
  11714. EXPECT_EQ(StatusCode::OK_200, result->status);
  11715. }
  11716. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11717. Server svr;
  11718. svr.set_keep_alive_max_count(0);
  11719. std::set<int> remote_ports;
  11720. svr.Get("/hi", [&](const Request &req, Response &res) {
  11721. remote_ports.insert(req.remote_port);
  11722. res.set_content("hi", "text/plain");
  11723. });
  11724. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11725. auto se = detail::scope_exit([&] {
  11726. svr.stop();
  11727. listen_thread.join();
  11728. ASSERT_FALSE(svr.is_running());
  11729. });
  11730. svr.wait_until_ready();
  11731. Client cli(HOST, PORT);
  11732. cli.set_keep_alive(true);
  11733. for (int i = 0; i < 3; i++) {
  11734. auto res = cli.Get("/hi");
  11735. ASSERT_TRUE(res);
  11736. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11737. }
  11738. // All three over one connection
  11739. EXPECT_EQ(1u, remote_ports.size());
  11740. }
  11741. // Forward declaration (see the base64_encode note).
  11742. namespace httplib {
  11743. namespace detail {
  11744. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11745. } // namespace detail
  11746. } // namespace httplib
  11747. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11748. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11749. #ifndef _WIN32
  11750. signal(SIGPIPE, SIG_IGN);
  11751. #endif
  11752. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11753. ASSERT_NE(INVALID_SOCKET, srv);
  11754. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11755. default_socket_options(srv);
  11756. sockaddr_in addr{};
  11757. addr.sin_family = AF_INET;
  11758. addr.sin_port = 0;
  11759. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11760. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11761. ASSERT_EQ(0, ::listen(srv, 2));
  11762. socklen_t addr_len = sizeof(addr);
  11763. ASSERT_EQ(0,
  11764. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11765. auto port = ntohs(addr.sin_port);
  11766. struct Peer {
  11767. socket_t sock = INVALID_SOCKET;
  11768. #ifdef CPPHTTPLIB_SSL_ENABLED
  11769. tls::session_t session = nullptr;
  11770. #endif
  11771. };
  11772. #ifdef CPPHTTPLIB_SSL_ENABLED
  11773. tls::ctx_t ctx = nullptr;
  11774. if (use_tls) {
  11775. ctx = tls::create_server_context();
  11776. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11777. nullptr);
  11778. }
  11779. auto ctx_se = detail::scope_exit([&] {
  11780. if (ctx) { tls::free_context(ctx); }
  11781. });
  11782. #endif
  11783. auto close_peer = [](Peer &peer) {
  11784. #ifdef CPPHTTPLIB_SSL_ENABLED
  11785. if (peer.session) { tls::free_session(peer.session); }
  11786. #endif
  11787. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11788. };
  11789. auto accept_peer = [&]() {
  11790. Peer peer;
  11791. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11792. peer.sock = ::accept(srv, nullptr, nullptr);
  11793. if (peer.sock == INVALID_SOCKET) { return peer; }
  11794. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11795. #ifdef CPPHTTPLIB_SSL_ENABLED
  11796. if (use_tls) {
  11797. peer.session = tls::create_session(ctx, peer.sock);
  11798. tls::TlsError err;
  11799. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11800. nullptr)) {
  11801. close_peer(peer);
  11802. return Peer();
  11803. }
  11804. }
  11805. #endif
  11806. return peer;
  11807. };
  11808. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11809. #ifdef CPPHTTPLIB_SSL_ENABLED
  11810. tls::TlsError err;
  11811. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11812. #endif
  11813. return detail::read_socket(peer.sock, buf, len, 0);
  11814. };
  11815. auto read_head = [&](const Peer &peer) {
  11816. std::string head;
  11817. char buf[1024];
  11818. while (head.find("\r\n\r\n") == std::string::npos) {
  11819. auto n = read_some(peer, buf, sizeof(buf));
  11820. if (n <= 0) { break; }
  11821. head.append(buf, static_cast<size_t>(n));
  11822. }
  11823. };
  11824. auto send_text = [](const Peer &peer, const std::string &text) {
  11825. #ifdef CPPHTTPLIB_SSL_ENABLED
  11826. tls::TlsError err;
  11827. if (peer.session) {
  11828. tls::write(peer.session, text.data(), text.size(), err);
  11829. return;
  11830. }
  11831. #endif
  11832. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11833. };
  11834. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11835. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11836. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11837. // Sent once the first response is read, so that it lands on an idle socket
  11838. std::promise<void> first_response_read;
  11839. auto first_response_read_future = first_response_read.get_future();
  11840. auto server_thread = std::thread([&] {
  11841. auto peer1 = accept_peer();
  11842. if (peer1.sock == INVALID_SOCKET) { return; }
  11843. read_head(peer1);
  11844. if (same_write) {
  11845. send_text(peer1, first + stray);
  11846. } else {
  11847. send_text(peer1, first);
  11848. first_response_read_future.wait_for(std::chrono::seconds(5));
  11849. send_text(peer1, stray);
  11850. }
  11851. // peer1 stays open, so only the unread data can tell the client
  11852. auto peer2 = accept_peer();
  11853. if (peer2.sock != INVALID_SOCKET) {
  11854. read_head(peer2);
  11855. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11856. "Connection: close\r\n\r\nsecond");
  11857. close_peer(peer2);
  11858. }
  11859. close_peer(peer1);
  11860. });
  11861. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11862. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11863. std::to_string(port));
  11864. #ifdef CPPHTTPLIB_SSL_ENABLED
  11865. cli.enable_server_certificate_verification(false);
  11866. #endif
  11867. cli.set_keep_alive(true);
  11868. cli.set_read_timeout(5, 0);
  11869. auto res = cli.Get("/1");
  11870. first_response_read.set_value();
  11871. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11872. EXPECT_EQ("first", res->body);
  11873. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11874. res = cli.Get("/2");
  11875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11876. EXPECT_EQ(StatusCode::OK_200, res->status);
  11877. EXPECT_EQ("second", res->body);
  11878. }
  11879. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11880. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11881. }
  11882. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11883. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11884. }
  11885. #ifdef CPPHTTPLIB_SSL_ENABLED
  11886. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11887. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11888. }
  11889. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11890. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11891. }
  11892. #endif
  11893. TEST(KeepAliveTest, Issue1959) {
  11894. Server svr;
  11895. svr.set_keep_alive_timeout(5);
  11896. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11897. res.set_content("a", "text/plain");
  11898. });
  11899. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11900. auto se = detail::scope_exit([&] {
  11901. if (!svr.is_running()) return;
  11902. svr.stop();
  11903. listen_thread.join();
  11904. ASSERT_FALSE(svr.is_running());
  11905. });
  11906. svr.wait_until_ready();
  11907. Client cli("localhost", PORT);
  11908. cli.set_keep_alive(true);
  11909. using namespace std::chrono;
  11910. auto start = steady_clock::now();
  11911. cli.Get("/a");
  11912. svr.stop();
  11913. listen_thread.join();
  11914. auto end = steady_clock::now();
  11915. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11916. EXPECT_LT(elapsed, 5000);
  11917. }
  11918. #ifdef CPPHTTPLIB_SSL_ENABLED
  11919. TEST(KeepAliveTest, SSLClientReconnection) {
  11920. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11921. ASSERT_TRUE(svr.is_valid());
  11922. svr.set_keep_alive_timeout(1);
  11923. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11924. res.set_content("Hello World!", "text/plain");
  11925. });
  11926. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11927. auto se = detail::scope_exit([&] {
  11928. svr.stop();
  11929. listen_thread.join();
  11930. ASSERT_FALSE(svr.is_running());
  11931. });
  11932. svr.wait_until_ready();
  11933. SSLClient cli(HOST, PORT);
  11934. cli.enable_server_certificate_verification(false);
  11935. cli.set_keep_alive(true);
  11936. auto result = cli.Get("/hi");
  11937. ASSERT_TRUE(result);
  11938. EXPECT_EQ(StatusCode::OK_200, result->status);
  11939. result = cli.Get("/hi");
  11940. ASSERT_TRUE(result);
  11941. EXPECT_EQ(StatusCode::OK_200, result->status);
  11942. std::this_thread::sleep_for(std::chrono::seconds(2));
  11943. // Recoonect
  11944. result = cli.Get("/hi");
  11945. ASSERT_TRUE(result);
  11946. EXPECT_EQ(StatusCode::OK_200, result->status);
  11947. result = cli.Get("/hi");
  11948. ASSERT_TRUE(result);
  11949. EXPECT_EQ(StatusCode::OK_200, result->status);
  11950. }
  11951. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11952. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11953. ASSERT_TRUE(svr.is_valid());
  11954. svr.set_keep_alive_timeout(1);
  11955. std::string content = "reconnect";
  11956. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11957. res.set_content("Hello World!", "text/plain");
  11958. });
  11959. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11960. auto se = detail::scope_exit([&] {
  11961. svr.stop();
  11962. listen_thread.join();
  11963. ASSERT_FALSE(svr.is_running());
  11964. });
  11965. svr.wait_until_ready();
  11966. SSLClient cli(HOST, PORT);
  11967. cli.enable_server_certificate_verification(false);
  11968. cli.set_keep_alive(true);
  11969. auto result = cli.Post(
  11970. "/hi", content.size(),
  11971. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11972. sink.write(content.c_str(), content.size());
  11973. return true;
  11974. },
  11975. "text/plain");
  11976. ASSERT_TRUE(result);
  11977. EXPECT_EQ(200, result->status);
  11978. std::this_thread::sleep_for(std::chrono::seconds(2));
  11979. // Recoonect
  11980. result = cli.Post(
  11981. "/hi", content.size(),
  11982. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11983. sink.write(content.c_str(), content.size());
  11984. return true;
  11985. },
  11986. "text/plain");
  11987. ASSERT_TRUE(result);
  11988. EXPECT_EQ(200, result->status);
  11989. result = cli.Post(
  11990. "/hi", content.size(),
  11991. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11992. sink.write(content.c_str(), content.size());
  11993. return true;
  11994. },
  11995. "text/plain");
  11996. ASSERT_TRUE(result);
  11997. EXPECT_EQ(200, result->status);
  11998. }
  11999. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  12000. using namespace httplib::tls;
  12001. {
  12002. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12003. ASSERT_TRUE(svr.is_valid());
  12004. svr.Get("/sni", [&](const Request &req, Response &res) {
  12005. std::string expected = req.sni();
  12006. EXPECT_EQ(expected, req.get_param_value("expected"));
  12007. res.set_content("ok", "text/plain");
  12008. });
  12009. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12010. auto se = detail::scope_exit([&] {
  12011. svr.stop();
  12012. listen_thread.join();
  12013. ASSERT_FALSE(svr.is_running());
  12014. });
  12015. svr.wait_until_ready();
  12016. {
  12017. SSLClient cli("localhost", PORT);
  12018. cli.enable_server_certificate_verification(false);
  12019. auto res = cli.Get("/sni?expected=localhost");
  12020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12021. }
  12022. {
  12023. SSLClient cli("::1", PORT);
  12024. cli.enable_server_certificate_verification(false);
  12025. auto res = cli.Get("/sni?expected=");
  12026. // NOTE: This may fail if the server is listening on IPv4 only
  12027. // (e.g., when localhost resolves to 127.0.0.1 only)
  12028. if (res) {
  12029. EXPECT_EQ(StatusCode::OK_200, res->status);
  12030. } else {
  12031. EXPECT_EQ(Error::Connection, res.error());
  12032. }
  12033. }
  12034. }
  12035. }
  12036. // The SNI of a failed handshake does not reach the next connection that the
  12037. // same worker thread serves
  12038. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  12039. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12040. ASSERT_TRUE(svr.is_valid());
  12041. svr.new_task_queue = [] { return new ThreadPool(1); };
  12042. svr.Get("/sni", [](const Request &req, Response &res) {
  12043. res.set_content(req.sni(), "text/plain");
  12044. });
  12045. auto port = svr.bind_to_any_port("127.0.0.1");
  12046. ASSERT_LT(0, port);
  12047. thread t = thread([&] { svr.listen_after_bind(); });
  12048. auto se = detail::scope_exit([&] {
  12049. svr.stop();
  12050. t.join();
  12051. ASSERT_FALSE(svr.is_running());
  12052. });
  12053. svr.wait_until_ready();
  12054. {
  12055. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12056. SSLClient cli("localhost", port);
  12057. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12058. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12059. auto res = cli.Get("/sni");
  12060. ASSERT_FALSE(res);
  12061. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12062. }
  12063. // An IP host sends no SNI (RFC 6066)
  12064. SSLClient cli("127.0.0.1", port);
  12065. cli.enable_server_certificate_verification(false);
  12066. auto res = cli.Get("/sni");
  12067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12068. EXPECT_EQ("", res->body);
  12069. }
  12070. #endif
  12071. TEST(ClientProblemDetectionTest, ContentProvider) {
  12072. Server svr;
  12073. size_t content_length = 1024 * 1024;
  12074. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12075. res.set_content_provider(
  12076. content_length, "text/plain",
  12077. [&](size_t offset, size_t length, DataSink &sink) {
  12078. auto out_len = std::min(length, static_cast<size_t>(1024));
  12079. std::string out(out_len, '@');
  12080. sink.write(out.data(), out_len);
  12081. return offset < 4096;
  12082. },
  12083. [](bool success) { ASSERT_FALSE(success); });
  12084. });
  12085. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12086. res.set_content_provider(
  12087. 0, "text/plain",
  12088. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12089. EXPECT_TRUE(false);
  12090. return true;
  12091. },
  12092. [](bool success) { ASSERT_FALSE(success); });
  12093. });
  12094. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12095. auto se = detail::scope_exit([&] {
  12096. svr.stop();
  12097. listen_thread.join();
  12098. ASSERT_FALSE(svr.is_running());
  12099. });
  12100. svr.wait_until_ready();
  12101. Client cli("localhost", PORT);
  12102. {
  12103. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12104. size_t /*data_length*/) { return false; });
  12105. ASSERT_FALSE(res);
  12106. }
  12107. {
  12108. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12109. size_t /*data_length*/) { return false; });
  12110. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12111. }
  12112. }
  12113. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12114. // A provider that reports success without writing anything and without
  12115. // calling done() used to be handed the same offset and length again on every
  12116. // pass, so it spun for as long as the peer stayed connected.
  12117. Server svr;
  12118. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12119. res.set_content("ok", "text/plain");
  12120. });
  12121. auto port = svr.bind_to_any_port(HOST);
  12122. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12123. auto se = detail::scope_exit([&] {
  12124. svr.stop();
  12125. listen_thread.join();
  12126. ASSERT_FALSE(svr.is_running());
  12127. });
  12128. svr.wait_until_ready();
  12129. std::atomic<int> call_count{0};
  12130. Client cli(HOST, port);
  12131. auto res = cli.Post(
  12132. "/", 1024,
  12133. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12134. // Give up after enough passes to show the spin, so that losing the
  12135. // check below fails this test instead of hanging it.
  12136. return ++call_count < 100;
  12137. },
  12138. "text/plain");
  12139. ASSERT_FALSE(res);
  12140. EXPECT_EQ(Error::Write, res.error());
  12141. EXPECT_EQ(1, call_count.load());
  12142. }
  12143. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12144. // A writer only has to assign `write`. The other three used to be left as
  12145. // empty std::functions, so a provider calling one threw
  12146. // std::bad_function_call out of the thread running it and took the whole
  12147. // process down.
  12148. DataSink sink;
  12149. std::string written;
  12150. sink.write = [&](const char *data, size_t data_len) {
  12151. written.append(data, data_len);
  12152. return true;
  12153. };
  12154. EXPECT_TRUE(sink.is_writable());
  12155. sink.done();
  12156. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12157. EXPECT_TRUE(written.empty());
  12158. }
  12159. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12160. // A sink that cannot carry trailers still has to finish.
  12161. DataSink sink;
  12162. auto done_count = 0;
  12163. sink.done = [&]() { done_count++; };
  12164. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12165. EXPECT_EQ(1, done_count);
  12166. }
  12167. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12168. Server svr;
  12169. const std::string body(4096, 'x');
  12170. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12171. res.set_content_provider(body.size(), "text/plain",
  12172. [&](size_t offset, size_t length, DataSink &sink) {
  12173. sink.write(body.data() + offset, length);
  12174. sink.done();
  12175. return true;
  12176. });
  12177. });
  12178. auto port = svr.bind_to_any_port(HOST);
  12179. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12180. auto se = detail::scope_exit([&] {
  12181. svr.stop();
  12182. listen_thread.join();
  12183. ASSERT_FALSE(svr.is_running());
  12184. });
  12185. svr.wait_until_ready();
  12186. Client cli(HOST, port);
  12187. auto res = cli.Get("/");
  12188. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12189. EXPECT_EQ(StatusCode::OK_200, res->status);
  12190. EXPECT_EQ(body, res->body);
  12191. }
  12192. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12193. Server svr;
  12194. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12195. res.set_content_provider(
  12196. 1024, "text/plain",
  12197. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12198. sink.write("hello", 5);
  12199. sink.done(); // short of the 1024 bytes the response promised
  12200. return true;
  12201. });
  12202. });
  12203. auto port = svr.bind_to_any_port(HOST);
  12204. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12205. auto se = detail::scope_exit([&] {
  12206. svr.stop();
  12207. listen_thread.join();
  12208. ASSERT_FALSE(svr.is_running());
  12209. });
  12210. svr.wait_until_ready();
  12211. Client cli(HOST, port);
  12212. cli.set_read_timeout(5, 0);
  12213. // The response is short of its Content-Length, so the client cannot read a
  12214. // complete body. What matters is that this returns at all: a no-op done()
  12215. // would leave the writer looping over a provider that never makes progress.
  12216. auto res = cli.Get("/");
  12217. EXPECT_FALSE(res);
  12218. }
  12219. // Read as the next response by a peer that sees it after a framed body.
  12220. static const std::string smuggled_response =
  12221. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12222. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12223. Server svr;
  12224. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12225. res.set_content_provider(
  12226. 5, "text/plain",
  12227. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12228. auto data = "AAAAA" + smuggled_response;
  12229. sink.write(data.data(), data.size());
  12230. return true;
  12231. });
  12232. });
  12233. thread t = thread([&] { svr.listen(HOST, PORT); });
  12234. auto se = detail::scope_exit([&] {
  12235. svr.stop();
  12236. t.join();
  12237. ASSERT_FALSE(svr.is_running());
  12238. });
  12239. svr.wait_until_ready();
  12240. std::string resp;
  12241. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12242. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12243. resp.clear();
  12244. ASSERT_TRUE(send_request(
  12245. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12246. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12247. }
  12248. TEST(NoContentTest, BodyIsNotSent) {
  12249. Server svr;
  12250. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12251. res.status = StatusCode::NoContent_204;
  12252. res.set_content(smuggled_response, "text/plain");
  12253. });
  12254. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12255. res.status = StatusCode::NotModified_304;
  12256. res.set_chunked_content_provider(
  12257. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12258. sink.write(smuggled_response.data(), smuggled_response.size());
  12259. sink.done();
  12260. return true;
  12261. });
  12262. });
  12263. thread t = thread([&] { svr.listen(HOST, PORT); });
  12264. auto se = detail::scope_exit([&] {
  12265. svr.stop();
  12266. t.join();
  12267. ASSERT_FALSE(svr.is_running());
  12268. });
  12269. svr.wait_until_ready();
  12270. for (auto path : {"/204", "/304"}) {
  12271. std::string resp;
  12272. ASSERT_TRUE(send_request(
  12273. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12274. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12275. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12276. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12277. }
  12278. }
  12279. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12280. Server svr;
  12281. std::atomic<bool> smuggled(false);
  12282. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12283. res.set_content("ok", "text/plain");
  12284. });
  12285. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12286. smuggled = true;
  12287. });
  12288. auto port = svr.bind_to_any_port(HOST);
  12289. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12290. auto se = detail::scope_exit([&] {
  12291. svr.stop();
  12292. listen_thread.join();
  12293. ASSERT_FALSE(svr.is_running());
  12294. });
  12295. svr.wait_until_ready();
  12296. // What follows the body would be read as the next request.
  12297. Client cli(HOST, port);
  12298. auto res = cli.Post(
  12299. "/", 5,
  12300. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12301. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12302. sink.write(data.data(), data.size());
  12303. return true;
  12304. },
  12305. "text/plain");
  12306. ASSERT_FALSE(res);
  12307. EXPECT_EQ(Error::Write, res.error());
  12308. EXPECT_FALSE(smuggled);
  12309. }
  12310. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12311. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12312. // The compressed path builds the whole body before connecting, so this
  12313. // fails client-side and never reaches a server.
  12314. Client cli(HOST, PORT);
  12315. cli.set_compress(true);
  12316. auto res = cli.Post(
  12317. "/", 1024,
  12318. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12319. sink.write("hello", 5);
  12320. sink.done(); // short of the 1024 bytes the request announced
  12321. return true;
  12322. },
  12323. "text/plain");
  12324. ASSERT_FALSE(res);
  12325. EXPECT_EQ(Error::Write, res.error());
  12326. }
  12327. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12328. Server svr;
  12329. std::string received;
  12330. size_t content_length_count = 0;
  12331. bool has_transfer_encoding = true;
  12332. svr.Post("/echo", [&](const Request &req, Response &res) {
  12333. received = req.body;
  12334. content_length_count = req.get_header_value_count("Content-Length");
  12335. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12336. res.set_content("ok", "text/plain");
  12337. });
  12338. svr.Get("/next", [](const Request &, Response &res) {
  12339. res.set_content("next", "text/plain");
  12340. });
  12341. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12342. auto se = detail::scope_exit([&] {
  12343. svr.stop();
  12344. listen_thread.join();
  12345. ASSERT_FALSE(svr.is_running());
  12346. });
  12347. svr.wait_until_ready();
  12348. Client cli(HOST, PORT);
  12349. cli.set_keep_alive(true);
  12350. cli.set_compress(true);
  12351. const std::string body = "hello world";
  12352. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12353. auto res = cli.Post("/echo", headers, body, "text/plain");
  12354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12355. EXPECT_EQ(StatusCode::OK_200, res->status);
  12356. EXPECT_EQ(body, received);
  12357. EXPECT_EQ(1u, content_length_count);
  12358. EXPECT_FALSE(has_transfer_encoding);
  12359. // The rest of a truncated body would be read as this request
  12360. auto res2 = cli.Get("/next");
  12361. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12362. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12363. EXPECT_EQ("next", res2->body);
  12364. }
  12365. #endif
  12366. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12367. Server svr;
  12368. std::string received;
  12369. size_t content_length_count = 1;
  12370. bool has_transfer_encoding = false;
  12371. svr.Post("/echo", [&](const Request &req, Response &res) {
  12372. received = req.body;
  12373. content_length_count = req.get_header_value_count("Content-Length");
  12374. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12375. res.set_content("ok", "text/plain");
  12376. });
  12377. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12378. auto se = detail::scope_exit([&] {
  12379. svr.stop();
  12380. listen_thread.join();
  12381. ASSERT_FALSE(svr.is_running());
  12382. });
  12383. svr.wait_until_ready();
  12384. Client cli(HOST, PORT);
  12385. cli.set_keep_alive(true);
  12386. const std::string body = "hello world";
  12387. Headers headers = {{"Content-Length", "5"}};
  12388. auto res = cli.Post(
  12389. "/echo", headers,
  12390. [&](size_t /*offset*/, DataSink &sink) {
  12391. sink.write(body.data(), body.size());
  12392. sink.done();
  12393. return true;
  12394. },
  12395. "text/plain");
  12396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12397. EXPECT_EQ(StatusCode::OK_200, res->status);
  12398. EXPECT_EQ(body, received);
  12399. EXPECT_EQ(0u, content_length_count);
  12400. EXPECT_TRUE(has_transfer_encoding);
  12401. }
  12402. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12403. Server svr;
  12404. svr.set_error_handler([](Request const &, Response &res) -> void {
  12405. res.set_chunked_content_provider(
  12406. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12407. sink.os << "hello";
  12408. sink.os << "world";
  12409. sink.done();
  12410. return true;
  12411. });
  12412. });
  12413. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12414. auto se = detail::scope_exit([&] {
  12415. svr.stop();
  12416. listen_thread.join();
  12417. ASSERT_FALSE(svr.is_running());
  12418. });
  12419. svr.wait_until_ready();
  12420. Client cli("localhost", PORT);
  12421. auto res = cli.Get("/");
  12422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12423. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12424. EXPECT_EQ("helloworld", res->body);
  12425. }
  12426. // A body set after a content provider must replace it, not be sent through it.
  12427. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12428. Server svr;
  12429. svr.set_mount_point("/", "./www");
  12430. svr.set_file_request_handler([](const Request &req, Response &res) {
  12431. if (req.path == "/dir/test.html") {
  12432. res.status = StatusCode::Forbidden_403;
  12433. res.set_content(std::string(5000, 'D'), "text/plain");
  12434. } else if (req.path == "/file") {
  12435. res.status = StatusCode::Forbidden_403;
  12436. res.body = "Denied";
  12437. }
  12438. });
  12439. auto port = svr.bind_to_any_port(HOST);
  12440. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12441. auto se = detail::scope_exit([&] {
  12442. svr.stop();
  12443. t.join();
  12444. ASSERT_FALSE(svr.is_running());
  12445. });
  12446. svr.wait_until_ready();
  12447. Client cli(HOST, port);
  12448. {
  12449. auto res = cli.Get("/dir/test.html");
  12450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12451. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12452. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12453. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12454. }
  12455. {
  12456. auto res = cli.Get("/file");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12459. EXPECT_EQ("Denied", res->body);
  12460. }
  12461. {
  12462. auto res = cli.Get("/dir/index.html");
  12463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12464. EXPECT_EQ(StatusCode::OK_200, res->status);
  12465. EXPECT_EQ(0U, res->body.find("<html>"));
  12466. }
  12467. }
  12468. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12469. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12470. Server svr;
  12471. std::vector<bool> released;
  12472. std::mutex released_mutex;
  12473. auto releaser = [&](bool success) {
  12474. std::lock_guard<std::mutex> guard(released_mutex);
  12475. released.push_back(success);
  12476. };
  12477. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12478. return sink.write(&"hello"[offset], length);
  12479. };
  12480. svr.Get("/sized", [&](const Request &, Response &res) {
  12481. res.status = StatusCode::NotFound_404;
  12482. res.set_content_provider(5, "text/plain", provider, releaser);
  12483. });
  12484. svr.Get("/chunked", [&](const Request &, Response &res) {
  12485. res.status = StatusCode::ServiceUnavailable_503;
  12486. res.set_chunked_content_provider(
  12487. "text/plain",
  12488. [](size_t, DataSink &sink) {
  12489. sink.os << "chunk";
  12490. sink.done();
  12491. return true;
  12492. },
  12493. releaser);
  12494. });
  12495. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12496. res.set_content_provider(5, "text/plain", provider, releaser);
  12497. throw std::runtime_error("after the provider");
  12498. });
  12499. svr.set_error_handler([](const Request &req, Response &res) {
  12500. // Leave the exception handler's content to it.
  12501. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12502. res.set_content(std::string(1000, 'E'), "text/html");
  12503. return Server::HandlerResponse::Handled;
  12504. });
  12505. svr.set_exception_handler(
  12506. [](const Request &, Response &res, std::exception_ptr) {
  12507. res.status = StatusCode::InternalServerError_500;
  12508. res.set_content(std::string(1000, 'X'), "text/html");
  12509. });
  12510. auto port = svr.bind_to_any_port(HOST);
  12511. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12512. auto se = detail::scope_exit([&] {
  12513. svr.stop();
  12514. t.join();
  12515. ASSERT_FALSE(svr.is_running());
  12516. });
  12517. svr.wait_until_ready();
  12518. Client cli(HOST, port);
  12519. {
  12520. auto res = cli.Get("/sized");
  12521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12522. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12523. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12524. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12525. }
  12526. {
  12527. auto res = cli.Get("/chunked");
  12528. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12529. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12530. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12531. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12532. }
  12533. {
  12534. auto res = cli.Get("/throw");
  12535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12536. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12537. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12538. }
  12539. std::lock_guard<std::mutex> guard(released_mutex);
  12540. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12541. }
  12542. #endif
  12543. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12544. Server svr;
  12545. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12546. return sink.write(&"abc"[offset], length);
  12547. };
  12548. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12549. res.set_file_content("./www/dir/test.html");
  12550. res.set_content("body", "text/plain");
  12551. });
  12552. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12553. res.set_content(std::string(100, 'B'), "text/plain");
  12554. res.set_file_content("./www/dir/test.html");
  12555. });
  12556. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12557. res.set_content(std::string(100, 'B'), "text/plain");
  12558. res.set_content_provider(3, "text/x-provider", abc);
  12559. });
  12560. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12561. res.set_content_provider(3, "text/x-provider", abc);
  12562. res.set_content(std::string(100, 'B'), "text/plain");
  12563. });
  12564. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12565. res.set_content_provider(3, "text/x-provider", abc);
  12566. res.set_file_content("./www/dir/test.html", "text/x-file");
  12567. });
  12568. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12569. res.set_file_content("./www/dir/test.html");
  12570. res.set_header("Content-Type", "text/x-handler");
  12571. });
  12572. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12573. res.set_content_provider(3, "text/plain", abc);
  12574. res.body = "direct";
  12575. });
  12576. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12577. res.set_file_content("./www/dir/test.html");
  12578. res.body = "direct";
  12579. });
  12580. auto port = svr.bind_to_any_port(HOST);
  12581. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12582. auto se = detail::scope_exit([&] {
  12583. svr.stop();
  12584. t.join();
  12585. ASSERT_FALSE(svr.is_running());
  12586. });
  12587. svr.wait_until_ready();
  12588. Client cli(HOST, port);
  12589. auto expect_body = [&](const char *path, const std::string &body,
  12590. const std::string &type) {
  12591. // Uncompressed, so Content-Length can be compared with the body.
  12592. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12593. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12594. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12595. EXPECT_EQ(body, res->body) << path;
  12596. EXPECT_EQ(std::to_string(body.size()),
  12597. res->get_header_value("Content-Length"))
  12598. << path;
  12599. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12600. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12601. };
  12602. expect_body("/file-then-body", "body", "text/plain");
  12603. expect_body("/body-then-file", "test.html", "text/html");
  12604. expect_body("/body-then-provider", "abc", "text/x-provider");
  12605. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12606. expect_body("/provider-then-file", "test.html", "text/x-file");
  12607. expect_body("/file-then-header", "test.html", "text/x-handler");
  12608. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12609. expect_body("/file-then-direct-body", "direct", "text/plain");
  12610. // Ranges are checked against the body, not the dropped provider.
  12611. {
  12612. auto res = cli.Get("/provider-then-direct-body",
  12613. Headers{{make_range_header({{1, 2}})}});
  12614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12615. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12616. EXPECT_EQ("ir", res->body);
  12617. }
  12618. {
  12619. auto res = cli.Get("/file-then-direct-body",
  12620. Headers{{make_range_header({{7, 8}})}});
  12621. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12622. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12623. }
  12624. }
  12625. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12626. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12627. const char *path = "./truncated_while_served.txt";
  12628. const size_t size = 32 * 1024 * 1024;
  12629. {
  12630. std::ofstream f(path, std::ios::binary);
  12631. f << std::string(size, 'x');
  12632. }
  12633. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12634. // Over TLS, where the bytes are encrypted in this process rather than
  12635. // copied by send().
  12636. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12637. svr.Get("/file", [&](const Request &, Response &res) {
  12638. res.set_file_content(path, "text/plain");
  12639. });
  12640. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12641. auto se = detail::scope_exit([&] {
  12642. svr.stop();
  12643. thread.join();
  12644. ASSERT_FALSE(svr.is_running());
  12645. });
  12646. svr.wait_until_ready();
  12647. // The file shrinks once the first bytes are in, as a rewrite in place
  12648. // would, and reading the mapping past its new end used to raise SIGBUS.
  12649. SSLClient cli(HOST, PORT);
  12650. cli.enable_server_certificate_verification(false);
  12651. size_t received = 0;
  12652. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12653. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12654. received += len;
  12655. return true;
  12656. });
  12657. EXPECT_FALSE(res);
  12658. EXPECT_LT(received, size);
  12659. }
  12660. #endif
  12661. // Forward declaration (see the base64_encode note).
  12662. namespace httplib {
  12663. namespace detail {
  12664. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12665. const std::string &content_type,
  12666. EncodingType encoding);
  12667. } // namespace detail
  12668. } // namespace httplib
  12669. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12670. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12671. ASSERT_TRUE(mm->is_open());
  12672. Response res;
  12673. detail::set_file_content_provider(res, mm, "text/html",
  12674. detail::EncodingType::None);
  12675. std::string out;
  12676. DataSink sink;
  12677. sink.write = [&](const char *d, size_t l) {
  12678. out.append(d, l);
  12679. return true;
  12680. };
  12681. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12682. EXPECT_EQ("test.html", out);
  12683. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12684. EXPECT_EQ("test.html", out);
  12685. }
  12686. TEST(LongPollingTest, ClientCloseDetection) {
  12687. Server svr;
  12688. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12689. res.set_chunked_content_provider(
  12690. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12691. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12692. sink.os << "hello";
  12693. auto count = 10;
  12694. while (count > 0 && sink.is_writable()) {
  12695. this_thread::sleep_for(chrono::milliseconds(10));
  12696. count--;
  12697. }
  12698. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12699. return true;
  12700. });
  12701. });
  12702. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  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(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12717. Server svr;
  12718. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12719. res.set_chunked_content_provider(
  12720. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12721. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12722. sink.os << "hello";
  12723. EXPECT_TRUE(sink.os.good());
  12724. // Wait for the client to close the connection
  12725. auto count = 10;
  12726. while (count > 0 && sink.is_writable()) {
  12727. this_thread::sleep_for(chrono::milliseconds(10));
  12728. count--;
  12729. }
  12730. // After client disconnect, write repeatedly until the socket
  12731. // write actually fails (small writes may be absorbed by the
  12732. // kernel buffer)
  12733. std::string chunk(1024, 'x');
  12734. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12735. sink.os << chunk;
  12736. }
  12737. EXPECT_TRUE(sink.os.fail());
  12738. return true;
  12739. });
  12740. });
  12741. auto port = svr.bind_to_any_port("localhost");
  12742. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12743. auto se = detail::scope_exit([&] {
  12744. svr.stop();
  12745. listen_thread.join();
  12746. ASSERT_FALSE(svr.is_running());
  12747. });
  12748. svr.wait_until_ready();
  12749. Client cli("localhost", port);
  12750. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12751. EXPECT_EQ("hello", string(data, data_length));
  12752. return false; // close the socket immediately.
  12753. });
  12754. ASSERT_FALSE(res);
  12755. }
  12756. TEST(GetWithParametersTest, GetWithParameters) {
  12757. Server svr;
  12758. svr.Get("/", [&](const Request &req, Response &) {
  12759. EXPECT_EQ("world", req.get_param_value("hello"));
  12760. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12761. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12762. });
  12763. svr.Get("/params", [&](const Request &req, Response &) {
  12764. EXPECT_EQ("world", req.get_param_value("hello"));
  12765. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12766. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12767. });
  12768. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12769. EXPECT_EQ("resource-id", req.matches[1]);
  12770. EXPECT_EQ("foo", req.get_param_value("param1"));
  12771. EXPECT_EQ("bar", req.get_param_value("param2"));
  12772. });
  12773. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12774. EXPECT_EQ("user-id", req.path_params.at("id"));
  12775. EXPECT_EQ("foo", req.get_param_value("param1"));
  12776. EXPECT_EQ("bar", req.get_param_value("param2"));
  12777. });
  12778. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12779. auto se = detail::scope_exit([&] {
  12780. svr.stop();
  12781. listen_thread.join();
  12782. ASSERT_FALSE(svr.is_running());
  12783. });
  12784. svr.wait_until_ready();
  12785. {
  12786. Client cli(HOST, PORT);
  12787. Params params;
  12788. params.emplace("hello", "world");
  12789. params.emplace("hello2", "world2");
  12790. params.emplace("hello3", "world3");
  12791. auto res = cli.Get("/", params, Headers{});
  12792. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12793. EXPECT_EQ(StatusCode::OK_200, res->status);
  12794. }
  12795. {
  12796. Client cli(HOST, PORT);
  12797. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  12798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12799. EXPECT_EQ(StatusCode::OK_200, res->status);
  12800. }
  12801. {
  12802. Client cli(HOST, PORT);
  12803. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  12804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12805. EXPECT_EQ(StatusCode::OK_200, res->status);
  12806. }
  12807. {
  12808. Client cli(HOST, PORT);
  12809. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  12810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12811. EXPECT_EQ(StatusCode::OK_200, res->status);
  12812. }
  12813. }
  12814. TEST(GetWithParametersTest, GetWithParameters2) {
  12815. Server svr;
  12816. svr.Get("/", [&](const Request &req, Response &res) {
  12817. auto text = req.get_param_value("hello");
  12818. res.set_content(text, "text/plain");
  12819. });
  12820. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12821. auto se = detail::scope_exit([&] {
  12822. svr.stop();
  12823. listen_thread.join();
  12824. ASSERT_FALSE(svr.is_running());
  12825. });
  12826. svr.wait_until_ready();
  12827. Client cli("localhost", PORT);
  12828. Params params;
  12829. params.emplace("hello", "world");
  12830. std::string body;
  12831. auto res = cli.Get("/", params, Headers{},
  12832. [&](const char *data, size_t data_length) {
  12833. body.append(data, data_length);
  12834. return true;
  12835. });
  12836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12837. EXPECT_EQ(StatusCode::OK_200, res->status);
  12838. EXPECT_EQ("world", body);
  12839. }
  12840. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12841. Server svr;
  12842. svr.Get("/search", [&](const Request &req, Response &res) {
  12843. auto q = req.get_param_value("q");
  12844. res.set_content(q, "text/plain");
  12845. });
  12846. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12847. auto se = detail::scope_exit([&] {
  12848. svr.stop();
  12849. listen_thread.join();
  12850. ASSERT_FALSE(svr.is_running());
  12851. });
  12852. svr.wait_until_ready();
  12853. Client cli("localhost", PORT);
  12854. // Verify that Get(path, params) works without requiring Headers argument
  12855. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12857. EXPECT_EQ(StatusCode::OK_200, res->status);
  12858. EXPECT_EQ("cpp-httplib", res->body);
  12859. }
  12860. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12861. auto host = "httpbingo.org";
  12862. auto path = std::string{"/range/32"};
  12863. #ifdef CPPHTTPLIB_SSL_ENABLED
  12864. SSLClient cli(host);
  12865. #else
  12866. Client cli(host);
  12867. #endif
  12868. cli.set_default_headers({make_range_header({{1, 10}})});
  12869. cli.set_connection_timeout(5);
  12870. {
  12871. auto res = retry_service_failures([&] { return cli.Get(path); });
  12872. SKIP_ON_SERVICE_FAILURE(res);
  12873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12874. EXPECT_EQ("bcdefghijk", res->body);
  12875. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12876. }
  12877. {
  12878. auto res = retry_service_failures([&] { return cli.Get(path); });
  12879. SKIP_ON_SERVICE_FAILURE(res);
  12880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12881. EXPECT_EQ("bcdefghijk", res->body);
  12882. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12883. }
  12884. }
  12885. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12886. Server svr;
  12887. svr.set_default_headers({{"Hello", "World"}});
  12888. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12889. res.set_content("ok", "text/plain");
  12890. });
  12891. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12892. auto se = detail::scope_exit([&] {
  12893. svr.stop();
  12894. listen_thread.join();
  12895. ASSERT_FALSE(svr.is_running());
  12896. });
  12897. svr.wait_until_ready();
  12898. Client cli("localhost", PORT);
  12899. auto res = cli.Get("/");
  12900. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12901. EXPECT_EQ(StatusCode::OK_200, res->status);
  12902. EXPECT_EQ("ok", res->body);
  12903. EXPECT_EQ("World", res->get_header_value("Hello"));
  12904. }
  12905. #ifdef CPPHTTPLIB_SSL_ENABLED
  12906. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12907. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12908. ASSERT_TRUE(svr.is_valid());
  12909. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12910. std::this_thread::sleep_for(std::chrono::seconds(2));
  12911. res.set_content("a", "text/plain");
  12912. });
  12913. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12914. res.set_content("b", "text/plain");
  12915. });
  12916. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12917. auto se = detail::scope_exit([&] {
  12918. svr.stop();
  12919. listen_thread.join();
  12920. ASSERT_FALSE(svr.is_running());
  12921. });
  12922. svr.wait_until_ready();
  12923. SSLClient cli("localhost", PORT);
  12924. cli.enable_server_certificate_verification(false);
  12925. cli.set_keep_alive(true);
  12926. cli.set_read_timeout(std::chrono::seconds(1));
  12927. auto resa = cli.Get("/a");
  12928. ASSERT_TRUE(!resa);
  12929. EXPECT_EQ(Error::Read, resa.error());
  12930. auto resb = cli.Get("/b");
  12931. ASSERT_TRUE(resb);
  12932. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12933. EXPECT_EQ("b", resb->body);
  12934. }
  12935. // Closing an idle keep-alive connection sends close_notify and returns. The
  12936. // server must not wait for the client's close_notify: an idle client never
  12937. // sends one, so the worker would be held until the read timeout expires, and
  12938. // stop() would wait for it.
  12939. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12940. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12941. ASSERT_TRUE(svr.is_valid());
  12942. svr.set_keep_alive_timeout(1);
  12943. svr.set_read_timeout(10, 0);
  12944. svr.Get("/", [](const Request &, Response &res) {
  12945. res.set_content("ok", "text/plain");
  12946. });
  12947. auto port = svr.bind_to_any_port(HOST);
  12948. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12949. auto se = detail::scope_exit([&] {
  12950. if (listen_thread.joinable()) {
  12951. svr.stop();
  12952. listen_thread.join();
  12953. }
  12954. });
  12955. svr.wait_until_ready();
  12956. SSLClient cli(HOST, port);
  12957. cli.enable_server_certificate_verification(false);
  12958. cli.set_keep_alive(true);
  12959. auto res = cli.Get("/");
  12960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12961. EXPECT_EQ(StatusCode::OK_200, res->status);
  12962. // Stay idle past the keep-alive timeout so the server closes the connection.
  12963. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12964. auto start = std::chrono::steady_clock::now();
  12965. svr.stop();
  12966. listen_thread.join();
  12967. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12968. std::chrono::steady_clock::now() - start)
  12969. .count();
  12970. EXPECT_LT(elapsed, 3000);
  12971. }
  12972. #endif
  12973. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12974. protected:
  12975. ServerTestWithAI_PASSIVE()
  12976. : cli_(HOST, PORT)
  12977. #ifdef CPPHTTPLIB_SSL_ENABLED
  12978. ,
  12979. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12980. #endif
  12981. {
  12982. #ifdef CPPHTTPLIB_SSL_ENABLED
  12983. cli_.enable_server_certificate_verification(false);
  12984. #endif
  12985. }
  12986. virtual void SetUp() {
  12987. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12988. res.set_content("Hello World!", "text/plain");
  12989. });
  12990. t_ = thread(
  12991. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12992. svr_.wait_until_ready();
  12993. }
  12994. virtual void TearDown() {
  12995. svr_.stop();
  12996. t_.join();
  12997. }
  12998. #ifdef CPPHTTPLIB_SSL_ENABLED
  12999. SSLClient cli_;
  13000. SSLServer svr_;
  13001. #else
  13002. Client cli_;
  13003. Server svr_;
  13004. #endif
  13005. thread t_;
  13006. };
  13007. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  13008. auto res = cli_.Get("/hi");
  13009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13010. EXPECT_EQ(StatusCode::OK_200, res->status);
  13011. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  13012. EXPECT_EQ("Hello World!", res->body);
  13013. }
  13014. class ServerUpDownTest : public ::testing::Test {
  13015. protected:
  13016. ServerUpDownTest() : cli_(HOST, PORT) {}
  13017. virtual void SetUp() {
  13018. t_ = thread([&]() {
  13019. svr_.bind_to_any_port(HOST);
  13020. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13021. ASSERT_TRUE(svr_.listen_after_bind());
  13022. });
  13023. svr_.wait_until_ready();
  13024. }
  13025. virtual void TearDown() {
  13026. svr_.stop();
  13027. t_.join();
  13028. }
  13029. Client cli_;
  13030. Server svr_;
  13031. thread t_;
  13032. };
  13033. TEST_F(ServerUpDownTest, QuickStartStop) {
  13034. // Should not crash, especially when run with
  13035. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  13036. }
  13037. class PayloadMaxLengthTest : public ::testing::Test {
  13038. protected:
  13039. PayloadMaxLengthTest()
  13040. : cli_(HOST, PORT)
  13041. #ifdef CPPHTTPLIB_SSL_ENABLED
  13042. ,
  13043. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13044. #endif
  13045. {
  13046. #ifdef CPPHTTPLIB_SSL_ENABLED
  13047. cli_.enable_server_certificate_verification(false);
  13048. #endif
  13049. }
  13050. virtual void SetUp() {
  13051. svr_.set_payload_max_length(8);
  13052. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13053. res.set_content("test", "text/plain");
  13054. });
  13055. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13056. svr_.wait_until_ready();
  13057. }
  13058. virtual void TearDown() {
  13059. svr_.stop();
  13060. t_.join();
  13061. }
  13062. #ifdef CPPHTTPLIB_SSL_ENABLED
  13063. SSLClient cli_;
  13064. SSLServer svr_;
  13065. #else
  13066. Client cli_;
  13067. Server svr_;
  13068. #endif
  13069. thread t_;
  13070. };
  13071. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13072. auto res = cli_.Post("/test", "123456789", "text/plain");
  13073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13074. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13075. res = cli_.Post("/test", "12345678", "text/plain");
  13076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13077. EXPECT_EQ(StatusCode::OK_200, res->status);
  13078. }
  13079. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13080. // Test chunked encoding with payload exceeding the 8-byte limit
  13081. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13082. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13084. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13085. }
  13086. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13087. // Test chunked encoding with payload within the 8-byte limit
  13088. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13089. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13091. EXPECT_EQ(StatusCode::OK_200, res->status);
  13092. }
  13093. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13094. // Test using send_request to send chunked data exceeding payload limit
  13095. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13096. "Host: " +
  13097. std::string(HOST) + ":" + std::to_string(PORT) +
  13098. "\r\n"
  13099. "Transfer-Encoding: chunked\r\n"
  13100. "Connection: close\r\n"
  13101. "\r\n"
  13102. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13103. "0123456789\r\n"
  13104. "0\r\n" // End chunk
  13105. "\r\n";
  13106. std::string response;
  13107. bool result = send_request(1, chunked_request, &response);
  13108. if (!result) {
  13109. // If send_request fails, it might be because the server closed the
  13110. // connection due to payload limit enforcement, which is acceptable
  13111. SUCCEED()
  13112. << "Server rejected oversized chunked request (connection closed)";
  13113. } else {
  13114. // If we got a response, check if it's an error response or connection was
  13115. // closed early Short response length indicates connection was closed due to
  13116. // payload limit
  13117. if (response.length() <= 10) {
  13118. SUCCEED() << "Server closed connection for oversized chunked request";
  13119. } else {
  13120. // Check for error status codes
  13121. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13122. response.find("Payload Too Large") != std::string::npos ||
  13123. response.find("400") != std::string::npos);
  13124. }
  13125. }
  13126. }
  13127. class LargePayloadMaxLengthTest : public ::testing::Test {
  13128. protected:
  13129. LargePayloadMaxLengthTest()
  13130. : cli_(HOST, PORT)
  13131. #ifdef CPPHTTPLIB_SSL_ENABLED
  13132. ,
  13133. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13134. #endif
  13135. {
  13136. #ifdef CPPHTTPLIB_SSL_ENABLED
  13137. cli_.enable_server_certificate_verification(false);
  13138. #endif
  13139. }
  13140. virtual void SetUp() {
  13141. // Set 10MB payload limit
  13142. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13143. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13144. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13145. res.set_content("Large payload test", "text/plain");
  13146. });
  13147. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13148. svr_.wait_until_ready();
  13149. }
  13150. virtual void TearDown() {
  13151. svr_.stop();
  13152. t_.join();
  13153. }
  13154. #ifdef CPPHTTPLIB_SSL_ENABLED
  13155. SSLClient cli_;
  13156. SSLServer svr_;
  13157. #else
  13158. Client cli_;
  13159. Server svr_;
  13160. #endif
  13161. thread t_;
  13162. };
  13163. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13164. // Test chunked encoding with payload within 10MB limit
  13165. std::string medium_payload(5 * 1024 * 1024,
  13166. 'A'); // 5MB payload, within 10MB limit
  13167. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13169. EXPECT_EQ(StatusCode::OK_200, res->status);
  13170. }
  13171. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13172. // Test chunked encoding with payload exceeding 10MB limit
  13173. std::string large_payload(12 * 1024 * 1024,
  13174. 'B'); // 12MB payload, exceeds 10MB limit
  13175. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13176. // Server may either return 413 or close the connection
  13177. if (res) {
  13178. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13179. } else {
  13180. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13181. }
  13182. }
  13183. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13184. Server svr;
  13185. svr.Get("/", [](const Request &, Response &res) {
  13186. // Claims the most the client accepts, far more than it sends, then drops
  13187. // the connection.
  13188. res.set_content_provider(std::string().max_size(), "text/plain",
  13189. [](size_t, size_t, DataSink &sink) {
  13190. sink.write("abc", 3);
  13191. return false;
  13192. });
  13193. });
  13194. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13195. auto se = detail::scope_exit([&] {
  13196. svr.stop();
  13197. thread.join();
  13198. ASSERT_FALSE(svr.is_running());
  13199. });
  13200. svr.wait_until_ready();
  13201. Client cli(HOST, PORT);
  13202. cli.set_payload_max_length(0);
  13203. EXPECT_FALSE(cli.Get("/"));
  13204. }
  13205. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13206. // Stream API does, not as a plain read failure
  13207. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13208. Server svr;
  13209. svr.Get("/big", [](const Request &, Response &res) {
  13210. res.set_content(std::string(100000, 'b'), "text/plain");
  13211. });
  13212. auto port = svr.bind_to_any_port(HOST);
  13213. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13214. auto se = detail::scope_exit([&] {
  13215. svr.stop();
  13216. thread.join();
  13217. });
  13218. svr.wait_until_ready();
  13219. Client cli(HOST, port);
  13220. cli.set_payload_max_length(1000);
  13221. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13222. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13223. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13224. [](const char *, size_t) { return true; });
  13225. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13226. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13227. // Small on the wire, over the limit once decompressed
  13228. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13229. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13230. #endif
  13231. }
  13232. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13233. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13234. // path.
  13235. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13236. Server svr;
  13237. const size_t LIMIT = 64 * 1024; // 64KB
  13238. svr.set_payload_max_length(LIMIT);
  13239. size_t total = 0;
  13240. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13241. const ContentReader &content_reader) {
  13242. content_reader([&](const char * /*data*/, size_t len) {
  13243. total += len;
  13244. return true;
  13245. });
  13246. res.status = 200;
  13247. res.set_content("stream_ok", "text/plain");
  13248. });
  13249. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13250. auto se = detail::scope_exit([&] {
  13251. svr.stop();
  13252. thread.join();
  13253. ASSERT_FALSE(svr.is_running());
  13254. });
  13255. svr.wait_until_ready();
  13256. // Prepare 256KB raw data and gzip-compress it
  13257. std::string raw(256 * 1024, 'A');
  13258. std::string gz;
  13259. {
  13260. z_stream zs{};
  13261. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13262. Z_DEFAULT_STRATEGY);
  13263. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13264. zs.avail_in = static_cast<uInt>(raw.size());
  13265. char outbuf[4096];
  13266. int ret;
  13267. do {
  13268. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13269. zs.avail_out = sizeof(outbuf);
  13270. ret = deflate(&zs, Z_FINISH);
  13271. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13272. } while (ret != Z_STREAM_END);
  13273. deflateEnd(&zs);
  13274. }
  13275. Client cli(HOST, PORT);
  13276. cli.set_connection_timeout(std::chrono::seconds(5));
  13277. Headers headers = {{"Content-Encoding", "gzip"}};
  13278. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13279. "application/octet-stream");
  13280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13281. // Server must reject oversized decompressed payloads with 413.
  13282. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13283. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13284. EXPECT_LE(total, LIMIT);
  13285. }
  13286. #endif
  13287. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13288. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13289. // the payload must be passed through untouched instead of being rejected.
  13290. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13291. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13292. Server svr;
  13293. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13294. res.set_content(body, "image/jpeg");
  13295. res.set_header("Content-Encoding", "UTF-8");
  13296. });
  13297. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13298. res.set_content(body, "image/jpeg");
  13299. res.set_header("Content-Encoding", "identity");
  13300. });
  13301. svr.Post("/echo", [](const Request &req, Response &res) {
  13302. res.set_content(req.body, "image/jpeg");
  13303. });
  13304. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13305. auto se = detail::scope_exit([&] {
  13306. svr.stop();
  13307. t.join();
  13308. ASSERT_FALSE(svr.is_running());
  13309. });
  13310. svr.wait_until_ready();
  13311. Client cli(HOST, PORT);
  13312. {
  13313. auto res = cli.Get("/image");
  13314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13315. EXPECT_EQ(StatusCode::OK_200, res->status);
  13316. EXPECT_EQ(body, res->body);
  13317. }
  13318. {
  13319. auto res = cli.Get("/identity");
  13320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13321. EXPECT_EQ(StatusCode::OK_200, res->status);
  13322. EXPECT_EQ(body, res->body);
  13323. }
  13324. {
  13325. // The same applies to a request body reaching the server.
  13326. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13327. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13328. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13329. EXPECT_EQ(StatusCode::OK_200, res->status);
  13330. EXPECT_EQ(body, res->body);
  13331. }
  13332. }
  13333. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13334. // gzip-encoded response even when the build has no zlib support.
  13335. static const char GZIPPED_HELLO_WORLD[] = {
  13336. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13337. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13338. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13339. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13340. // A content coding is a whole token, not something the field value merely
  13341. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13342. // as "fibre" look like Brotli, and turned a multi-coding value like
  13343. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13344. // it was never meant to see.
  13345. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13346. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13347. Server svr;
  13348. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13349. res.set_content(body, "image/jpeg");
  13350. res.set_header("Content-Encoding", "fibre");
  13351. });
  13352. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13353. res.set_content(body, "image/jpeg");
  13354. res.set_header("Content-Encoding", "gzip, br");
  13355. });
  13356. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13357. res.set_content(body, "image/jpeg");
  13358. res.set_header("Content-Encoding", "x-zstd-ish");
  13359. });
  13360. auto port = svr.bind_to_any_port(HOST);
  13361. thread t = thread([&]() { svr.listen_after_bind(); });
  13362. auto se = detail::scope_exit([&] {
  13363. svr.stop();
  13364. t.join();
  13365. ASSERT_FALSE(svr.is_running());
  13366. });
  13367. svr.wait_until_ready();
  13368. Client cli(HOST, port);
  13369. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13370. auto res = cli.Get(path);
  13371. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13372. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13373. // Not a coding we recognize, so the payload comes back untouched
  13374. EXPECT_EQ(body, res->body) << path;
  13375. }
  13376. }
  13377. // A content coding cpp-httplib recognizes but was not built with must be
  13378. // reported as such. Handing the still-compressed payload back to the caller
  13379. // would silently corrupt it.
  13380. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13381. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13382. Server svr;
  13383. // "image/jpeg" keeps the server from applying a content coding of its own,
  13384. // so the hand-crafted Content-Encoding below survives.
  13385. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13386. res.set_content(gzipped, "image/jpeg");
  13387. res.set_header("Content-Encoding", "gzip");
  13388. });
  13389. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13390. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13391. res.set_content(gzipped, "image/jpeg");
  13392. res.set_header("Content-Encoding", "GZIP");
  13393. });
  13394. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13395. auto se = detail::scope_exit([&] {
  13396. svr.stop();
  13397. t.join();
  13398. ASSERT_FALSE(svr.is_running());
  13399. });
  13400. svr.wait_until_ready();
  13401. Client cli(HOST, PORT);
  13402. {
  13403. auto res = cli.Get("/gzipped");
  13404. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13406. EXPECT_EQ("Hello World!", res->body);
  13407. #else
  13408. ASSERT_FALSE(res);
  13409. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13410. #endif
  13411. }
  13412. {
  13413. // open_stream() must behave the same way.
  13414. auto handle = cli.open_stream("GET", "/gzipped");
  13415. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13416. ASSERT_TRUE(handle.is_valid());
  13417. std::string received;
  13418. char buf[256];
  13419. ssize_t n;
  13420. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13421. received.append(buf, static_cast<size_t>(n));
  13422. }
  13423. EXPECT_EQ("Hello World!", received);
  13424. #else
  13425. EXPECT_FALSE(handle.is_valid());
  13426. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13427. #endif
  13428. }
  13429. {
  13430. // A differently-cased coding must not be mistaken for an unknown one, or
  13431. // the body would be handed back still compressed.
  13432. auto res = cli.Get("/gzipped-uppercase");
  13433. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13434. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13435. EXPECT_EQ("Hello World!", res->body);
  13436. #else
  13437. ASSERT_FALSE(res);
  13438. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13439. #endif
  13440. }
  13441. }
  13442. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13443. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13444. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13445. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13446. // body a second time and appending a second Content-Encoding field line, so
  13447. // clients that decode one coding per listed value handed back raw gzip bytes.
  13448. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13449. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13450. Server svr;
  13451. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13452. // keeps the server from applying a coding of its own.
  13453. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13454. res.set_content(gzipped, "text/plain");
  13455. res.set_header("Content-Encoding", "gzip");
  13456. });
  13457. auto port = svr.bind_to_any_port(HOST);
  13458. thread t = thread([&]() { svr.listen_after_bind(); });
  13459. auto se = detail::scope_exit([&] {
  13460. svr.stop();
  13461. t.join();
  13462. ASSERT_FALSE(svr.is_running());
  13463. });
  13464. svr.wait_until_ready();
  13465. Client cli(HOST, port);
  13466. Headers headers = {{"Accept-Encoding", "gzip"}};
  13467. auto res = cli.Get("/pre-gzipped", headers);
  13468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13469. EXPECT_EQ(StatusCode::OK_200, res->status);
  13470. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13471. EXPECT_EQ("Hello World!", res->body);
  13472. }
  13473. // set_compress(false) sends every handler response as it is, buffered or
  13474. // streamed
  13475. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13476. const std::string text(1000, 'a');
  13477. Server svr;
  13478. svr.set_compress(false);
  13479. svr.Get("/buffered", [&](const Request &, Response &res) {
  13480. res.set_content(text, "text/plain");
  13481. });
  13482. svr.Get("/streamed", [&](const Request &, Response &res) {
  13483. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13484. sink.write(text.data(), text.size());
  13485. sink.done();
  13486. return true;
  13487. });
  13488. });
  13489. auto port = svr.bind_to_any_port(HOST);
  13490. ASSERT_LT(0, port);
  13491. thread t = thread([&] { svr.listen_after_bind(); });
  13492. auto se = detail::scope_exit([&] {
  13493. svr.stop();
  13494. t.join();
  13495. ASSERT_FALSE(svr.is_running());
  13496. });
  13497. svr.wait_until_ready();
  13498. Client cli(HOST, port);
  13499. cli.set_decompress(false);
  13500. for (auto path : {"/buffered", "/streamed"}) {
  13501. SCOPED_TRACE(path);
  13502. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13504. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13505. EXPECT_EQ(text, res->body);
  13506. }
  13507. }
  13508. // A chunked provider settles its coding where the headers are written and
  13509. // reuses it at write time. Both ends of that have to hold: a handler's own
  13510. // Content-Encoding suppresses the coding, and a response without one is still
  13511. // compressed as it always was.
  13512. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13513. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13514. const std::string plain = "Hello World! Hello World! Hello World!";
  13515. Server svr;
  13516. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13517. res.set_header("Content-Encoding", "gzip");
  13518. res.set_chunked_content_provider(
  13519. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13520. sink.write(gzipped.data(), gzipped.size());
  13521. sink.done();
  13522. return true;
  13523. });
  13524. });
  13525. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13526. res.set_chunked_content_provider(
  13527. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13528. sink.write(plain.data(), plain.size());
  13529. sink.done();
  13530. return true;
  13531. });
  13532. });
  13533. auto port = svr.bind_to_any_port(HOST);
  13534. thread t = thread([&]() { svr.listen_after_bind(); });
  13535. auto se = detail::scope_exit([&] {
  13536. svr.stop();
  13537. t.join();
  13538. ASSERT_FALSE(svr.is_running());
  13539. });
  13540. svr.wait_until_ready();
  13541. Client cli(HOST, port);
  13542. Headers headers = {{"Accept-Encoding", "gzip"}};
  13543. {
  13544. auto res = cli.Get("/pre-gzipped", headers);
  13545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13546. EXPECT_EQ(StatusCode::OK_200, res->status);
  13547. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13548. EXPECT_EQ("Hello World!", res->body);
  13549. }
  13550. {
  13551. auto res = cli.Get("/negotiated", headers);
  13552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13553. EXPECT_EQ(StatusCode::OK_200, res->status);
  13554. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13555. EXPECT_EQ(plain, res->body);
  13556. }
  13557. }
  13558. #endif
  13559. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13560. // the same message as the comma-joined one, so both have to be read the same
  13561. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13562. // single gzip coding, and a body the sender says was encoded twice was handed
  13563. // back after one pass, still compressed but presented as decoded.
  13564. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13565. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13566. Server svr;
  13567. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13568. res.set_content(body, "image/jpeg");
  13569. res.headers.emplace("Content-Encoding", "gzip");
  13570. res.headers.emplace("Content-Encoding", "gzip");
  13571. });
  13572. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13573. res.set_content(body, "image/jpeg");
  13574. res.set_header("Content-Encoding", "gzip, gzip");
  13575. });
  13576. auto port = svr.bind_to_any_port(HOST);
  13577. thread t = thread([&]() { svr.listen_after_bind(); });
  13578. auto se = detail::scope_exit([&] {
  13579. svr.stop();
  13580. t.join();
  13581. ASSERT_FALSE(svr.is_running());
  13582. });
  13583. svr.wait_until_ready();
  13584. Client cli(HOST, port);
  13585. // Two codings is not something cpp-httplib decodes, so both representations
  13586. // take the pass-through path rather than one of them being gunzipped once.
  13587. for (const char *path : {"/split", "/joined"}) {
  13588. auto res = cli.Get(path);
  13589. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13590. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13591. EXPECT_EQ(body, res->body) << path;
  13592. }
  13593. }
  13594. // Regression test for DoS vulnerability: a malicious server sending a response
  13595. // without Content-Length header must not cause unbounded memory consumption on
  13596. // the client side. The client should stop reading after a reasonable limit,
  13597. // similar to the server-side set_payload_max_length protection.
  13598. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13599. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13600. #ifndef _WIN32
  13601. signal(SIGPIPE, SIG_IGN);
  13602. #endif
  13603. auto server_thread = std::thread([] {
  13604. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13605. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13606. default_socket_options(srv);
  13607. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13608. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13609. sockaddr_in addr{};
  13610. addr.sin_family = AF_INET;
  13611. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13612. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13613. int opt = 1;
  13614. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13615. #ifdef _WIN32
  13616. reinterpret_cast<const char *>(&opt),
  13617. #else
  13618. &opt,
  13619. #endif
  13620. sizeof(opt));
  13621. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13622. ::listen(srv, 1);
  13623. sockaddr_in cli_addr{};
  13624. socklen_t cli_len = sizeof(cli_addr);
  13625. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13626. if (cli != INVALID_SOCKET) {
  13627. char buf[4096];
  13628. ::recv(cli, buf, sizeof(buf), 0);
  13629. // Malicious response: no Content-Length, no chunked encoding
  13630. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13631. "Connection: close\r\n"
  13632. "\r\n";
  13633. ::send(cli,
  13634. #ifdef _WIN32
  13635. static_cast<const char *>(response_header.c_str()),
  13636. static_cast<int>(response_header.size()),
  13637. #else
  13638. response_header.c_str(), response_header.size(),
  13639. #endif
  13640. 0);
  13641. // Send 10MB of data
  13642. std::string chunk(64 * 1024, 'A');
  13643. size_t total_sent = 0;
  13644. while (total_sent < MALICIOUS_DATA_SIZE) {
  13645. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13646. auto sent = ::send(cli,
  13647. #ifdef _WIN32
  13648. static_cast<const char *>(chunk.c_str()),
  13649. static_cast<int>(to_send),
  13650. #else
  13651. chunk.c_str(), to_send,
  13652. #endif
  13653. 0);
  13654. if (sent <= 0) break;
  13655. total_sent += static_cast<size_t>(sent);
  13656. }
  13657. detail::close_socket(cli);
  13658. }
  13659. detail::close_socket(srv);
  13660. });
  13661. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13662. size_t total_read = 0;
  13663. {
  13664. Client cli("127.0.0.1", PORT + 2);
  13665. cli.set_read_timeout(5, 0);
  13666. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13667. auto stream = cli.open_stream("GET", "/malicious");
  13668. ASSERT_TRUE(stream.is_valid());
  13669. char buffer[64 * 1024];
  13670. ssize_t n;
  13671. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13672. total_read += static_cast<size_t>(n);
  13673. }
  13674. } // StreamHandle and Client destroyed here, closing the socket
  13675. server_thread.join();
  13676. // With set_payload_max_length, the client must stop reading before consuming
  13677. // all 10MB. The read loop should be cut off at or near the configured limit.
  13678. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13679. << "Client read " << total_read << " bytes, exceeding the configured "
  13680. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13681. }
  13682. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13683. // the entire response body without truncation.
  13684. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13685. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13686. #ifndef _WIN32
  13687. signal(SIGPIPE, SIG_IGN);
  13688. #endif
  13689. auto server_thread = std::thread([] {
  13690. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13691. default_socket_options(srv);
  13692. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13693. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13694. sockaddr_in addr{};
  13695. addr.sin_family = AF_INET;
  13696. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13697. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13698. int opt = 1;
  13699. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13700. #ifdef _WIN32
  13701. reinterpret_cast<const char *>(&opt),
  13702. #else
  13703. &opt,
  13704. #endif
  13705. sizeof(opt));
  13706. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13707. ::listen(srv, 1);
  13708. sockaddr_in cli_addr{};
  13709. socklen_t cli_len = sizeof(cli_addr);
  13710. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13711. if (cli != INVALID_SOCKET) {
  13712. char buf[4096];
  13713. ::recv(cli, buf, sizeof(buf), 0);
  13714. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13715. "Connection: close\r\n"
  13716. "\r\n";
  13717. ::send(cli,
  13718. #ifdef _WIN32
  13719. static_cast<const char *>(response_header.c_str()),
  13720. static_cast<int>(response_header.size()),
  13721. #else
  13722. response_header.c_str(), response_header.size(),
  13723. #endif
  13724. 0);
  13725. std::string chunk(64 * 1024, 'A');
  13726. size_t total_sent = 0;
  13727. while (total_sent < DATA_SIZE) {
  13728. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13729. auto sent = ::send(cli,
  13730. #ifdef _WIN32
  13731. static_cast<const char *>(chunk.c_str()),
  13732. static_cast<int>(to_send),
  13733. #else
  13734. chunk.c_str(), to_send,
  13735. #endif
  13736. 0);
  13737. if (sent <= 0) break;
  13738. total_sent += static_cast<size_t>(sent);
  13739. }
  13740. #ifdef _WIN32
  13741. ::shutdown(cli, SD_SEND);
  13742. #else
  13743. ::shutdown(cli, SHUT_WR);
  13744. #endif
  13745. // Drain until the client closes its end, ensuring all data is delivered
  13746. char drain[1024];
  13747. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13748. detail::close_socket(cli);
  13749. }
  13750. detail::close_socket(srv);
  13751. });
  13752. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13753. size_t total_read = 0;
  13754. {
  13755. Client cli("127.0.0.1", PORT + 2);
  13756. cli.set_read_timeout(5, 0);
  13757. cli.set_payload_max_length(0); // 0 means no limit
  13758. auto stream = cli.open_stream("GET", "/data");
  13759. ASSERT_TRUE(stream.is_valid());
  13760. char buffer[64 * 1024];
  13761. ssize_t n;
  13762. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13763. total_read += static_cast<size_t>(n);
  13764. }
  13765. }
  13766. server_thread.join();
  13767. EXPECT_EQ(total_read, DATA_SIZE)
  13768. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13769. << " bytes without truncation, but only read " << total_read << " bytes.";
  13770. }
  13771. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13772. // enormous Content-Length must not cause the client to pre-allocate a huge
  13773. // response body buffer. The reservation is capped at payload_max_length_, and
  13774. // the read itself fails when the body exceeds the limit.
  13775. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13776. #ifndef _WIN32
  13777. signal(SIGPIPE, SIG_IGN);
  13778. #endif
  13779. auto server_thread = std::thread([] {
  13780. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13781. default_socket_options(srv);
  13782. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13783. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13784. sockaddr_in addr{};
  13785. addr.sin_family = AF_INET;
  13786. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13787. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13788. int opt = 1;
  13789. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13790. #ifdef _WIN32
  13791. reinterpret_cast<const char *>(&opt),
  13792. #else
  13793. &opt,
  13794. #endif
  13795. sizeof(opt));
  13796. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13797. ::listen(srv, 1);
  13798. sockaddr_in cli_addr{};
  13799. socklen_t cli_len = sizeof(cli_addr);
  13800. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13801. if (cli != INVALID_SOCKET) {
  13802. char buf[4096];
  13803. ::recv(cli, buf, sizeof(buf), 0);
  13804. // Malicious response: claim a 20GB body but send only a tiny payload.
  13805. std::string response = "HTTP/1.1 200 OK\r\n"
  13806. "Content-Length: 20000000000\r\n"
  13807. "\r\n"
  13808. "abc";
  13809. ::send(cli,
  13810. #ifdef _WIN32
  13811. static_cast<const char *>(response.c_str()),
  13812. static_cast<int>(response.size()),
  13813. #else
  13814. response.c_str(), response.size(),
  13815. #endif
  13816. 0);
  13817. detail::close_socket(cli);
  13818. }
  13819. detail::close_socket(srv);
  13820. });
  13821. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13822. {
  13823. Client cli("127.0.0.1", PORT + 2);
  13824. cli.set_read_timeout(5, 0);
  13825. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13826. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13827. // (server claims more bytes than payload_max_length permits), but it must
  13828. // not exhaust memory before getting there.
  13829. auto res = cli.Get("/malicious");
  13830. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13831. }
  13832. server_thread.join();
  13833. }
  13834. // Verify that content_receiver bypasses the default payload_max_length,
  13835. // allowing streaming downloads larger than 100MB without requiring an explicit
  13836. // set_payload_max_length call.
  13837. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13838. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13839. #ifndef _WIN32
  13840. signal(SIGPIPE, SIG_IGN);
  13841. #endif
  13842. auto server_thread = std::thread([] {
  13843. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13844. default_socket_options(srv);
  13845. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13846. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13847. sockaddr_in addr{};
  13848. addr.sin_family = AF_INET;
  13849. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13850. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13851. int opt = 1;
  13852. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13853. #ifdef _WIN32
  13854. reinterpret_cast<const char *>(&opt),
  13855. #else
  13856. &opt,
  13857. #endif
  13858. sizeof(opt));
  13859. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13860. ::listen(srv, 1);
  13861. sockaddr_in cli_addr{};
  13862. socklen_t cli_len = sizeof(cli_addr);
  13863. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13864. if (cli != INVALID_SOCKET) {
  13865. char buf[4096];
  13866. ::recv(cli, buf, sizeof(buf), 0);
  13867. // Response with Content-Length larger than default 100MB limit
  13868. auto content_length = std::to_string(DATA_SIZE);
  13869. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13870. "Content-Length: " +
  13871. content_length +
  13872. "\r\n"
  13873. "Connection: close\r\n"
  13874. "\r\n";
  13875. ::send(cli,
  13876. #ifdef _WIN32
  13877. static_cast<const char *>(response_header.c_str()),
  13878. static_cast<int>(response_header.size()),
  13879. #else
  13880. response_header.c_str(), response_header.size(),
  13881. #endif
  13882. 0);
  13883. std::string chunk(64 * 1024, 'A');
  13884. size_t total_sent = 0;
  13885. while (total_sent < DATA_SIZE) {
  13886. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13887. auto sent = ::send(cli,
  13888. #ifdef _WIN32
  13889. static_cast<const char *>(chunk.c_str()),
  13890. static_cast<int>(to_send),
  13891. #else
  13892. chunk.c_str(), to_send,
  13893. #endif
  13894. 0);
  13895. if (sent <= 0) break;
  13896. total_sent += static_cast<size_t>(sent);
  13897. }
  13898. detail::close_socket(cli);
  13899. }
  13900. detail::close_socket(srv);
  13901. });
  13902. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13903. size_t total_received = 0;
  13904. {
  13905. Client cli("127.0.0.1", PORT + 2);
  13906. cli.set_read_timeout(10, 0);
  13907. // Do NOT call set_payload_max_length — use the default 100MB limit
  13908. auto res =
  13909. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13910. total_received += data_length;
  13911. return true;
  13912. });
  13913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13914. EXPECT_EQ(StatusCode::OK_200, res->status);
  13915. }
  13916. server_thread.join();
  13917. EXPECT_EQ(total_received, DATA_SIZE)
  13918. << "With content_receiver, the client should read all " << DATA_SIZE
  13919. << " bytes despite the default 100MB payload_max_length, but only read "
  13920. << total_received << " bytes.";
  13921. }
  13922. // Verify that an explicit set_payload_max_length smaller than the response is
  13923. // enforced even when a content_receiver is used.
  13924. TEST(ClientVulnerabilityTest,
  13925. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13926. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13927. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13928. #ifndef _WIN32
  13929. signal(SIGPIPE, SIG_IGN);
  13930. #endif
  13931. auto server_thread = std::thread([] {
  13932. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13933. default_socket_options(srv);
  13934. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13935. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13936. sockaddr_in addr{};
  13937. addr.sin_family = AF_INET;
  13938. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13939. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13940. int opt = 1;
  13941. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13942. #ifdef _WIN32
  13943. reinterpret_cast<const char *>(&opt),
  13944. #else
  13945. &opt,
  13946. #endif
  13947. sizeof(opt));
  13948. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13949. ::listen(srv, 1);
  13950. sockaddr_in cli_addr{};
  13951. socklen_t cli_len = sizeof(cli_addr);
  13952. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13953. if (cli != INVALID_SOCKET) {
  13954. char buf[4096];
  13955. ::recv(cli, buf, sizeof(buf), 0);
  13956. auto content_length = std::to_string(DATA_SIZE);
  13957. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13958. "Content-Length: " +
  13959. content_length +
  13960. "\r\n"
  13961. "Connection: close\r\n"
  13962. "\r\n";
  13963. ::send(cli,
  13964. #ifdef _WIN32
  13965. static_cast<const char *>(response_header.c_str()),
  13966. static_cast<int>(response_header.size()),
  13967. #else
  13968. response_header.c_str(), response_header.size(),
  13969. #endif
  13970. 0);
  13971. std::string chunk(64 * 1024, 'A');
  13972. size_t total_sent = 0;
  13973. while (total_sent < DATA_SIZE) {
  13974. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13975. auto sent = ::send(cli,
  13976. #ifdef _WIN32
  13977. static_cast<const char *>(chunk.c_str()),
  13978. static_cast<int>(to_send),
  13979. #else
  13980. chunk.c_str(), to_send,
  13981. #endif
  13982. 0);
  13983. if (sent <= 0) break;
  13984. total_sent += static_cast<size_t>(sent);
  13985. }
  13986. detail::close_socket(cli);
  13987. }
  13988. detail::close_socket(srv);
  13989. });
  13990. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13991. size_t total_received = 0;
  13992. {
  13993. Client cli("127.0.0.1", PORT + 2);
  13994. cli.set_read_timeout(10, 0);
  13995. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13996. auto res =
  13997. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13998. total_received += data_length;
  13999. return true;
  14000. });
  14001. // Should fail because 200MB exceeds the explicit 150MB limit
  14002. EXPECT_FALSE(res);
  14003. }
  14004. server_thread.join();
  14005. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  14006. << "Client with content_receiver should respect the explicit "
  14007. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  14008. << total_received << " bytes.";
  14009. }
  14010. // Verify that an explicit set_payload_max_length larger than the response
  14011. // allows the content_receiver to read all data successfully.
  14012. TEST(ClientVulnerabilityTest,
  14013. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  14014. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14015. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  14016. #ifndef _WIN32
  14017. signal(SIGPIPE, SIG_IGN);
  14018. #endif
  14019. auto server_thread = std::thread([] {
  14020. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14021. default_socket_options(srv);
  14022. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14023. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14024. sockaddr_in addr{};
  14025. addr.sin_family = AF_INET;
  14026. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14027. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14028. int opt = 1;
  14029. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14030. #ifdef _WIN32
  14031. reinterpret_cast<const char *>(&opt),
  14032. #else
  14033. &opt,
  14034. #endif
  14035. sizeof(opt));
  14036. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14037. ::listen(srv, 1);
  14038. sockaddr_in cli_addr{};
  14039. socklen_t cli_len = sizeof(cli_addr);
  14040. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14041. if (cli != INVALID_SOCKET) {
  14042. char buf[4096];
  14043. ::recv(cli, buf, sizeof(buf), 0);
  14044. auto content_length = std::to_string(DATA_SIZE);
  14045. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14046. "Content-Length: " +
  14047. content_length +
  14048. "\r\n"
  14049. "Connection: close\r\n"
  14050. "\r\n";
  14051. ::send(cli,
  14052. #ifdef _WIN32
  14053. static_cast<const char *>(response_header.c_str()),
  14054. static_cast<int>(response_header.size()),
  14055. #else
  14056. response_header.c_str(), response_header.size(),
  14057. #endif
  14058. 0);
  14059. std::string chunk(64 * 1024, 'A');
  14060. size_t total_sent = 0;
  14061. while (total_sent < DATA_SIZE) {
  14062. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14063. auto sent = ::send(cli,
  14064. #ifdef _WIN32
  14065. static_cast<const char *>(chunk.c_str()),
  14066. static_cast<int>(to_send),
  14067. #else
  14068. chunk.c_str(), to_send,
  14069. #endif
  14070. 0);
  14071. if (sent <= 0) break;
  14072. total_sent += static_cast<size_t>(sent);
  14073. }
  14074. #ifdef _WIN32
  14075. ::shutdown(cli, SD_SEND);
  14076. #else
  14077. ::shutdown(cli, SHUT_WR);
  14078. #endif
  14079. char drain[1024];
  14080. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14081. detail::close_socket(cli);
  14082. }
  14083. detail::close_socket(srv);
  14084. });
  14085. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14086. size_t total_received = 0;
  14087. {
  14088. Client cli("127.0.0.1", PORT + 2);
  14089. cli.set_read_timeout(10, 0);
  14090. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14091. auto res =
  14092. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14093. total_received += data_length;
  14094. return true;
  14095. });
  14096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14097. EXPECT_EQ(StatusCode::OK_200, res->status);
  14098. }
  14099. server_thread.join();
  14100. EXPECT_EQ(total_received, DATA_SIZE)
  14101. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14102. << " bytes (larger than " << DATA_SIZE
  14103. << " bytes response), content_receiver should read all data, but only "
  14104. "read "
  14105. << total_received << " bytes.";
  14106. }
  14107. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14108. // Regression test for "zip bomb" attack on the client side: a malicious server
  14109. // sends a small gzip-compressed response that decompresses to a huge payload.
  14110. // The client must enforce payload_max_length on the decompressed size.
  14111. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14112. constexpr size_t DECOMPRESSED_SIZE =
  14113. 10 * 1024 * 1024; // 10MB after decompression
  14114. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14115. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14116. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14117. std::string compressed;
  14118. {
  14119. httplib::detail::gzip_compressor compressor;
  14120. bool ok =
  14121. compressor.compress(uncompressed.data(), uncompressed.size(),
  14122. /*last=*/true, [&](const char *buf, size_t len) {
  14123. compressed.append(buf, len);
  14124. return true;
  14125. });
  14126. ASSERT_TRUE(ok);
  14127. }
  14128. // Sanity: compressed data should be much smaller than the decompressed size
  14129. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14130. #ifndef _WIN32
  14131. signal(SIGPIPE, SIG_IGN);
  14132. #endif
  14133. // Set up the listening socket in the main thread so the server is guaranteed
  14134. // to be ready before the client connects (eliminates race condition).
  14135. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14136. default_socket_options(srv);
  14137. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14138. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14139. sockaddr_in addr{};
  14140. addr.sin_family = AF_INET;
  14141. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14142. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14143. int opt = 1;
  14144. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14145. #ifdef _WIN32
  14146. reinterpret_cast<const char *>(&opt),
  14147. #else
  14148. &opt,
  14149. #endif
  14150. sizeof(opt));
  14151. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14152. ASSERT_EQ(0, ::listen(srv, 1));
  14153. auto server_thread = std::thread([&compressed, srv] {
  14154. sockaddr_in cli_addr{};
  14155. socklen_t cli_len = sizeof(cli_addr);
  14156. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14157. if (cli != INVALID_SOCKET) {
  14158. // Read the full HTTP request (until \r\n\r\n)
  14159. char buf[4096];
  14160. size_t total = 0;
  14161. while (total < sizeof(buf)) {
  14162. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14163. if (n <= 0) break;
  14164. total += static_cast<size_t>(n);
  14165. // Check for end of headers
  14166. if (total >= 4) {
  14167. std::string req(buf, total);
  14168. if (req.find("\r\n\r\n") != std::string::npos) break;
  14169. }
  14170. }
  14171. // Malicious response: gzip-compressed body, no Content-Length
  14172. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14173. "Content-Encoding: gzip\r\n"
  14174. "Connection: close\r\n"
  14175. "\r\n";
  14176. ::send(cli,
  14177. #ifdef _WIN32
  14178. static_cast<const char *>(response_header.c_str()),
  14179. static_cast<int>(response_header.size()),
  14180. #else
  14181. response_header.c_str(), response_header.size(),
  14182. #endif
  14183. 0);
  14184. // Send the compressed payload (small on the wire, huge when decompressed)
  14185. size_t total_sent = 0;
  14186. while (total_sent < compressed.size()) {
  14187. auto to_send = std::min(compressed.size() - total_sent,
  14188. static_cast<size_t>(64 * 1024));
  14189. auto sent =
  14190. ::send(cli,
  14191. #ifdef _WIN32
  14192. static_cast<const char *>(compressed.c_str() + total_sent),
  14193. static_cast<int>(to_send),
  14194. #else
  14195. compressed.c_str() + total_sent, to_send,
  14196. #endif
  14197. 0);
  14198. if (sent <= 0) break;
  14199. total_sent += static_cast<size_t>(sent);
  14200. }
  14201. detail::close_socket(cli);
  14202. }
  14203. });
  14204. auto se = detail::scope_exit([&] {
  14205. detail::close_socket(srv);
  14206. server_thread.join();
  14207. });
  14208. size_t total_decompressed = 0;
  14209. {
  14210. Client cli("127.0.0.1", PORT + 3);
  14211. cli.set_read_timeout(5, 0);
  14212. cli.set_decompress(true);
  14213. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14214. auto stream = cli.open_stream("GET", "/zipbomb");
  14215. ASSERT_TRUE(stream.is_valid());
  14216. char buffer[64 * 1024];
  14217. ssize_t n;
  14218. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14219. total_decompressed += static_cast<size_t>(n);
  14220. }
  14221. }
  14222. // The decompressed size must be capped by payload_max_length. Without
  14223. // protection, the client would decompress the full 10MB from a tiny
  14224. // compressed payload, enabling a zip bomb DoS attack.
  14225. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14226. << "Client decompressed " << total_decompressed
  14227. << " bytes from a gzip response. The decompressed size should be "
  14228. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14229. }
  14230. #endif
  14231. TEST(HostAndPortPropertiesTest, NoSSL) {
  14232. httplib::Client cli("www.google.com", 1234);
  14233. ASSERT_EQ("www.google.com", cli.host());
  14234. ASSERT_EQ(1234, cli.port());
  14235. }
  14236. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14237. httplib::Client cli("www.google.com:1234");
  14238. ASSERT_EQ("www.google.com", cli.host());
  14239. ASSERT_EQ(1234, cli.port());
  14240. }
  14241. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14242. // Port number that overflows int — should not crash, client becomes invalid
  14243. httplib::Client cli("http://www.google.com:99999999999999999999");
  14244. ASSERT_FALSE(cli.is_valid());
  14245. }
  14246. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14247. // Port 99999 exceeds valid range (1-65535) — should not crash
  14248. httplib::Client cli("http://www.google.com:99999");
  14249. ASSERT_FALSE(cli.is_valid());
  14250. auto res = cli.Get("/");
  14251. EXPECT_FALSE(res);
  14252. EXPECT_EQ(Error::Connection, res.error());
  14253. }
  14254. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14255. httplib::Client cli("http://user:pass@localhost:1234");
  14256. ASSERT_FALSE(cli.is_valid());
  14257. EXPECT_FALSE(cli.Get("/"));
  14258. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14259. }
  14260. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14261. httplib::Client cli("http://www.google.com:80abc");
  14262. ASSERT_FALSE(cli.is_valid());
  14263. }
  14264. #ifdef CPPHTTPLIB_SSL_ENABLED
  14265. TEST(HostAndPortPropertiesTest, SSL) {
  14266. httplib::SSLClient cli("www.google.com");
  14267. ASSERT_EQ("www.google.com", cli.host());
  14268. ASSERT_EQ(443, cli.port());
  14269. }
  14270. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14271. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14272. std::string cert;
  14273. read_file(CA_CERT_FILE, cert);
  14274. httplib::SSLClient httplib_client("www.google.com");
  14275. // Load CA store first time
  14276. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14277. // Load CA store second time (update)
  14278. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14279. // Verify client is still valid and can make connections
  14280. httplib_client.enable_server_certificate_verification(true);
  14281. auto res = httplib_client.Get("/");
  14282. // Any status: Google may redirect or rate-limit CI runners.
  14283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14284. }
  14285. TEST(SSLClientTest, ServerNameIndication_Online) {
  14286. auto host = "httpbingo.org";
  14287. auto path = std::string{"/get"};
  14288. SSLClient cli(host, 443);
  14289. auto res = retry_service_failures([&] { return cli.Get(path); });
  14290. SKIP_ON_SERVICE_FAILURE(res);
  14291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14292. ASSERT_EQ(StatusCode::OK_200, res->status);
  14293. }
  14294. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14295. // Use a site that will cause SSL verification failure due to self-signed cert
  14296. SSLClient cli("self-signed.badssl.com", 443);
  14297. cli.enable_server_certificate_verification(true);
  14298. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14299. SKIP_ON_SERVICE_FAILURE(res);
  14300. ASSERT_TRUE(!res);
  14301. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14302. // Verify backend error is captured for SSLServerVerification
  14303. // This occurs when certificate verification fails
  14304. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14305. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14306. EXPECT_NE(0UL, res.ssl_backend_error());
  14307. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14308. res.ssl_error());
  14309. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14310. #if !defined(_WIN32) || \
  14311. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14312. // On non-Windows or when Windows Schannel is disabled, the error comes
  14313. // from OpenSSL's verification
  14314. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14315. res.ssl_backend_error());
  14316. #endif
  14317. #endif
  14318. }
  14319. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14320. // Use a site where hostname doesn't match the certificate
  14321. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14322. SSLClient cli("wrong.host.badssl.com", 443);
  14323. cli.enable_server_certificate_verification(true);
  14324. cli.enable_server_hostname_verification(true);
  14325. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14326. SKIP_ON_SERVICE_FAILURE(res);
  14327. ASSERT_TRUE(!res);
  14328. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14329. // Verify backend error is captured for hostname verification failure
  14330. EXPECT_NE(0UL, res.ssl_backend_error());
  14331. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14332. res.ssl_error());
  14333. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14334. #if !defined(_WIN32) || \
  14335. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14336. // On non-Windows or when Windows Schannel is disabled, the error comes
  14337. // from OpenSSL's hostname verification
  14338. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14339. res.ssl_backend_error());
  14340. #endif
  14341. #endif
  14342. }
  14343. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14344. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14345. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14346. SSLClient cli("www.google.com", 443);
  14347. cli.enable_server_certificate_verification(true);
  14348. auto res = cli.Get("/");
  14349. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14350. }
  14351. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14352. SSLClient cli("www.google.com", 443);
  14353. cli.enable_server_certificate_verification(true);
  14354. cli.enable_windows_certificate_verification(false);
  14355. auto res = cli.Get("/");
  14356. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14357. }
  14358. // The server sends an intermediate cross-signed by a root Windows trusts,
  14359. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14360. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14361. SSLClient cli("accounts.spotify.com", 443);
  14362. auto res = cli.Get("/");
  14363. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14364. << " ssl_backend_error=" << res.ssl_backend_error();
  14365. }
  14366. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14367. // policy status, which no backend reports for a self-signed certificate.
  14368. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14369. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14370. ASSERT_TRUE(svr.is_valid());
  14371. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14372. auto se = detail::scope_exit([&] {
  14373. svr.stop();
  14374. t.join();
  14375. ASSERT_FALSE(svr.is_running());
  14376. });
  14377. svr.wait_until_ready();
  14378. SSLClient cli("127.0.0.1", PORT);
  14379. cli.set_connection_timeout(30);
  14380. auto res = cli.Get("/");
  14381. ASSERT_FALSE(res);
  14382. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14383. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14384. }
  14385. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14386. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14387. ASSERT_TRUE(svr.is_valid());
  14388. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14389. auto se = detail::scope_exit([&] {
  14390. svr.stop();
  14391. t.join();
  14392. ASSERT_FALSE(svr.is_running());
  14393. });
  14394. svr.wait_until_ready();
  14395. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14396. {
  14397. ws::WebSocketClient client(url);
  14398. auto res = client.connect();
  14399. ASSERT_FALSE(res);
  14400. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14401. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14402. res.ssl_backend_error());
  14403. }
  14404. {
  14405. ws::WebSocketClient client(url);
  14406. client.enable_windows_certificate_verification(false);
  14407. auto res = client.connect();
  14408. ASSERT_FALSE(res);
  14409. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14410. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14411. res.ssl_backend_error());
  14412. }
  14413. }
  14414. #endif
  14415. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14416. Client cli("https://google.com");
  14417. auto res = cli.Get("/");
  14418. // Any status: Google may redirect or rate-limit CI runners.
  14419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14420. }
  14421. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14422. SSLClient cli("google.com");
  14423. cli.set_ca_cert_path(CA_CERT_FILE);
  14424. auto res = cli.Get("/");
  14425. // Any status: Google may redirect or rate-limit CI runners.
  14426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14427. }
  14428. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14429. SSLClient cli("google.com");
  14430. cli.enable_server_certificate_verification(true);
  14431. cli.set_ca_cert_path("hello");
  14432. auto res = cli.Get("/");
  14433. ASSERT_TRUE(!res);
  14434. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14435. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14436. // should be set
  14437. EXPECT_EQ(0, res.ssl_error());
  14438. // Verify backend error is captured for SSLLoadingCerts
  14439. // This error occurs when loading CA certificates fails
  14440. EXPECT_NE(0UL, res.ssl_backend_error());
  14441. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14442. // OpenSSL specific error codes:
  14443. // > openssl errstr 0x80000002
  14444. // error:80000002:system library::No such file or directory
  14445. // > openssl errstr 0xA000126
  14446. // error:0A000126:SSL routines::unexpected eof while reading
  14447. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14448. res.ssl_backend_error() == 0xA000126);
  14449. #endif
  14450. }
  14451. TEST(SSLClientTest, ServerCertificateVerification4) {
  14452. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14453. ASSERT_TRUE(svr.is_valid());
  14454. svr.Get("/test", [&](const Request &, Response &res) {
  14455. res.set_content("test", "text/plain");
  14456. svr.stop();
  14457. ASSERT_TRUE(true);
  14458. });
  14459. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14460. auto se = detail::scope_exit([&] {
  14461. t.join();
  14462. ASSERT_FALSE(svr.is_running());
  14463. });
  14464. svr.wait_until_ready();
  14465. SSLClient cli("127.0.0.1", PORT);
  14466. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14467. cli.enable_server_certificate_verification(true);
  14468. cli.set_connection_timeout(30);
  14469. auto res = cli.Get("/test");
  14470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14471. ASSERT_EQ(StatusCode::OK_200, res->status);
  14472. }
  14473. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14474. std::string cert;
  14475. read_file(CA_CERT_FILE, cert);
  14476. SSLClient cli("google.com");
  14477. cli.load_ca_cert_store(cert.data(), cert.size());
  14478. const auto res = cli.Get("/");
  14479. // Any status: Google may redirect or rate-limit CI runners.
  14480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14481. }
  14482. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14483. // clang-format off
  14484. static constexpr char cert[] =
  14485. "GlobalSign Root CA\n"
  14486. "==================\n"
  14487. "-----BEGIN CERTIFICATE-----\n"
  14488. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14489. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14490. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14491. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14492. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14493. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14494. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14495. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14496. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14497. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14498. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14499. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14500. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14501. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14502. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14503. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14504. "-----END CERTIFICATE-----\n";
  14505. // clang-format on
  14506. SSLClient cli("google.com");
  14507. cli.load_ca_cert_store(cert, sizeof(cert));
  14508. const auto res = cli.Get("/");
  14509. // Any status: Google may redirect or rate-limit CI runners.
  14510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14511. }
  14512. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14513. SSLClient cli("www.youtube.com");
  14514. cli.set_ca_cert_path(CA_CERT_FILE);
  14515. cli.enable_server_certificate_verification(true);
  14516. cli.set_follow_location(true);
  14517. auto res = cli.Get("/");
  14518. // Any status: Google may redirect or rate-limit CI runners.
  14519. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14520. }
  14521. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14522. SSLClient cli("wWw.YouTube.Com");
  14523. cli.set_ca_cert_path(CA_CERT_FILE);
  14524. cli.enable_server_certificate_verification(true);
  14525. cli.enable_server_hostname_verification(true);
  14526. cli.set_follow_location(true);
  14527. auto res = cli.Get("/");
  14528. // Any status: Google may redirect or rate-limit CI runners.
  14529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14530. }
  14531. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14532. SSLClient cli("gOoGlE.COm");
  14533. cli.enable_server_certificate_verification(true);
  14534. cli.enable_server_hostname_verification(true);
  14535. cli.set_follow_location(true);
  14536. auto res = cli.Get("/");
  14537. // Any status: Google may redirect or rate-limit CI runners.
  14538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14539. }
  14540. TEST(SSLClientTest, Issue2004_Online) {
  14541. Client client("https://google.com");
  14542. client.set_follow_location(true);
  14543. auto res = client.Get("/");
  14544. // Any status: Google may redirect or rate-limit CI runners.
  14545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14546. }
  14547. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14548. // Create SSLClient with invalid cert/key to make is_valid() return false
  14549. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14550. "nonexistent_key.pem");
  14551. // is_valid() should be false due to cert loading failure
  14552. ASSERT_FALSE(cli.is_valid());
  14553. auto res = cli.Get("/");
  14554. ASSERT_FALSE(res);
  14555. EXPECT_EQ(Error::SSLConnection, res.error());
  14556. }
  14557. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14558. // Test for Issue #2251: SSL error not properly reported when client cert
  14559. // and key paths are swapped or mismatched
  14560. // This simulates the scenario where user accidentally swaps the cert and key
  14561. // files
  14562. // Using client cert file as private key and vice versa (completely wrong)
  14563. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14564. // Should fail validation due to cert/key mismatch
  14565. ASSERT_FALSE(cli.is_valid());
  14566. // Attempt to make a request should fail with proper error
  14567. auto res = cli.Get("/");
  14568. ASSERT_FALSE(res);
  14569. EXPECT_EQ(Error::SSLConnection, res.error());
  14570. // SSL error should be recorded in the Result object (this is the key fix for
  14571. // Issue #2251)
  14572. auto backend_error = res.ssl_backend_error();
  14573. EXPECT_NE(0u, backend_error);
  14574. }
  14575. // Tests cert/key mismatch detection at the TLS context level
  14576. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14577. // Test that using mismatched cert/key causes connection failure.
  14578. // We verify this at the SSLClient level rather than through internal
  14579. // TLS API functions.
  14580. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14581. cli.enable_server_certificate_verification(false);
  14582. cli.set_connection_timeout(2);
  14583. // The mismatch should cause a connection or handshake error
  14584. auto res = cli.Get("/test");
  14585. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14586. // Either way, the request should fail
  14587. EXPECT_FALSE(res);
  14588. }
  14589. #endif
  14590. #if 0
  14591. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14592. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14593. ASSERT_TRUE(cli != nullptr);
  14594. cli->set_address_family(AF_INET6);
  14595. cli->set_interface("en0");
  14596. auto res = cli->Get("/get");
  14597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14598. ASSERT_EQ(StatusCode::OK_200, res->status);
  14599. }
  14600. #endif
  14601. // Client certificate tests - work with all TLS backends
  14602. #ifdef CPPHTTPLIB_SSL_ENABLED
  14603. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14604. void ClientCertPresent(
  14605. const std::string &client_cert_file,
  14606. const std::string &client_private_key_file,
  14607. const std::string &client_encrypted_private_key_pass = std::string(),
  14608. const ClientCertServerSetup &setup = nullptr) {
  14609. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14610. ASSERT_TRUE(svr.is_valid());
  14611. if (setup) { setup(svr); }
  14612. svr.Get("/test", [&](const Request &req, Response &res) {
  14613. res.set_content("test", "text/plain");
  14614. auto cert = req.peer_cert();
  14615. ASSERT_TRUE(static_cast<bool>(cert));
  14616. std::string common_name = cert.subject_cn();
  14617. EXPECT_EQ("Common Name", common_name);
  14618. });
  14619. auto port = svr.bind_to_any_port(HOST);
  14620. ASSERT_LT(0, port);
  14621. thread t = thread([&]() { svr.listen_after_bind(); });
  14622. auto se = detail::scope_exit([&] {
  14623. svr.stop();
  14624. t.join();
  14625. ASSERT_FALSE(svr.is_running());
  14626. });
  14627. svr.wait_until_ready();
  14628. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14629. client_encrypted_private_key_pass);
  14630. cli.enable_server_certificate_verification(false);
  14631. cli.set_connection_timeout(30);
  14632. auto res = cli.Get("/test");
  14633. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14634. ASSERT_EQ(StatusCode::OK_200, res->status);
  14635. }
  14636. TEST(SSLClientServerTest, ClientCertPresent) {
  14637. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14638. }
  14639. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14640. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14641. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14642. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14643. }
  14644. // Expects svr, which must require client certificates, to reject a client
  14645. // that has none
  14646. void RejectsClientWithoutCert(SSLServer &svr) {
  14647. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14648. auto port = svr.bind_to_any_port(HOST);
  14649. ASSERT_LT(0, port);
  14650. thread t = thread([&]() { svr.listen_after_bind(); });
  14651. auto se = detail::scope_exit([&] {
  14652. svr.stop();
  14653. t.join();
  14654. ASSERT_FALSE(svr.is_running());
  14655. });
  14656. svr.wait_until_ready();
  14657. SSLClient cli(HOST, port);
  14658. cli.set_connection_timeout(30);
  14659. // Skip the server certificate check, so that the request fails because the
  14660. // client certificate is missing rather than because cert.pem is not trusted
  14661. cli.enable_server_certificate_verification(false);
  14662. auto res = cli.Get("/test");
  14663. ASSERT_FALSE(res);
  14664. // The server rejects the client during the handshake, or on TLS 1.3 right
  14665. // after it, which the client notices on its first write or read
  14666. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14667. res.error() == Error::Write || res.error() == Error::Read)
  14668. << to_string(res.error());
  14669. if (res.error() == Error::SSLConnection) {
  14670. EXPECT_NE(0UL, res.ssl_backend_error());
  14671. }
  14672. // A rejection noticed on the write keeps the TLS error the write hit
  14673. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14674. }
  14675. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14676. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14677. ASSERT_TRUE(svr.is_valid());
  14678. if (setup) { setup(svr); }
  14679. RejectsClientWithoutCert(svr);
  14680. }
  14681. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14682. // A server that requires client certificates must keep requiring them after
  14683. // setup changes it, and keep accepting a client that has one
  14684. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14685. ClientCertMissing(setup);
  14686. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14687. setup);
  14688. }
  14689. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14690. ClientCertStillRequired([](SSLServer &svr) {
  14691. ASSERT_TRUE(tls::set_verify_callback(
  14692. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14693. });
  14694. }
  14695. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14696. ClientCertStillRequired([](SSLServer &svr) {
  14697. ASSERT_TRUE(tls::set_verify_callback(
  14698. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14699. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14700. });
  14701. }
  14702. // The client verifies the server certificate during the handshake, so a
  14703. // server that fails the check never gets the client certificate, even when a
  14704. // verifier of the client's own accepts it
  14705. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14706. struct Case {
  14707. const char *trusted_ca;
  14708. const char *host;
  14709. Error error;
  14710. };
  14711. // cert2.pem names localhost: the first client does not trust it, and the
  14712. // second trusts it but asks for another name
  14713. for (const auto &c :
  14714. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14715. Case{SERVER_CERT2_FILE, "example.com",
  14716. Error::SSLServerHostnameVerification}}) {
  14717. for (auto with_verifier : {false, true}) {
  14718. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14719. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14720. CLIENT_CA_CERT_FILE);
  14721. ASSERT_TRUE(svr.is_valid());
  14722. std::atomic<bool> got_client_cert{false};
  14723. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14724. [&](const tls::VerifyContext &) {
  14725. got_client_cert = true;
  14726. return true;
  14727. }));
  14728. auto port = svr.bind_to_any_port("127.0.0.1");
  14729. ASSERT_LT(0, port);
  14730. thread t = thread([&] { svr.listen_after_bind(); });
  14731. svr.wait_until_ready();
  14732. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14733. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14734. cli.set_ca_cert_path(c.trusted_ca);
  14735. if (with_verifier) {
  14736. cli.set_server_certificate_verifier(
  14737. [](const tls::VerifyContext &) { return true; });
  14738. }
  14739. auto res = cli.Get("/");
  14740. EXPECT_FALSE(res);
  14741. EXPECT_EQ(c.error, res.error());
  14742. svr.stop();
  14743. t.join();
  14744. EXPECT_FALSE(got_client_cert);
  14745. }
  14746. }
  14747. }
  14748. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14749. std::string cert_pem, key_pem, ca_pem;
  14750. read_file(SERVER_CERT_FILE, cert_pem);
  14751. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14752. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14753. ASSERT_TRUE(
  14754. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14755. }
  14756. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14757. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14758. ASSERT_TRUE(svr.is_valid());
  14759. UpdateCertsPemWithClientCA(svr);
  14760. RejectsClientWithoutCert(svr);
  14761. }
  14762. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14763. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14764. }
  14765. // A TLS error from one request must not show up in a later request's Result
  14766. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14767. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14768. ASSERT_TRUE(svr.is_valid());
  14769. svr.Get("/test", [](const Request &, Response &res) {
  14770. res.set_content("test", "text/plain");
  14771. });
  14772. auto port = svr.bind_to_any_port(HOST);
  14773. ASSERT_LT(0, port);
  14774. thread t = thread([&]() { svr.listen_after_bind(); });
  14775. auto se = detail::scope_exit([&] {
  14776. svr.stop();
  14777. t.join();
  14778. ASSERT_FALSE(svr.is_running());
  14779. });
  14780. svr.wait_until_ready();
  14781. SSLClient cli(HOST, port);
  14782. cli.set_connection_timeout(30);
  14783. cli.enable_server_hostname_verification(false);
  14784. // cert.pem is not trusted, so the handshake fails
  14785. ASSERT_FALSE(cli.Get("/test"));
  14786. cli.enable_server_certificate_verification(false);
  14787. auto res = cli.Get("/test");
  14788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14789. EXPECT_EQ(0, res.ssl_error());
  14790. EXPECT_EQ(0UL, res.ssl_backend_error());
  14791. }
  14792. // PEM memory-based constructor tests (works with all TLS backends).
  14793. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14794. // terminator after it.
  14795. void PemMemoryClientCertPresent(
  14796. const std::string &client_cert_file,
  14797. const std::string &client_private_key_file,
  14798. const std::string &client_encrypted_private_key_pass = std::string(),
  14799. bool exact_size = false) {
  14800. // Read PEM files into memory
  14801. std::string server_cert_pem, server_key_pem;
  14802. std::string client_ca_pem;
  14803. std::string client_cert_pem, client_key_pem;
  14804. read_file(SERVER_CERT_FILE, server_cert_pem);
  14805. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14806. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14807. read_file(client_cert_file, client_cert_pem);
  14808. read_file(client_private_key_file, client_key_pem);
  14809. std::list<std::vector<char>> exact_copies;
  14810. auto data = [&](const std::string &pem) -> const char * {
  14811. if (!exact_size) { return pem.c_str(); }
  14812. exact_copies.emplace_back(pem.begin(), pem.end());
  14813. return exact_copies.back().data();
  14814. };
  14815. // Create server with PEM memory
  14816. SSLServer::PemMemory server_pem = {
  14817. data(server_cert_pem),
  14818. server_cert_pem.size(),
  14819. data(server_key_pem),
  14820. server_key_pem.size(),
  14821. data(client_ca_pem),
  14822. client_ca_pem.size(),
  14823. nullptr // no password for server key
  14824. };
  14825. SSLServer svr(server_pem);
  14826. ASSERT_TRUE(svr.is_valid());
  14827. svr.Get("/test", [&](const Request &req, Response &res) {
  14828. res.set_content("test", "text/plain");
  14829. auto cert = req.peer_cert();
  14830. ASSERT_TRUE(static_cast<bool>(cert));
  14831. EXPECT_EQ("Common Name", cert.subject_cn());
  14832. });
  14833. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14834. auto se = detail::scope_exit([&] {
  14835. svr.stop();
  14836. t.join();
  14837. ASSERT_FALSE(svr.is_running());
  14838. });
  14839. svr.wait_until_ready();
  14840. // Create client with PEM memory
  14841. const char *password = client_encrypted_private_key_pass.empty()
  14842. ? nullptr
  14843. : client_encrypted_private_key_pass.c_str();
  14844. SSLClient::PemMemory client_pem = {
  14845. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14846. client_key_pem.size(), password};
  14847. SSLClient cli(HOST, PORT, client_pem);
  14848. cli.enable_server_certificate_verification(false);
  14849. cli.set_connection_timeout(30);
  14850. auto res = cli.Get("/test");
  14851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14852. ASSERT_EQ(StatusCode::OK_200, res->status);
  14853. }
  14854. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14855. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14856. }
  14857. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14858. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14859. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14860. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14861. }
  14862. // A server built from PEM memory with a client CA requires client certificates,
  14863. // also when the CA is a NUL-terminated string passed with a length of 0
  14864. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14865. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14866. read_file(SERVER_CERT_FILE, server_cert_pem);
  14867. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14868. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14869. SSLServer::PemMemory server_pem = {
  14870. server_cert_pem.c_str(),
  14871. server_cert_pem.size(),
  14872. server_key_pem.c_str(),
  14873. server_key_pem.size(),
  14874. client_ca_pem.c_str(),
  14875. client_ca_pem.size(),
  14876. nullptr // no password for server key
  14877. };
  14878. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14879. SCOPED_TRACE(client_ca_pem_len);
  14880. server_pem.client_ca_pem_len = client_ca_pem_len;
  14881. SSLServer svr(server_pem);
  14882. ASSERT_TRUE(svr.is_valid());
  14883. RejectsClientWithoutCert(svr);
  14884. }
  14885. // An empty CA fails to load instead of turning the check off
  14886. server_pem.client_ca_pem = "";
  14887. server_pem.client_ca_pem_len = 0;
  14888. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14889. }
  14890. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14891. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14892. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14893. true);
  14894. }
  14895. // A length shorter than the PEM cuts it short, so it no longer loads
  14896. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14897. std::string cert, key;
  14898. read_file(SERVER_CERT_FILE, cert);
  14899. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14900. for (auto cut_cert : {true, false}) {
  14901. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14902. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14903. SSLServer::PemMemory server_pem = {
  14904. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14905. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14906. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14907. key_len, nullptr};
  14908. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14909. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14910. key.c_str(), key_len, nullptr};
  14911. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14912. }
  14913. }
  14914. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14915. class NoListenSSLServer : public SSLServer {
  14916. public:
  14917. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14918. const char *client_ca_cert_file_path,
  14919. const char *client_ca_cert_dir_path = nullptr)
  14920. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14921. client_ca_cert_dir_path),
  14922. stop_(false) {}
  14923. std::atomic_bool stop_;
  14924. private:
  14925. bool process_and_close_socket(socket_t /*sock*/) override {
  14926. // Don't create SSL context
  14927. while (!stop_.load()) {
  14928. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14929. }
  14930. return true;
  14931. }
  14932. };
  14933. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14934. CLIENT_CA_CERT_FILE);
  14935. ASSERT_TRUE(svr.is_valid());
  14936. // Keep-alive parking would bypass the override.
  14937. svr.set_keep_alive_parking(false);
  14938. svr.Get("/test", [&](const Request &, Response &res) {
  14939. res.set_content("test", "text/plain");
  14940. });
  14941. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14942. auto se = detail::scope_exit([&] {
  14943. svr.stop_ = true;
  14944. svr.stop();
  14945. t.join();
  14946. ASSERT_FALSE(svr.is_running());
  14947. });
  14948. svr.wait_until_ready();
  14949. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14950. cli.enable_server_certificate_verification(false);
  14951. cli.set_connection_timeout(1);
  14952. auto res = cli.Get("/test");
  14953. ASSERT_TRUE(!res);
  14954. EXPECT_EQ(Error::SSLConnection, res.error());
  14955. // Timeout results in WantRead error code (maps to backend-specific value)
  14956. EXPECT_NE(0, res.ssl_error());
  14957. }
  14958. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14959. // Test SSLServer with client certificate verification using the standard
  14960. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14962. CLIENT_CA_CERT_DIR);
  14963. ASSERT_TRUE(svr.is_valid());
  14964. svr.Get("/test", [&](const Request &req, Response &res) {
  14965. res.set_content("test", "text/plain");
  14966. auto cert = req.peer_cert();
  14967. ASSERT_TRUE(static_cast<bool>(cert));
  14968. auto common_name = cert.subject_cn();
  14969. EXPECT_EQ("Common Name", common_name);
  14970. });
  14971. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14972. auto se = detail::scope_exit([&] {
  14973. svr.stop();
  14974. t.join();
  14975. ASSERT_FALSE(svr.is_running());
  14976. });
  14977. svr.wait_until_ready();
  14978. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14979. cli.enable_server_certificate_verification(false);
  14980. cli.set_connection_timeout(30);
  14981. auto res = cli.Get("/test");
  14982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14983. ASSERT_EQ(StatusCode::OK_200, res->status);
  14984. }
  14985. // Test verify_hostname on every backend: a host is named by a SAN only
  14986. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14987. using namespace httplib::tls;
  14988. // We need a running server to test against
  14989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14990. ASSERT_TRUE(svr.is_valid());
  14991. svr.Get("/test", [](const Request &, Response &res) {
  14992. res.set_content("ok", "text/plain");
  14993. });
  14994. thread t([&]() { svr.listen(HOST, PORT); });
  14995. auto se = detail::scope_exit([&] {
  14996. svr.stop();
  14997. t.join();
  14998. });
  14999. svr.wait_until_ready();
  15000. bool verify_callback_called = false;
  15001. bool verify_result_wrong = false;
  15002. SSLClient cli(HOST, PORT);
  15003. cli.enable_server_certificate_verification(true);
  15004. cli.set_ca_cert_path(CA_CERT_FILE);
  15005. cli.set_connection_timeout(5);
  15006. // Note: Test certificate has CN="Common Name", not "localhost"
  15007. bool verify_result_cn = false;
  15008. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15009. verify_callback_called = true;
  15010. if (!ctx.cert) return false;
  15011. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  15012. verify_result_cn = ctx.check_hostname("Common Name");
  15013. // Test 2: wrong hostname should not match
  15014. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  15015. return true; // Accept for the purpose of this test
  15016. });
  15017. auto res = cli.Get("/test");
  15018. // The request may succeed or fail depending on cert configuration
  15019. // but the callback should have been called
  15020. ASSERT_TRUE(verify_callback_called)
  15021. << "Verify callback should have been called";
  15022. EXPECT_FALSE(verify_result_cn)
  15023. << "verify_hostname must not match the certificate CN (no SAN)";
  15024. // Wrong hostname should not match
  15025. EXPECT_FALSE(verify_result_wrong)
  15026. << "verify_hostname should not match 'wronghost.example.com'";
  15027. }
  15028. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  15029. // backend verifies it.
  15030. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  15031. // Certificate CN is "localhost" and it carries no SAN.
  15032. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15033. ASSERT_TRUE(svr.is_valid());
  15034. svr.Get("/test", [](const Request &, Response &res) {
  15035. res.set_content("ok", "text/plain");
  15036. });
  15037. auto port = svr.bind_to_any_port(HOST);
  15038. thread t([&]() { svr.listen_after_bind(); });
  15039. auto se = detail::scope_exit([&] {
  15040. svr.stop();
  15041. t.join();
  15042. });
  15043. svr.wait_until_ready();
  15044. SSLClient cli("localhost", port);
  15045. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15046. cli.enable_server_certificate_verification(true);
  15047. cli.set_connection_timeout(5);
  15048. auto res = cli.Get("/test");
  15049. ASSERT_FALSE(res);
  15050. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15051. // The same certificate is accepted once host name verification is off, so the
  15052. // failure above is the host name and not the chain.
  15053. cli.enable_server_hostname_verification(false);
  15054. res = cli.Get("/test");
  15055. ASSERT_TRUE(res) << to_string(res.error());
  15056. EXPECT_EQ(StatusCode::OK_200, res->status);
  15057. }
  15058. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15059. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15060. // X509_check_ip behavior and must hold for every backend.
  15061. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15062. using namespace httplib::tls;
  15063. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15064. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15065. ASSERT_TRUE(svr.is_valid());
  15066. svr.Get("/test", [](const Request &, Response &res) {
  15067. res.set_content("ok", "text/plain");
  15068. });
  15069. thread t([&]() { svr.listen(HOST, PORT); });
  15070. auto se = detail::scope_exit([&] {
  15071. svr.stop();
  15072. t.join();
  15073. });
  15074. svr.wait_until_ready();
  15075. bool verify_callback_called = false;
  15076. bool ip_matched_via_cn = true;
  15077. SSLClient cli(HOST, PORT);
  15078. cli.enable_server_certificate_verification(true);
  15079. cli.set_ca_cert_path(CA_CERT_FILE);
  15080. cli.set_connection_timeout(5);
  15081. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15082. verify_callback_called = true;
  15083. if (!ctx.cert) return false;
  15084. // The IP appears only in the CN, so it must NOT be accepted.
  15085. ip_matched_via_cn = ctx.check_hostname("127.0.0.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_FALSE(ip_matched_via_cn)
  15092. << "An IP host must not be authenticated via the certificate CN";
  15093. }
  15094. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15095. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15096. using namespace httplib::tls;
  15097. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15098. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15099. ASSERT_TRUE(svr.is_valid());
  15100. svr.Get("/test", [](const Request &, Response &res) {
  15101. res.set_content("ok", "text/plain");
  15102. });
  15103. thread t([&]() { svr.listen(HOST, PORT); });
  15104. auto se = detail::scope_exit([&] {
  15105. svr.stop();
  15106. t.join();
  15107. });
  15108. svr.wait_until_ready();
  15109. bool verify_callback_called = false;
  15110. bool san_matched = false;
  15111. bool wrong_ipv6_matched = true;
  15112. bool cn_ipv6_matched = true;
  15113. SSLClient cli(HOST, PORT);
  15114. cli.enable_server_certificate_verification(true);
  15115. cli.set_ca_cert_path(CA_CERT_FILE);
  15116. cli.set_connection_timeout(5);
  15117. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15118. verify_callback_called = true;
  15119. if (!ctx.cert) return false;
  15120. // Matches the IPv6 iPAddress SAN.
  15121. san_matched = ctx.check_hostname("2001:db8::1");
  15122. // A different IPv6 address must not match.
  15123. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15124. // "::1" lives only in the CN, so it must not be accepted.
  15125. cn_ipv6_matched = ctx.check_hostname("::1");
  15126. return true; // Accept for the purpose of this test
  15127. });
  15128. cli.Get("/test");
  15129. ASSERT_TRUE(verify_callback_called)
  15130. << "Verify callback should have been called";
  15131. EXPECT_TRUE(san_matched)
  15132. << "verify_hostname should match an IPv6 iPAddress SAN";
  15133. EXPECT_FALSE(wrong_ipv6_matched)
  15134. << "verify_hostname should not match a non-matching IPv6 address";
  15135. EXPECT_FALSE(cn_ipv6_matched)
  15136. << "An IPv6 host must not be authenticated via the certificate CN";
  15137. }
  15138. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15139. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15140. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15141. using namespace httplib::tls;
  15142. // SANs: DNS:a.zz, IP:42.46.122.122
  15143. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15144. ASSERT_TRUE(svr.is_valid());
  15145. svr.Get("/test", [](const Request &, Response &res) {
  15146. res.set_content("ok", "text/plain");
  15147. });
  15148. auto port = svr.bind_to_any_port(HOST);
  15149. thread t([&]() { svr.listen_after_bind(); });
  15150. auto se = detail::scope_exit([&] {
  15151. svr.stop();
  15152. t.join();
  15153. });
  15154. svr.wait_until_ready();
  15155. bool verify_callback_called = false;
  15156. bool dns_san_matched = false;
  15157. bool ip_san_matched = false;
  15158. bool ip_matched_via_dns_san = true;
  15159. bool dns_matched_via_ip_san = true;
  15160. bool cn_matched_next_to_dns_san = true;
  15161. SSLClient cli(HOST, port);
  15162. cli.enable_server_certificate_verification(true);
  15163. cli.set_ca_cert_path(CA_CERT_FILE);
  15164. cli.set_connection_timeout(5);
  15165. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15166. verify_callback_called = true;
  15167. if (!ctx.cert) return false;
  15168. dns_san_matched = ctx.check_hostname("a.zz");
  15169. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15170. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15171. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15172. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15173. return true; // Accept for the purpose of this test
  15174. });
  15175. cli.Get("/test");
  15176. ASSERT_TRUE(verify_callback_called)
  15177. << "Verify callback should have been called";
  15178. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15179. EXPECT_TRUE(ip_san_matched)
  15180. << "verify_hostname should match an iPAddress SAN";
  15181. EXPECT_FALSE(ip_matched_via_dns_san)
  15182. << "An IP host must not be authenticated via a dNSName SAN";
  15183. EXPECT_FALSE(dns_matched_via_ip_san)
  15184. << "A DNS host must not be authenticated via an iPAddress SAN";
  15185. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15186. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15187. }
  15188. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15189. // "www.*.example.test" names one host and not every host under example.test.
  15190. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15191. using namespace httplib::tls;
  15192. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15193. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15194. ASSERT_TRUE(svr.is_valid());
  15195. svr.Get("/test", [](const Request &, Response &res) {
  15196. res.set_content("ok", "text/plain");
  15197. });
  15198. auto port = svr.bind_to_any_port(HOST);
  15199. thread t([&]() { svr.listen_after_bind(); });
  15200. auto se = detail::scope_exit([&] {
  15201. svr.stop();
  15202. t.join();
  15203. });
  15204. svr.wait_until_ready();
  15205. bool verify_callback_called = false;
  15206. bool leftmost_wildcard_matched = false;
  15207. bool wildcard_spanned_labels = true;
  15208. bool inner_wildcard_matched = true;
  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. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15217. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15218. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15219. return true; // Accept for the purpose of this test
  15220. });
  15221. cli.Get("/test");
  15222. ASSERT_TRUE(verify_callback_called)
  15223. << "Verify callback should have been called";
  15224. EXPECT_TRUE(leftmost_wildcard_matched)
  15225. << "A leftmost wildcard should match a single label";
  15226. EXPECT_FALSE(wildcard_spanned_labels)
  15227. << "A wildcard label must not match more than one label";
  15228. EXPECT_FALSE(inner_wildcard_matched)
  15229. << "A wildcard outside the leftmost label must not be honoured";
  15230. }
  15231. // sans() must report each SAN entry under its own type.
  15232. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15233. using namespace httplib::tls;
  15234. // SANs: DNS:a.zz, IP:42.46.122.122
  15235. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15236. ASSERT_TRUE(svr.is_valid());
  15237. svr.Get("/test", [](const Request &, Response &res) {
  15238. res.set_content("ok", "text/plain");
  15239. });
  15240. auto port = svr.bind_to_any_port(HOST);
  15241. thread t([&]() { svr.listen_after_bind(); });
  15242. auto se = detail::scope_exit([&] {
  15243. svr.stop();
  15244. t.join();
  15245. });
  15246. svr.wait_until_ready();
  15247. bool verify_callback_called = false;
  15248. std::vector<SanEntry> sans;
  15249. SSLClient cli(HOST, port);
  15250. cli.enable_server_certificate_verification(true);
  15251. cli.set_ca_cert_path(CA_CERT_FILE);
  15252. cli.set_connection_timeout(5);
  15253. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15254. verify_callback_called = true;
  15255. if (!ctx.cert) return false;
  15256. sans = ctx.sans();
  15257. return true; // Accept for the purpose of this test
  15258. });
  15259. cli.Get("/test");
  15260. ASSERT_TRUE(verify_callback_called)
  15261. << "Verify callback should have been called";
  15262. auto has_san = [&](SanType type, const std::string &value) {
  15263. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15264. return san.type == type && san.value == value;
  15265. });
  15266. };
  15267. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15268. << "sans() should report the dNSName SAN";
  15269. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15270. << "sans() should report the iPAddress SAN";
  15271. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15272. << "sans() must not report the dNSName SAN as an address";
  15273. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15274. << "sans() must not report the iPAddress SAN as a DNS name";
  15275. }
  15276. #endif
  15277. // mbedTLS-specific callback constructor test
  15278. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15279. #ifdef CPPHTTPLIB_SSL_ENABLED
  15280. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15281. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15282. ASSERT_TRUE(svr.is_valid());
  15283. // Set up a handler to verify client certificate is present
  15284. bool client_cert_verified = false;
  15285. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15286. // Verify that client certificate was provided
  15287. client_cert_verified = true;
  15288. res.set_content("success", "text/plain");
  15289. });
  15290. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15291. auto se = detail::scope_exit([&] {
  15292. svr.stop();
  15293. t.join();
  15294. ASSERT_FALSE(svr.is_running());
  15295. });
  15296. svr.wait_until_ready();
  15297. // Client with certificate
  15298. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15299. cli.enable_server_certificate_verification(false);
  15300. cli.set_connection_timeout(30);
  15301. auto res = cli.Get("/test");
  15302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15303. ASSERT_EQ(StatusCode::OK_200, res->status);
  15304. ASSERT_TRUE(client_cert_verified);
  15305. EXPECT_EQ("success", res->body);
  15306. }
  15307. #endif
  15308. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15309. // backends
  15310. #ifdef CPPHTTPLIB_SSL_ENABLED
  15311. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15312. using namespace httplib::tls;
  15313. // Test that when client CA cert file is provided,
  15314. // the server properly requests and validates client certificates
  15315. // Create a server with client authentication
  15316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15317. ASSERT_TRUE(svr.is_valid());
  15318. bool handler_called = false;
  15319. svr.Get("/test", [&](const Request &req, Response &res) {
  15320. handler_called = true;
  15321. // Verify that a client certificate was provided
  15322. auto cert = req.peer_cert();
  15323. ASSERT_TRUE(static_cast<bool>(cert));
  15324. // Get the issuer name
  15325. std::string issuer_str = cert.issuer_name();
  15326. ASSERT_FALSE(issuer_str.empty());
  15327. // The client certificate should be issued by our test CA
  15328. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15329. res.set_content("authenticated", "text/plain");
  15330. });
  15331. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15332. auto se = detail::scope_exit([&] {
  15333. svr.stop();
  15334. t.join();
  15335. ASSERT_FALSE(svr.is_running());
  15336. });
  15337. svr.wait_until_ready();
  15338. // Connect with a client certificate issued by the CA
  15339. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15340. cli.enable_server_certificate_verification(false);
  15341. cli.set_connection_timeout(30);
  15342. auto res = cli.Get("/test");
  15343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15344. ASSERT_EQ(StatusCode::OK_200, res->status);
  15345. ASSERT_TRUE(handler_called);
  15346. EXPECT_EQ("authenticated", res->body);
  15347. }
  15348. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15349. using namespace httplib::tls;
  15350. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15351. ASSERT_TRUE(svr.is_valid());
  15352. svr.Get("/test", [](const Request &, Response &res) {
  15353. res.set_content("ok", "text/plain");
  15354. });
  15355. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15356. auto se = detail::scope_exit([&] {
  15357. svr.stop();
  15358. t.join();
  15359. });
  15360. svr.wait_until_ready();
  15361. SSLClient cli(HOST, PORT);
  15362. cli.enable_server_certificate_verification(false);
  15363. cli.set_connection_timeout(30);
  15364. bool cert_checked = false;
  15365. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15366. if (ctx.cert) {
  15367. auto sans = ctx.sans();
  15368. // Test certificate may or may not have SANs - just verify the API
  15369. // works If SANs exist, verify the types are valid
  15370. for (const auto &san : sans) {
  15371. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15372. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15373. san.type == SanType::OTHER);
  15374. EXPECT_FALSE(san.value.empty());
  15375. }
  15376. cert_checked = true;
  15377. }
  15378. return true;
  15379. });
  15380. auto res = cli.Get("/test");
  15381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15382. EXPECT_TRUE(cert_checked);
  15383. }
  15384. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15385. using namespace httplib::tls;
  15386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15387. ASSERT_TRUE(svr.is_valid());
  15388. svr.Get("/test", [](const Request &, Response &res) {
  15389. res.set_content("ok", "text/plain");
  15390. });
  15391. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15392. auto se = detail::scope_exit([&] {
  15393. svr.stop();
  15394. t.join();
  15395. });
  15396. svr.wait_until_ready();
  15397. SSLClient cli(HOST, PORT);
  15398. cli.enable_server_certificate_verification(false);
  15399. cli.set_connection_timeout(30);
  15400. bool validity_checked = false;
  15401. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15402. if (ctx.cert) {
  15403. time_t not_before = 0, not_after = 0;
  15404. bool result = ctx.validity(not_before, not_after);
  15405. EXPECT_TRUE(result);
  15406. // Verify that not_before < now < not_after for a valid cert
  15407. time_t now = time(nullptr);
  15408. EXPECT_LT(not_before, now);
  15409. EXPECT_GT(not_after, now);
  15410. validity_checked = true;
  15411. }
  15412. return true;
  15413. });
  15414. auto res = cli.Get("/test");
  15415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15416. EXPECT_TRUE(validity_checked);
  15417. }
  15418. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15419. using namespace httplib::tls;
  15420. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15421. ASSERT_TRUE(svr.is_valid());
  15422. svr.Get("/test", [](const Request &, Response &res) {
  15423. res.set_content("ok", "text/plain");
  15424. });
  15425. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15426. auto se = detail::scope_exit([&] {
  15427. svr.stop();
  15428. t.join();
  15429. });
  15430. svr.wait_until_ready();
  15431. SSLClient cli(HOST, PORT);
  15432. cli.enable_server_certificate_verification(false);
  15433. cli.set_connection_timeout(30);
  15434. bool serial_checked = false;
  15435. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15436. if (ctx.cert) {
  15437. std::string serial = ctx.serial();
  15438. EXPECT_FALSE(serial.empty());
  15439. // Serial should be a hex string
  15440. for (char c : serial) {
  15441. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15442. (c >= 'a' && c <= 'f'));
  15443. }
  15444. serial_checked = true;
  15445. }
  15446. return true;
  15447. });
  15448. auto res = cli.Get("/test");
  15449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15450. EXPECT_TRUE(serial_checked);
  15451. }
  15452. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15453. // Test 1: Valid CA file - no error should be recorded
  15454. {
  15455. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15456. CLIENT_CA_CERT_FILE);
  15457. ASSERT_TRUE(svr.is_valid());
  15458. // With valid setup, last_ssl_error should be 0
  15459. EXPECT_EQ(0, svr.ssl_last_error());
  15460. }
  15461. // Test 2: Invalid CA file content
  15462. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15463. {
  15464. // Create a temporary file with completely invalid content
  15465. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15466. {
  15467. std::ofstream ofs(temp_invalid_ca);
  15468. ofs << "This is not a certificate file at all\n";
  15469. ofs << "Just plain text content\n";
  15470. }
  15471. // Create server with invalid CA file
  15472. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15473. // Clean up temporary file
  15474. std::remove(temp_invalid_ca);
  15475. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15476. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15477. // Note: SSL_CTX_load_verify_locations typically fails first,
  15478. // but our error handling code path is still exercised
  15479. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15480. }
  15481. }
  15482. TEST(VerifyCallbackTest, VerifyContextFields) {
  15483. using namespace httplib::tls;
  15484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15485. ASSERT_TRUE(svr.is_valid());
  15486. svr.Get("/test", [](const Request &, Response &res) {
  15487. res.set_content("ok", "text/plain");
  15488. });
  15489. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15490. auto se = detail::scope_exit([&] {
  15491. svr.stop();
  15492. t.join();
  15493. });
  15494. svr.wait_until_ready();
  15495. SSLClient cli(HOST, PORT);
  15496. cli.enable_server_certificate_verification(false);
  15497. cli.set_connection_timeout(30);
  15498. int callback_count = 0;
  15499. bool saw_leaf_cert = false;
  15500. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15501. if (ctx.cert) {
  15502. callback_count++;
  15503. // We should see at least one certificate (the leaf)
  15504. std::string cn = ctx.subject_cn();
  15505. if (!cn.empty()) { saw_leaf_cert = true; }
  15506. // Verify context fields are populated
  15507. EXPECT_NE(ctx.session, nullptr);
  15508. EXPECT_GE(ctx.depth, 0);
  15509. }
  15510. return true;
  15511. });
  15512. auto res = cli.Get("/test");
  15513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15514. EXPECT_GT(callback_count, 0);
  15515. EXPECT_TRUE(saw_leaf_cert);
  15516. }
  15517. // A verifier that accepts runs alongside the built-in verification, and is the
  15518. // only check once that is turned off.
  15519. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15520. using namespace httplib::tls;
  15521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15522. ASSERT_TRUE(svr.is_valid());
  15523. svr.Get("/test", [](const Request &, Response &res) {
  15524. res.set_content("ok", "text/plain");
  15525. });
  15526. auto port = svr.bind_to_any_port(HOST);
  15527. thread t([&]() { svr.listen_after_bind(); });
  15528. auto se = detail::scope_exit([&] {
  15529. svr.stop();
  15530. t.join();
  15531. });
  15532. svr.wait_until_ready();
  15533. SSLClient cli(HOST, port);
  15534. cli.enable_server_hostname_verification(false);
  15535. auto calls = 0;
  15536. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15537. calls++;
  15538. return true;
  15539. });
  15540. // cert.pem is not trusted
  15541. auto res = cli.Get("/test");
  15542. ASSERT_FALSE(res);
  15543. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15544. EXPECT_GT(calls, 0);
  15545. cli.enable_server_certificate_verification(false);
  15546. res = cli.Get("/test");
  15547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15548. EXPECT_EQ("ok", res->body);
  15549. }
  15550. // A verifier belongs to the client that set it, not to the thread that set it.
  15551. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15552. using namespace httplib::tls;
  15553. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15554. ASSERT_TRUE(svr.is_valid());
  15555. svr.Get("/test", [](const Request &, Response &res) {
  15556. res.set_content("ok", "text/plain");
  15557. });
  15558. auto port = svr.bind_to_any_port(HOST);
  15559. thread t([&]() { svr.listen_after_bind(); });
  15560. auto se = detail::scope_exit([&] {
  15561. svr.stop();
  15562. t.join();
  15563. });
  15564. svr.wait_until_ready();
  15565. auto rejecting_calls = 0;
  15566. SSLClient rejecting(HOST, port);
  15567. rejecting.enable_server_certificate_verification(false);
  15568. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15569. rejecting_calls++;
  15570. return false;
  15571. });
  15572. auto accepting_calls = 0;
  15573. SSLClient accepting(HOST, port);
  15574. accepting.enable_server_certificate_verification(false);
  15575. // Set on another thread than the requests below.
  15576. thread([&]() {
  15577. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15578. accepting_calls++;
  15579. return true;
  15580. });
  15581. }).join();
  15582. // Requested on another thread than the verifier was set on.
  15583. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15584. EXPECT_GT(rejecting_calls, 0);
  15585. auto res = accepting.Get("/test");
  15586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15587. EXPECT_GT(accepting_calls, 0);
  15588. }
  15589. // A verifier replaced while a handshake runs it lives until it returns.
  15590. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15591. using namespace httplib::tls;
  15592. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15593. ASSERT_TRUE(svr.is_valid());
  15594. svr.Get("/test", [](const Request &, Response &res) {
  15595. res.set_content("ok", "text/plain");
  15596. });
  15597. auto port = svr.bind_to_any_port(HOST);
  15598. thread t([&]() { svr.listen_after_bind(); });
  15599. auto se = detail::scope_exit([&] {
  15600. svr.stop();
  15601. t.join();
  15602. });
  15603. svr.wait_until_ready();
  15604. SSLClient cli(HOST, port);
  15605. cli.enable_server_certificate_verification(false);
  15606. std::promise<void> entered;
  15607. std::promise<void> replaced;
  15608. auto replaced_future = replaced.get_future();
  15609. auto first_call = true;
  15610. // Long enough to live on the heap
  15611. std::string expected(64, 'v');
  15612. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15613. if (first_call) {
  15614. first_call = false;
  15615. entered.set_value();
  15616. replaced_future.wait();
  15617. }
  15618. return expected == std::string(64, 'v');
  15619. });
  15620. thread request([&]() {
  15621. auto res = cli.Get("/test");
  15622. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15623. });
  15624. entered.get_future().wait();
  15625. cli.set_server_certificate_verifier(
  15626. [](const VerifyContext &) { return true; });
  15627. replaced.set_value();
  15628. request.join();
  15629. }
  15630. // VerifyContext::session is the same handle the other tls:: functions take.
  15631. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15632. using namespace httplib::tls;
  15633. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15634. ASSERT_TRUE(svr.is_valid());
  15635. svr.Get("/test", [](const Request &, Response &res) {
  15636. res.set_content("ok", "text/plain");
  15637. });
  15638. auto port = svr.bind_to_any_port(HOST);
  15639. thread t([&]() { svr.listen_after_bind(); });
  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. session_t verifier_session = nullptr;
  15648. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15649. verifier_session = ctx.session;
  15650. return true;
  15651. });
  15652. session_t session_verifier_session = nullptr;
  15653. cli.set_session_verifier([&](session_t session) {
  15654. session_verifier_session = session;
  15655. return SSLVerifierResponse::NoDecisionMade;
  15656. });
  15657. auto res = cli.Get("/test");
  15658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15659. EXPECT_NE(nullptr, verifier_session);
  15660. EXPECT_EQ(session_verifier_session, verifier_session);
  15661. }
  15662. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15663. using httplib::tls::TlsError;
  15664. // Test that verify_error_to_string returns empty for success
  15665. std::string success_str = TlsError::verify_error_to_string(0);
  15666. EXPECT_TRUE(success_str.empty());
  15667. // Test that verify_error_to_string returns non-empty for error codes
  15668. // Using a common error code (certificate expired)
  15669. std::string error_str =
  15670. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15671. EXPECT_FALSE(error_str.empty());
  15672. }
  15673. TEST(SessionVerifierTest, CertificateAccepted) {
  15674. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15675. ASSERT_TRUE(svr.is_valid());
  15676. svr.Get("/test", [](const Request &, Response &res) {
  15677. res.set_content("ok", "text/plain");
  15678. });
  15679. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15680. auto se = detail::scope_exit([&] {
  15681. svr.stop();
  15682. t.join();
  15683. });
  15684. svr.wait_until_ready();
  15685. SSLClient cli(HOST, PORT);
  15686. cli.enable_server_certificate_verification(false);
  15687. cli.set_connection_timeout(30);
  15688. bool callback_called = false;
  15689. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15690. EXPECT_NE(session, nullptr);
  15691. callback_called = true;
  15692. return SSLVerifierResponse::CertificateAccepted;
  15693. });
  15694. auto res = cli.Get("/test");
  15695. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15696. EXPECT_EQ(200, res->status);
  15697. EXPECT_TRUE(callback_called);
  15698. }
  15699. TEST(SessionVerifierTest, CertificateRejected) {
  15700. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15701. ASSERT_TRUE(svr.is_valid());
  15702. svr.Get("/test", [](const Request &, Response &res) {
  15703. res.set_content("ok", "text/plain");
  15704. });
  15705. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15706. auto se = detail::scope_exit([&] {
  15707. svr.stop();
  15708. t.join();
  15709. });
  15710. svr.wait_until_ready();
  15711. SSLClient cli(HOST, PORT);
  15712. cli.enable_server_certificate_verification(false);
  15713. cli.set_connection_timeout(30);
  15714. bool callback_called = false;
  15715. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15716. EXPECT_NE(session, nullptr);
  15717. callback_called = true;
  15718. return SSLVerifierResponse::CertificateRejected;
  15719. });
  15720. auto res = cli.Get("/test");
  15721. EXPECT_FALSE(res);
  15722. EXPECT_TRUE(callback_called);
  15723. }
  15724. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15725. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15726. ASSERT_TRUE(svr.is_valid());
  15727. svr.Get("/test", [](const Request &, Response &res) {
  15728. res.set_content("ok", "text/plain");
  15729. });
  15730. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15731. auto se = detail::scope_exit([&] {
  15732. svr.stop();
  15733. t.join();
  15734. });
  15735. svr.wait_until_ready();
  15736. // NoDecisionMade with verification disabled should succeed (no default check)
  15737. SSLClient cli(HOST, PORT);
  15738. cli.enable_server_certificate_verification(false);
  15739. cli.set_connection_timeout(30);
  15740. bool callback_called = false;
  15741. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15742. EXPECT_NE(session, nullptr);
  15743. callback_called = true;
  15744. return SSLVerifierResponse::NoDecisionMade;
  15745. });
  15746. auto res = cli.Get("/test");
  15747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15748. EXPECT_EQ(200, res->status);
  15749. EXPECT_TRUE(callback_called);
  15750. }
  15751. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15752. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15753. ASSERT_TRUE(svr.is_valid());
  15754. svr.Get("/test", [](const Request &, Response &res) {
  15755. res.set_content("ok", "text/plain");
  15756. });
  15757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15758. auto se = detail::scope_exit([&] {
  15759. svr.stop();
  15760. t.join();
  15761. });
  15762. svr.wait_until_ready();
  15763. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15764. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15765. // so we only check that the request fails, not whether the callback was
  15766. // called.
  15767. SSLClient cli(HOST, PORT);
  15768. cli.enable_server_certificate_verification(true);
  15769. cli.set_connection_timeout(30);
  15770. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15771. EXPECT_NE(session, nullptr);
  15772. return SSLVerifierResponse::NoDecisionMade;
  15773. });
  15774. auto res = cli.Get("/test");
  15775. EXPECT_FALSE(res);
  15776. }
  15777. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15778. // Test SSL server using PemMemory constructor with client CA certificates
  15779. // Read PEM files
  15780. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15781. read_file(SERVER_CERT_FILE, server_cert_pem);
  15782. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15783. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15784. // Create SSLServer with PemMemory constructor including client CA
  15785. SSLServer::PemMemory server_pem = {
  15786. server_cert_pem.c_str(),
  15787. server_cert_pem.size(),
  15788. server_key_pem.c_str(),
  15789. server_key_pem.size(),
  15790. client_ca_pem.c_str(),
  15791. client_ca_pem.size(),
  15792. nullptr // no password for server key
  15793. };
  15794. SSLServer svr(server_pem);
  15795. ASSERT_TRUE(svr.is_valid());
  15796. // No SSL error should be recorded for valid setup
  15797. EXPECT_EQ(0, svr.ssl_last_error());
  15798. // Set up server endpoints
  15799. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15800. res.set_content("ok", "text/plain");
  15801. });
  15802. // Start server in a thread
  15803. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15804. svr.wait_until_ready();
  15805. // Connect with client certificate (using constructor with paths)
  15806. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15807. cli.enable_server_certificate_verification(false);
  15808. auto res = cli.Get("/test-pem-ca");
  15809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15810. EXPECT_EQ(200, res->status);
  15811. EXPECT_EQ("ok", res->body);
  15812. svr.stop();
  15813. server_thread.join();
  15814. }
  15815. #endif
  15816. #ifdef _WIN32
  15817. TEST(CleanupTest, WSACleanup) {
  15818. int ret = WSACleanup();
  15819. ASSERT_EQ(0, ret);
  15820. }
  15821. #endif
  15822. #ifndef CPPHTTPLIB_SSL_ENABLED
  15823. TEST(NoSSLSupport, SimpleInterface) {
  15824. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15825. }
  15826. #endif
  15827. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15828. TEST(InvalidScheme, SimpleInterface) {
  15829. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15830. }
  15831. #endif
  15832. TEST(NoScheme, SimpleInterface) {
  15833. Client cli("yahoo.com:80");
  15834. ASSERT_TRUE(cli.is_valid());
  15835. }
  15836. TEST(SendAPI, SimpleInterface_Online) {
  15837. Client cli("http://yahoo.com");
  15838. Request req;
  15839. req.method = "GET";
  15840. req.path = "/";
  15841. auto res = cli.send(req);
  15842. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15843. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15844. }
  15845. TEST(SendAPI, WithParamsInRequest) {
  15846. Server svr;
  15847. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15848. EXPECT_TRUE(req.has_param("test"));
  15849. EXPECT_EQ("test_value", req.get_param_value("test"));
  15850. });
  15851. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15852. auto se = detail::scope_exit([&] {
  15853. svr.stop();
  15854. t.join();
  15855. ASSERT_FALSE(svr.is_running());
  15856. });
  15857. svr.wait_until_ready();
  15858. Client cli(HOST, PORT);
  15859. {
  15860. Request req;
  15861. req.method = "GET";
  15862. req.path = "/";
  15863. req.params.emplace("test", "test_value");
  15864. auto res = cli.send(req);
  15865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15866. }
  15867. {
  15868. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15870. }
  15871. }
  15872. TEST(ClientImplMethods, GetSocketTest) {
  15873. httplib::Server svr;
  15874. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15875. res.status = StatusCode::OK_200;
  15876. });
  15877. auto port = svr.bind_to_any_port("127.0.0.1");
  15878. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15879. auto se = detail::scope_exit([&] {
  15880. svr.stop();
  15881. thread.join();
  15882. ASSERT_FALSE(svr.is_running());
  15883. });
  15884. svr.wait_until_ready();
  15885. {
  15886. httplib::Client cli("127.0.0.1", port);
  15887. cli.set_keep_alive(true);
  15888. // Use the behavior of cpp-httplib of opening the connection
  15889. // only when the first request happens. If that changes,
  15890. // this test would be obsolete.
  15891. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15892. // This also implicitly tests the server. But other tests would fail much
  15893. // earlier than this one to be considered.
  15894. auto res = cli.Get("/");
  15895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15896. EXPECT_EQ(StatusCode::OK_200, res->status);
  15897. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15898. }
  15899. }
  15900. #ifdef CPPHTTPLIB_SSL_ENABLED
  15901. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15902. Client cli("http://yahoo.com");
  15903. auto res = cli.Get("/");
  15904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15905. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15906. cli.set_follow_location(true);
  15907. res = cli.Get("/");
  15908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15909. EXPECT_EQ(StatusCode::OK_200, res->status);
  15910. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15911. }
  15912. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15913. Client cli("https://yahoo.com");
  15914. auto res = cli.Get("/");
  15915. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15916. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15917. cli.set_follow_location(true);
  15918. res = cli.Get("/");
  15919. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15920. EXPECT_EQ(StatusCode::OK_200, res->status);
  15921. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15922. }
  15923. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15924. Client cli("https://yahoo.com");
  15925. auto res = cli.Get("/");
  15926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15927. ASSERT_FALSE(!res);
  15928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15929. ASSERT_FALSE(res == nullptr);
  15930. ASSERT_TRUE(res != nullptr);
  15931. EXPECT_EQ(Error::Success, res.error());
  15932. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15933. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15934. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15935. cli.set_follow_location(true);
  15936. res = cli.Get("/");
  15937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15938. EXPECT_EQ(Error::Success, res.error());
  15939. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15940. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15941. EXPECT_EQ(StatusCode::OK_200, res->status);
  15942. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15943. }
  15944. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15945. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15946. Client cli("https://cdnjs.cloudflare.com");
  15947. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15948. Headers{{"Accept-Encoding", "br"}});
  15949. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15950. EXPECT_EQ(StatusCode::OK_200, res->status);
  15951. EXPECT_EQ(287630U, res->body.size());
  15952. EXPECT_EQ("application/javascript; charset=utf-8",
  15953. res->get_header_value("Content-Type"));
  15954. }
  15955. #endif
  15956. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15957. #undef REDIR_HOST // Silence compiler warning
  15958. #define REDIR_HOST "https://httpbingo.org"
  15959. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15960. Client cli(REDIR_HOST);
  15961. cli.set_follow_location(true);
  15962. auto res = retry_service_failures([&] {
  15963. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15964. });
  15965. SKIP_ON_SERVICE_FAILURE(res);
  15966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15967. EXPECT_EQ(StatusCode::OK_200, res->status);
  15968. }
  15969. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15970. Client cli(REDIR_HOST);
  15971. cli.set_follow_location(true);
  15972. Params params;
  15973. params.emplace("url", "http://example.com");
  15974. params.emplace("status_code", "302");
  15975. auto res = retry_service_failures(
  15976. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15977. SKIP_ON_SERVICE_FAILURE(res);
  15978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15979. EXPECT_EQ(StatusCode::OK_200, res->status);
  15980. }
  15981. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15982. Client cli(REDIR_HOST);
  15983. cli.set_follow_location(true);
  15984. Params params;
  15985. params.emplace("url", "http://example.com");
  15986. auto res = retry_service_failures([&] {
  15987. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15988. });
  15989. SKIP_ON_SERVICE_FAILURE(res);
  15990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15991. EXPECT_EQ(StatusCode::OK_200, res->status);
  15992. }
  15993. TEST(HttpToHttpsRedirectTest, CertFile) {
  15994. auto ssl_port = PORT + 1;
  15995. Server svr;
  15996. ASSERT_TRUE(svr.is_valid());
  15997. svr.Get("/index", [&](const Request &, Response &res) {
  15998. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15999. "/index");
  16000. svr.stop();
  16001. });
  16002. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16003. ASSERT_TRUE(ssl_svr.is_valid());
  16004. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  16005. res.set_content("test", "text/plain");
  16006. ssl_svr.stop();
  16007. });
  16008. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16009. thread t2 =
  16010. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  16011. auto se = detail::scope_exit([&] {
  16012. t2.join();
  16013. t.join();
  16014. ASSERT_FALSE(svr.is_running());
  16015. });
  16016. svr.wait_until_ready();
  16017. ssl_svr.wait_until_ready();
  16018. Client cli("127.0.0.1", PORT);
  16019. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16020. cli.enable_server_certificate_verification(true);
  16021. cli.set_follow_location(true);
  16022. cli.set_connection_timeout(30);
  16023. auto res = cli.Get("/index");
  16024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16025. ASSERT_EQ(StatusCode::OK_200, res->status);
  16026. }
  16027. TEST(UppercaseSchemeTest, UsesTLS) {
  16028. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16029. ASSERT_TRUE(ssl_svr.is_valid());
  16030. ssl_svr.Get("/index", [](const Request &, Response &res) {
  16031. res.set_content("test", "text/plain");
  16032. });
  16033. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  16034. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  16035. Server svr;
  16036. svr.Get("/index", [&](const Request &, Response &res) {
  16037. res.set_redirect(https_url + "/index");
  16038. });
  16039. auto port = svr.bind_to_any_port("127.0.0.1");
  16040. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  16041. auto t2 = thread([&] { svr.listen_after_bind(); });
  16042. auto se = detail::scope_exit([&] {
  16043. svr.stop();
  16044. ssl_svr.stop();
  16045. t2.join();
  16046. t.join();
  16047. });
  16048. ssl_svr.wait_until_ready();
  16049. svr.wait_until_ready();
  16050. {
  16051. Client cli(https_url);
  16052. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16053. auto res = cli.Get("/index");
  16054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16055. EXPECT_EQ("test", res->body);
  16056. }
  16057. {
  16058. Client cli("127.0.0.1", port);
  16059. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16060. cli.set_follow_location(true);
  16061. auto res = cli.Get("/index");
  16062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16063. EXPECT_EQ("test", res->body);
  16064. }
  16065. }
  16066. TEST(SSLClientRedirectTest, CertFile) {
  16067. auto ssl_port = PORT + 1;
  16068. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16069. ASSERT_TRUE(ssl_svr1.is_valid());
  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. ssl_svr1.stop();
  16074. });
  16075. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16076. ASSERT_TRUE(ssl_svr2.is_valid());
  16077. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16078. res.set_content("test", "text/plain");
  16079. ssl_svr2.stop();
  16080. });
  16081. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16082. thread t2 =
  16083. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16084. auto se = detail::scope_exit([&] {
  16085. t2.join();
  16086. t.join();
  16087. ASSERT_FALSE(ssl_svr1.is_running());
  16088. });
  16089. ssl_svr1.wait_until_ready();
  16090. ssl_svr2.wait_until_ready();
  16091. SSLClient cli("127.0.0.1", PORT);
  16092. std::string cert;
  16093. read_file(SERVER_CERT2_FILE, cert);
  16094. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16095. cli.enable_server_certificate_verification(true);
  16096. cli.set_follow_location(true);
  16097. cli.set_connection_timeout(30);
  16098. auto res = cli.Get("/index");
  16099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16100. ASSERT_EQ(StatusCode::OK_200, res->status);
  16101. }
  16102. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16103. // another port, so the client follows it with a new client.
  16104. static Result GetThroughTlsRedirectToDifferentPort(
  16105. const std::function<void(SSLClient &)> &setup,
  16106. const char *target_cert = SERVER_CERT2_FILE,
  16107. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16108. auto ssl_port = PORT + 1;
  16109. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16110. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16111. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16112. "/index");
  16113. });
  16114. SSLServer ssl_svr2(target_cert, target_key);
  16115. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16116. res.set_content("test", "text/plain");
  16117. });
  16118. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16119. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16120. auto se = detail::scope_exit([&] {
  16121. ssl_svr2.stop();
  16122. ssl_svr1.stop();
  16123. t2.join();
  16124. t.join();
  16125. });
  16126. ssl_svr1.wait_until_ready();
  16127. ssl_svr2.wait_until_ready();
  16128. SSLClient cli("127.0.0.1", PORT);
  16129. cli.set_follow_location(true);
  16130. cli.set_connection_timeout(30);
  16131. setup(cli);
  16132. return cli.Get("/index");
  16133. }
  16134. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16135. auto calls = 0;
  16136. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16137. cli.enable_server_certificate_verification(false);
  16138. // Accept the first server only.
  16139. cli.set_session_verifier([&](tls::session_t) {
  16140. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16141. : SSLVerifierResponse::CertificateRejected;
  16142. });
  16143. });
  16144. ASSERT_FALSE(res);
  16145. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16146. EXPECT_EQ(2, calls);
  16147. }
  16148. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16149. std::string pinned;
  16150. auto res = GetThroughTlsRedirectToDifferentPort(
  16151. [&](SSLClient &cli) {
  16152. cli.enable_server_certificate_verification(false);
  16153. // Pin the first certificate seen.
  16154. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16155. if (pinned.empty()) { pinned = ctx.serial(); }
  16156. return ctx.serial() == pinned;
  16157. });
  16158. },
  16159. // A certificate other than the first server's.
  16160. SERVER_CERT_FILE);
  16161. EXPECT_FALSE(res);
  16162. EXPECT_FALSE(pinned.empty());
  16163. }
  16164. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16165. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16166. std::string cert;
  16167. read_file(SERVER_CERT2_FILE, cert);
  16168. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16169. });
  16170. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16171. EXPECT_EQ(StatusCode::OK_200, res->status);
  16172. }
  16173. // The target's certificate is signed by the root CA, which the first server's
  16174. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16175. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16176. auto res = GetThroughTlsRedirectToDifferentPort(
  16177. [](SSLClient &cli) {
  16178. std::string root_ca, cert;
  16179. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16180. read_file(SERVER_CERT2_FILE, cert);
  16181. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16182. cli.load_ca_cert_store(cert.data(), cert.size());
  16183. cli.enable_server_hostname_verification(false);
  16184. },
  16185. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16187. EXPECT_EQ(StatusCode::OK_200, res->status);
  16188. }
  16189. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16190. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16191. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16192. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16193. auto res = GetThroughTlsRedirectToDifferentPort(
  16194. [](SSLClient &cli) {
  16195. std::string root_ca, cert;
  16196. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16197. read_file(SERVER_CERT2_FILE, cert);
  16198. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16199. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16200. cli.enable_server_hostname_verification(false);
  16201. },
  16202. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16203. ASSERT_FALSE(res);
  16204. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16205. }
  16206. #endif
  16207. #endif
  16208. #ifdef CPPHTTPLIB_SSL_ENABLED
  16209. // Test that set_ca_cert_store() skips system certs (consistent with
  16210. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16211. // should be trusted - system certs should NOT be loaded.
  16212. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16213. // Load a specific cert that is NOT a system CA cert
  16214. std::string cert;
  16215. read_file(SERVER_CERT2_FILE, cert);
  16216. SSLClient cli("google.com");
  16217. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16218. cli.enable_server_certificate_verification(true);
  16219. // This should FAIL because:
  16220. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16221. // 2. System certs should NOT be loaded when custom store is set
  16222. // If system certs WERE loaded, this would succeed
  16223. auto res = cli.Get("/");
  16224. ASSERT_FALSE(res);
  16225. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16226. }
  16227. // Same as above, but through the native store handle path. Regression test:
  16228. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16229. // merged system certs into the user-provided store.
  16230. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16231. std::string cert;
  16232. read_file(SERVER_CERT2_FILE, cert);
  16233. SSLClient cli("google.com");
  16234. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16235. cli.enable_server_certificate_verification(true);
  16236. auto res = cli.Get("/");
  16237. ASSERT_FALSE(res);
  16238. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16239. }
  16240. // A custom store set via the native handle must still verify a server whose
  16241. // cert it does contain.
  16242. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16243. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16244. ASSERT_TRUE(svr.is_valid());
  16245. svr.Get("/test", [&](const Request &, Response &res) {
  16246. res.set_content("test", "text/plain");
  16247. });
  16248. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16249. auto se = detail::scope_exit([&] {
  16250. svr.stop();
  16251. t.join();
  16252. ASSERT_FALSE(svr.is_running());
  16253. });
  16254. svr.wait_until_ready();
  16255. SSLClient cli("127.0.0.1", PORT);
  16256. std::string cert;
  16257. read_file(SERVER_CERT2_FILE, cert);
  16258. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16259. cli.enable_server_certificate_verification(true);
  16260. cli.set_connection_timeout(30);
  16261. auto res = cli.Get("/test");
  16262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16263. ASSERT_EQ(StatusCode::OK_200, res->status);
  16264. }
  16265. // CA certs loaded through the universal Client must be transferred to the
  16266. // client created internally for following an HTTPS redirect. Regression test:
  16267. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16268. // the CA data for redirect transfer.
  16269. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16270. auto ssl_port = PORT + 1;
  16271. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16272. ASSERT_TRUE(ssl_svr1.is_valid());
  16273. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16274. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16275. "/index");
  16276. });
  16277. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16278. ASSERT_TRUE(ssl_svr2.is_valid());
  16279. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16280. res.set_content("test", "text/plain");
  16281. });
  16282. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16283. thread t2 =
  16284. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16285. auto se = detail::scope_exit([&] {
  16286. ssl_svr2.stop();
  16287. ssl_svr1.stop();
  16288. t2.join();
  16289. t.join();
  16290. ASSERT_FALSE(ssl_svr1.is_running());
  16291. });
  16292. ssl_svr1.wait_until_ready();
  16293. ssl_svr2.wait_until_ready();
  16294. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16295. std::string cert;
  16296. read_file(SERVER_CERT2_FILE, cert);
  16297. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16298. cli.enable_server_certificate_verification(true);
  16299. cli.set_follow_location(true);
  16300. cli.set_connection_timeout(30);
  16301. auto res = cli.Get("/index");
  16302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16303. ASSERT_EQ(StatusCode::OK_200, res->status);
  16304. }
  16305. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16306. // so a host signed by a system CA verifies even though a custom CA is set
  16307. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16308. std::string cert;
  16309. read_file(SERVER_CERT2_FILE, cert);
  16310. SSLClient cli("google.com");
  16311. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16312. cli.enable_system_ca(true);
  16313. cli.enable_server_certificate_verification(true);
  16314. auto res = cli.Get("/");
  16315. // Any status: Google may redirect or rate-limit CI runners.
  16316. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16317. }
  16318. // The custom CA remains effective when combined with the system CA
  16319. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16320. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16321. ASSERT_TRUE(svr.is_valid());
  16322. svr.Get("/test", [&](const Request &, Response &res) {
  16323. res.set_content("test", "text/plain");
  16324. });
  16325. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16326. auto se = detail::scope_exit([&] {
  16327. svr.stop();
  16328. t.join();
  16329. ASSERT_FALSE(svr.is_running());
  16330. });
  16331. svr.wait_until_ready();
  16332. SSLClient cli("127.0.0.1", PORT);
  16333. std::string cert;
  16334. read_file(SERVER_CERT2_FILE, cert);
  16335. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16336. cli.enable_system_ca(true);
  16337. cli.enable_server_certificate_verification(true);
  16338. cli.set_connection_timeout(30);
  16339. auto res = cli.Get("/test");
  16340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16341. ASSERT_EQ(StatusCode::OK_200, res->status);
  16342. }
  16343. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16344. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16345. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16346. static CFDictionaryRef
  16347. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16348. const SecTrustSettingsResult *result) {
  16349. auto constraint =
  16350. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16351. &kCFTypeDictionaryValueCallBacks);
  16352. if (policy) {
  16353. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16354. }
  16355. if (policy_string) {
  16356. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16357. kCFStringEncodingUTF8);
  16358. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16359. CFRelease(str);
  16360. }
  16361. if (result) {
  16362. auto number_value = static_cast<SInt32>(*result);
  16363. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16364. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16365. CFRelease(number);
  16366. }
  16367. return constraint;
  16368. }
  16369. static SecTrustSettingsResult
  16370. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16371. auto trust_settings =
  16372. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16373. for (auto constraint : constraints) {
  16374. CFArrayAppendValue(trust_settings, constraint);
  16375. CFRelease(constraint);
  16376. }
  16377. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16378. CFRelease(trust_settings);
  16379. return result;
  16380. }
  16381. // The system CA loader takes a Keychain certificate as a trusted root only
  16382. // when its Trust Settings say so for SSL, not merely because it has some.
  16383. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16384. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16385. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16386. const auto deny = kSecTrustSettingsResultDeny;
  16387. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16388. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16389. auto x509_policy = SecPolicyCreateBasicX509();
  16390. // "Always Trust", which stores no constraint at all
  16391. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16392. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16393. ssl_trust_settings_result(
  16394. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16395. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16396. ssl_trust_settings_result(
  16397. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16398. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16399. ssl_trust_settings_result(
  16400. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16401. // "Never Trust", for everything or for SSL
  16402. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16403. ssl_trust_settings_result(
  16404. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16405. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16406. ssl_trust_settings_result(
  16407. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16408. // Trusted for another policy, for one host, or not at all
  16409. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16410. ssl_trust_settings_result(
  16411. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16412. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16413. ssl_trust_settings_result({make_usage_constraint(
  16414. ssl_policy, "www.example.com", &trust_root)}));
  16415. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16416. ssl_trust_settings_result(
  16417. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16418. // The first constraint that applies to SSL decides
  16419. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16420. ssl_trust_settings_result(
  16421. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16422. make_usage_constraint(nullptr, nullptr, &deny)}));
  16423. CFRelease(x509_policy);
  16424. CFRelease(ssl_policy);
  16425. }
  16426. #endif
  16427. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16428. // skip chain verification entirely (only the certificate identity was
  16429. // checked), so a server presenting an untrusted certificate with a matching
  16430. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16431. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16432. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16433. ASSERT_TRUE(svr.is_valid());
  16434. svr.Get("/test", [&](const Request &, Response &res) {
  16435. res.set_content("test", "text/plain");
  16436. });
  16437. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16438. auto se = detail::scope_exit([&] {
  16439. svr.stop();
  16440. t.join();
  16441. ASSERT_FALSE(svr.is_running());
  16442. });
  16443. svr.wait_until_ready();
  16444. SSLClient cli("127.0.0.1", PORT);
  16445. std::string cert;
  16446. // A trusted CA that did not sign the server certificate. The server cert
  16447. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16448. // this connection.
  16449. read_file(CLIENT_CA_CERT_FILE, cert);
  16450. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16451. cli.enable_server_certificate_verification(true);
  16452. cli.set_connection_timeout(30);
  16453. auto res = cli.Get("/test");
  16454. ASSERT_FALSE(res);
  16455. }
  16456. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16457. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16458. // CA that failed to come through fails verification instead of trusting them.
  16459. // (wolfSSL does not list the system CAs it loaded.)
  16460. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16461. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16462. ASSERT_TRUE(svr.is_valid());
  16463. auto port = svr.bind_to_any_port("127.0.0.1");
  16464. ASSERT_LT(0, port);
  16465. thread t = thread([&] { svr.listen_after_bind(); });
  16466. auto se = detail::scope_exit([&] {
  16467. svr.stop();
  16468. t.join();
  16469. ASSERT_FALSE(svr.is_running());
  16470. });
  16471. svr.wait_until_ready();
  16472. // The CAs a client trusts once its first request has loaded them
  16473. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16474. Client cli("https://127.0.0.1:" + std::to_string(port));
  16475. setup(cli);
  16476. cli.Get("/");
  16477. return tls::get_ca_names(cli.tls_context()).size();
  16478. };
  16479. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16480. EXPECT_EQ(0u,
  16481. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16482. }
  16483. #endif
  16484. // A TLS setting changed between requests applies to the next one, not just to
  16485. // the next connection
  16486. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16487. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16488. ASSERT_TRUE(svr.is_valid());
  16489. svr.Get("/", [](const Request &req, Response &res) {
  16490. res.set_content(std::to_string(req.remote_port), "text/plain");
  16491. });
  16492. auto port = svr.bind_to_any_port("127.0.0.1");
  16493. ASSERT_LT(0, port);
  16494. thread t = thread([&] { svr.listen_after_bind(); });
  16495. auto se = detail::scope_exit([&] {
  16496. svr.stop();
  16497. t.join();
  16498. ASSERT_FALSE(svr.is_running());
  16499. });
  16500. svr.wait_until_ready();
  16501. SSLClient cli("127.0.0.1", port);
  16502. cli.set_keep_alive(true);
  16503. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16504. cli.enable_server_certificate_verification(false);
  16505. // The port the request went out from, so a new one means a new connection
  16506. auto client_port = [&] {
  16507. auto res = cli.Get("/");
  16508. return res ? res->body : std::string();
  16509. };
  16510. auto last = client_port();
  16511. ASSERT_FALSE(last.empty());
  16512. // Setting a value it already has keeps the connection
  16513. cli.enable_server_certificate_verification(false);
  16514. cli.enable_server_hostname_verification(true);
  16515. EXPECT_EQ(last, client_port());
  16516. cli.enable_server_certificate_verification(true);
  16517. auto res = cli.Get("/");
  16518. EXPECT_FALSE(res);
  16519. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16520. std::string ca;
  16521. read_file(SERVER_CERT2_FILE, ca);
  16522. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16523. last = client_port();
  16524. ASSERT_FALSE(last.empty());
  16525. std::vector<std::function<void()>> setters = {
  16526. [&] { cli.enable_server_hostname_verification(false); },
  16527. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16528. [&] {
  16529. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16530. },
  16531. [&] {
  16532. cli.set_server_certificate_verifier(
  16533. [](const tls::VerifyContext &) { return true; });
  16534. },
  16535. [&] {
  16536. cli.set_session_verifier(
  16537. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16538. },
  16539. };
  16540. for (const auto &setter : setters) {
  16541. setter();
  16542. auto next = client_port();
  16543. ASSERT_FALSE(next.empty());
  16544. EXPECT_NE(last, next);
  16545. last = next;
  16546. }
  16547. cli.set_session_verifier(
  16548. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16549. auto handle = cli.open_stream("GET", "/");
  16550. EXPECT_FALSE(handle.is_valid());
  16551. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16552. }
  16553. // A PEM given to create_ca_store() needs no NUL after it
  16554. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16555. std::string pem;
  16556. read_file(SERVER_CERT2_FILE, pem);
  16557. auto buf = pem + "X";
  16558. auto store = tls::create_ca_store(buf.data(), pem.size());
  16559. EXPECT_TRUE(store != nullptr);
  16560. SSLClient cli("localhost");
  16561. cli.set_ca_cert_store(store);
  16562. }
  16563. // enable_system_ca(false) prevents system CA loading entirely
  16564. TEST(SSLClientTest, DisableSystemCa_Online) {
  16565. SSLClient cli("google.com");
  16566. cli.enable_system_ca(false);
  16567. cli.enable_server_certificate_verification(true);
  16568. auto res = cli.Get("/");
  16569. ASSERT_FALSE(res);
  16570. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16571. // itself when the CA chain is empty
  16572. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16573. res.error() == Error::SSLConnection);
  16574. }
  16575. // The universal Client forwards enable_system_ca()
  16576. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16577. std::string cert;
  16578. read_file(SERVER_CERT2_FILE, cert);
  16579. Client cli("https://google.com");
  16580. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16581. cli.enable_system_ca(true);
  16582. cli.enable_server_certificate_verification(true);
  16583. auto res = cli.Get("/");
  16584. // Any status: Google may redirect or rate-limit CI runners.
  16585. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16586. }
  16587. // The system CA policy must carry over to the client created internally for
  16588. // following a cross-host HTTPS redirect
  16589. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16590. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16591. ASSERT_TRUE(svr.is_valid());
  16592. svr.Get("/index", [&](const Request &, Response &res) {
  16593. res.set_redirect("https://www.google.com/");
  16594. });
  16595. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16596. auto se = detail::scope_exit([&] {
  16597. svr.stop();
  16598. t.join();
  16599. ASSERT_FALSE(svr.is_running());
  16600. });
  16601. svr.wait_until_ready();
  16602. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16603. std::string cert;
  16604. read_file(SERVER_CERT2_FILE, cert);
  16605. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16606. cli.enable_system_ca(true);
  16607. cli.enable_server_certificate_verification(true);
  16608. cli.set_follow_location(true);
  16609. cli.set_connection_timeout(30);
  16610. // Receiving any response proves the redirect client completed the TLS
  16611. // handshake with a system-CA-signed host
  16612. auto res = cli.Get("/index");
  16613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16614. }
  16615. TEST(MultipartFormDataTest, LargeData) {
  16616. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16617. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16618. const ContentReader &content_reader) {
  16619. if (req.is_multipart_form_data()) {
  16620. std::vector<FormData> items;
  16621. content_reader(
  16622. [&](const FormData &file) {
  16623. items.push_back(file);
  16624. return true;
  16625. },
  16626. [&](const char *data, size_t data_length) {
  16627. items.back().content.append(data, data_length);
  16628. return true;
  16629. });
  16630. EXPECT_TRUE(std::string(items[0].name) == "document");
  16631. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16632. EXPECT_TRUE(items[0].filename == "2MB_data");
  16633. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16634. EXPECT_TRUE(items[1].name == "hello");
  16635. EXPECT_TRUE(items[1].content == "world");
  16636. EXPECT_TRUE(items[1].filename == "");
  16637. EXPECT_TRUE(items[1].content_type == "");
  16638. } else {
  16639. std::string body;
  16640. content_reader([&](const char *data, size_t data_length) {
  16641. body.append(data, data_length);
  16642. return true;
  16643. });
  16644. }
  16645. });
  16646. auto port = svr.bind_to_any_port(HOST);
  16647. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16648. auto se = detail::scope_exit([&] {
  16649. svr.stop();
  16650. t.join();
  16651. ASSERT_FALSE(svr.is_running());
  16652. });
  16653. svr.wait_until_ready();
  16654. {
  16655. std::string data(1024 * 1024 * 2, '.');
  16656. std::stringstream buffer;
  16657. buffer << data;
  16658. SSLClient cli(HOST, port);
  16659. cli.enable_server_certificate_verification(false);
  16660. UploadFormDataItems items{
  16661. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16662. {"hello", "world", "", ""},
  16663. };
  16664. auto res = cli.Post("/post", items);
  16665. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16666. ASSERT_EQ(StatusCode::OK_200, res->status);
  16667. }
  16668. }
  16669. TEST(MultipartFormDataTest, DataProviderItems) {
  16670. std::random_device seed_gen;
  16671. std::mt19937 random(seed_gen());
  16672. std::string rand1;
  16673. rand1.resize(1000);
  16674. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16675. std::string rand2;
  16676. rand2.resize(3000);
  16677. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16678. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16679. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16680. const ContentReader &content_reader) {
  16681. ASSERT_FALSE(req.is_multipart_form_data());
  16682. std::string body;
  16683. content_reader([&](const char *data, size_t data_length) {
  16684. body.append(data, data_length);
  16685. return true;
  16686. });
  16687. EXPECT_EQ(body, "");
  16688. });
  16689. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16690. const ContentReader &content_reader) {
  16691. ASSERT_TRUE(req.is_multipart_form_data());
  16692. std::vector<FormData> items;
  16693. content_reader(
  16694. [&](const FormData &file) {
  16695. items.push_back(file);
  16696. return true;
  16697. },
  16698. [&](const char *data, size_t data_length) {
  16699. items.back().content.append(data, data_length);
  16700. return true;
  16701. });
  16702. ASSERT_TRUE(items.size() == 2);
  16703. EXPECT_EQ(std::string(items[0].name), "name1");
  16704. EXPECT_EQ(items[0].content, "Testing123");
  16705. EXPECT_EQ(items[0].filename, "filename1");
  16706. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16707. EXPECT_EQ(items[1].name, "name2");
  16708. EXPECT_EQ(items[1].content, "Testing456");
  16709. EXPECT_EQ(items[1].filename, "");
  16710. EXPECT_EQ(items[1].content_type, "");
  16711. });
  16712. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16713. const ContentReader &content_reader) {
  16714. ASSERT_TRUE(req.is_multipart_form_data());
  16715. std::vector<FormData> items;
  16716. content_reader(
  16717. [&](const FormData &file) {
  16718. items.push_back(file);
  16719. return true;
  16720. },
  16721. [&](const char *data, size_t data_length) {
  16722. items.back().content.append(data, data_length);
  16723. return true;
  16724. });
  16725. ASSERT_TRUE(items.size() == 2);
  16726. EXPECT_EQ(items[0].name, "name3");
  16727. EXPECT_EQ(items[0].content, rand1);
  16728. EXPECT_EQ(items[0].filename, "filename3");
  16729. EXPECT_EQ(items[0].content_type, "");
  16730. EXPECT_EQ(items[1].name, "name4");
  16731. EXPECT_EQ(items[1].content, rand2);
  16732. EXPECT_EQ(items[1].filename, "filename4");
  16733. EXPECT_EQ(items[1].content_type, "");
  16734. });
  16735. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16736. const ContentReader &content_reader) {
  16737. ASSERT_TRUE(req.is_multipart_form_data());
  16738. std::vector<FormData> items;
  16739. content_reader(
  16740. [&](const FormData &file) {
  16741. items.push_back(file);
  16742. return true;
  16743. },
  16744. [&](const char *data, size_t data_length) {
  16745. items.back().content.append(data, data_length);
  16746. return true;
  16747. });
  16748. ASSERT_TRUE(items.size() == 4);
  16749. EXPECT_EQ(std::string(items[0].name), "name1");
  16750. EXPECT_EQ(items[0].content, "Testing123");
  16751. EXPECT_EQ(items[0].filename, "filename1");
  16752. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16753. EXPECT_EQ(items[1].name, "name2");
  16754. EXPECT_EQ(items[1].content, "Testing456");
  16755. EXPECT_EQ(items[1].filename, "");
  16756. EXPECT_EQ(items[1].content_type, "");
  16757. EXPECT_EQ(items[2].name, "name3");
  16758. EXPECT_EQ(items[2].content, rand1);
  16759. EXPECT_EQ(items[2].filename, "filename3");
  16760. EXPECT_EQ(items[2].content_type, "");
  16761. EXPECT_EQ(items[3].name, "name4");
  16762. EXPECT_EQ(items[3].content, rand2);
  16763. EXPECT_EQ(items[3].filename, "filename4");
  16764. EXPECT_EQ(items[3].content_type, "");
  16765. });
  16766. auto port = svr.bind_to_any_port("localhost");
  16767. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16768. auto se = detail::scope_exit([&] {
  16769. svr.stop();
  16770. t.join();
  16771. ASSERT_FALSE(svr.is_running());
  16772. });
  16773. svr.wait_until_ready();
  16774. {
  16775. SSLClient cli("localhost", port);
  16776. cli.enable_server_certificate_verification(false);
  16777. UploadFormDataItems items{
  16778. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16779. {"name2", "Testing456", "", ""}, // not a file
  16780. };
  16781. {
  16782. auto res = cli.Post("/post-none", {}, {}, {});
  16783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16784. ASSERT_EQ(StatusCode::OK_200, res->status);
  16785. }
  16786. FormDataProviderItems providers;
  16787. {
  16788. auto res =
  16789. cli.Post("/post-items", {}, items, providers); // empty providers
  16790. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16791. ASSERT_EQ(StatusCode::OK_200, res->status);
  16792. }
  16793. providers.push_back({"name3",
  16794. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16795. // test the offset is given correctly at each step
  16796. if (!offset)
  16797. sink.os.write(rand1.data(), 30);
  16798. else if (offset == 30)
  16799. sink.os.write(rand1.data() + 30, 300);
  16800. else if (offset == 330)
  16801. sink.os.write(rand1.data() + 330, 670);
  16802. else if (offset == rand1.size())
  16803. sink.done();
  16804. return true;
  16805. },
  16806. "filename3",
  16807. {}});
  16808. providers.push_back({"name4",
  16809. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16810. // test the offset is given correctly at each step
  16811. if (!offset)
  16812. sink.os.write(rand2.data(), 2000);
  16813. else if (offset == 2000)
  16814. sink.os.write(rand2.data() + 2000, 1);
  16815. else if (offset == 2001)
  16816. sink.os.write(rand2.data() + 2001, 999);
  16817. else if (offset == rand2.size())
  16818. sink.done();
  16819. return true;
  16820. },
  16821. "filename4",
  16822. {}});
  16823. {
  16824. auto res = cli.Post("/post-providers", {}, {}, providers);
  16825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16826. ASSERT_EQ(StatusCode::OK_200, res->status);
  16827. }
  16828. {
  16829. auto res = cli.Post("/post-both", {}, items, providers);
  16830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16831. ASSERT_EQ(StatusCode::OK_200, res->status);
  16832. }
  16833. }
  16834. }
  16835. TEST(MultipartFormDataTest, BadHeader) {
  16836. Server svr;
  16837. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16838. res.set_content("ok", "text/plain");
  16839. });
  16840. thread t = thread([&] { svr.listen(HOST, PORT); });
  16841. auto se = detail::scope_exit([&] {
  16842. svr.stop();
  16843. t.join();
  16844. ASSERT_FALSE(svr.is_running());
  16845. });
  16846. svr.wait_until_ready();
  16847. const std::string body =
  16848. "This is the preamble. It is to be ignored, though it\r\n"
  16849. "is a handy place for composition agents to include an\r\n"
  16850. "explanatory note to non-MIME conformant readers.\r\n"
  16851. "\r\n"
  16852. "\r\n"
  16853. "--simple boundary\r\n"
  16854. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16855. ": BAD...\r\n"
  16856. "\r\n"
  16857. "value1\r\n"
  16858. "--simple boundary\r\n"
  16859. "Content-Disposition: form-data; name=\"field2\"; "
  16860. "filename=\"example.txt\"\r\n"
  16861. "\r\n"
  16862. "value2\r\n"
  16863. "--simple boundary--\r\n"
  16864. "This is the epilogue. It is also to be ignored.\r\n";
  16865. std::string content_type =
  16866. R"(multipart/form-data; boundary="simple boundary")";
  16867. Client cli(HOST, PORT);
  16868. auto res = cli.Post("/post", body, content_type.c_str());
  16869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16870. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16871. }
  16872. TEST(MultipartFormDataTest, WithPreamble) {
  16873. Server svr;
  16874. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16875. res.set_content("ok", "text/plain");
  16876. });
  16877. thread t = thread([&] { svr.listen(HOST, PORT); });
  16878. auto se = detail::scope_exit([&] {
  16879. svr.stop();
  16880. t.join();
  16881. ASSERT_FALSE(svr.is_running());
  16882. });
  16883. svr.wait_until_ready();
  16884. const std::string body =
  16885. "This is the preamble. It is to be ignored, though it\r\n"
  16886. "is a handy place for composition agents to include an\r\n"
  16887. "explanatory note to non-MIME conformant readers.\r\n"
  16888. "\r\n"
  16889. "\r\n"
  16890. "--simple boundary\r\n"
  16891. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16892. "\r\n"
  16893. "value1\r\n"
  16894. "--simple boundary\r\n"
  16895. "Content-Disposition: form-data; name=\"field2\"; "
  16896. "filename=\"example.txt\"\r\n"
  16897. "\r\n"
  16898. "value2\r\n"
  16899. "--simple boundary--\r\n"
  16900. "This is the epilogue. It is also to be ignored.\r\n";
  16901. std::string content_type =
  16902. R"(multipart/form-data; boundary="simple boundary")";
  16903. Client cli(HOST, PORT);
  16904. auto res = cli.Post("/post", body, content_type.c_str());
  16905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16906. EXPECT_EQ(StatusCode::OK_200, res->status);
  16907. }
  16908. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16909. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16910. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16911. const ContentReader &content_reader) {
  16912. if (req.is_multipart_form_data()) {
  16913. std::vector<FormData> items;
  16914. content_reader(
  16915. [&](const FormData &file) {
  16916. items.push_back(file);
  16917. return true;
  16918. },
  16919. [&](const char *data, size_t data_length) {
  16920. items.back().content.append(data, data_length);
  16921. return true;
  16922. });
  16923. EXPECT_TRUE(std::string(items[0].name) == "document");
  16924. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16925. EXPECT_TRUE(items[0].filename == "2MB_data");
  16926. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16927. EXPECT_TRUE(items[1].name == "hello");
  16928. EXPECT_TRUE(items[1].content == "world");
  16929. EXPECT_TRUE(items[1].filename == "");
  16930. EXPECT_TRUE(items[1].content_type == "");
  16931. } else {
  16932. std::string body;
  16933. content_reader([&](const char *data, size_t data_length) {
  16934. body.append(data, data_length);
  16935. return true;
  16936. });
  16937. }
  16938. });
  16939. auto port = svr.bind_to_any_port("localhost");
  16940. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16941. auto se = detail::scope_exit([&] {
  16942. svr.stop();
  16943. t.join();
  16944. ASSERT_FALSE(svr.is_running());
  16945. });
  16946. svr.wait_until_ready();
  16947. {
  16948. std::string data(1024 * 1024 * 2, '.');
  16949. std::stringstream buffer;
  16950. buffer << data;
  16951. SSLClient cli("localhost", port);
  16952. cli.enable_server_certificate_verification(false);
  16953. UploadFormDataItems items{
  16954. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16955. {"hello", "world", "", ""},
  16956. };
  16957. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16959. ASSERT_EQ(StatusCode::OK_200, res->status);
  16960. }
  16961. }
  16962. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16963. std::string data(1024 * 1024 * 2, '&');
  16964. std::stringstream buffer;
  16965. buffer << data;
  16966. Client cli("https://localhost:8080");
  16967. UploadFormDataItems items{
  16968. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16969. {"hello", "world", "", ""},
  16970. };
  16971. for (const char &c : " \t\r\n") {
  16972. auto res =
  16973. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16974. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16975. ASSERT_FALSE(res);
  16976. }
  16977. }
  16978. TEST(MultipartFormDataTest, PutFormData) {
  16979. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16980. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16981. const ContentReader &content_reader) {
  16982. if (req.is_multipart_form_data()) {
  16983. std::vector<FormData> items;
  16984. content_reader(
  16985. [&](const FormData &file) {
  16986. items.push_back(file);
  16987. return true;
  16988. },
  16989. [&](const char *data, size_t data_length) {
  16990. items.back().content.append(data, data_length);
  16991. return true;
  16992. });
  16993. EXPECT_TRUE(std::string(items[0].name) == "document");
  16994. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16995. EXPECT_TRUE(items[0].filename == "2MB_data");
  16996. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16997. EXPECT_TRUE(items[1].name == "hello");
  16998. EXPECT_TRUE(items[1].content == "world");
  16999. EXPECT_TRUE(items[1].filename == "");
  17000. EXPECT_TRUE(items[1].content_type == "");
  17001. } else {
  17002. std::string body;
  17003. content_reader([&](const char *data, size_t data_length) {
  17004. body.append(data, data_length);
  17005. return true;
  17006. });
  17007. }
  17008. });
  17009. auto port = svr.bind_to_any_port("localhost");
  17010. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17011. auto se = detail::scope_exit([&] {
  17012. svr.stop();
  17013. t.join();
  17014. ASSERT_FALSE(svr.is_running());
  17015. });
  17016. svr.wait_until_ready();
  17017. {
  17018. std::string data(1024 * 1024 * 2, '&');
  17019. std::stringstream buffer;
  17020. buffer << data;
  17021. SSLClient cli("localhost", port);
  17022. cli.enable_server_certificate_verification(false);
  17023. UploadFormDataItems items{
  17024. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17025. {"hello", "world", "", ""},
  17026. };
  17027. auto res = cli.Put("/put", items);
  17028. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17029. ASSERT_EQ(StatusCode::OK_200, res->status);
  17030. }
  17031. }
  17032. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  17033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17034. svr.Put("/put_customboundary",
  17035. [&](const Request &req, const Response & /*res*/,
  17036. const ContentReader &content_reader) {
  17037. if (req.is_multipart_form_data()) {
  17038. std::vector<FormData> items;
  17039. content_reader(
  17040. [&](const FormData &file) {
  17041. items.push_back(file);
  17042. return true;
  17043. },
  17044. [&](const char *data, size_t data_length) {
  17045. items.back().content.append(data, data_length);
  17046. return true;
  17047. });
  17048. EXPECT_TRUE(std::string(items[0].name) == "document");
  17049. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17050. EXPECT_TRUE(items[0].filename == "2MB_data");
  17051. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17052. EXPECT_TRUE(items[1].name == "hello");
  17053. EXPECT_TRUE(items[1].content == "world");
  17054. EXPECT_TRUE(items[1].filename == "");
  17055. EXPECT_TRUE(items[1].content_type == "");
  17056. } else {
  17057. std::string body;
  17058. content_reader([&](const char *data, size_t data_length) {
  17059. body.append(data, data_length);
  17060. return true;
  17061. });
  17062. }
  17063. });
  17064. auto port = svr.bind_to_any_port("localhost");
  17065. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17066. auto se = detail::scope_exit([&] {
  17067. svr.stop();
  17068. t.join();
  17069. ASSERT_FALSE(svr.is_running());
  17070. });
  17071. svr.wait_until_ready();
  17072. {
  17073. std::string data(1024 * 1024 * 2, '&');
  17074. std::stringstream buffer;
  17075. buffer << data;
  17076. SSLClient cli("localhost", port);
  17077. cli.enable_server_certificate_verification(false);
  17078. UploadFormDataItems items{
  17079. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17080. {"hello", "world", "", ""},
  17081. };
  17082. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17084. ASSERT_EQ(StatusCode::OK_200, res->status);
  17085. }
  17086. }
  17087. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17088. std::string data(1024 * 1024 * 2, '&');
  17089. std::stringstream buffer;
  17090. buffer << data;
  17091. Client cli("https://localhost:8080");
  17092. cli.enable_server_certificate_verification(false);
  17093. UploadFormDataItems items{
  17094. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17095. {"hello", "world", "", ""},
  17096. };
  17097. for (const char &c : " \t\r\n") {
  17098. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17099. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17100. ASSERT_FALSE(res);
  17101. }
  17102. }
  17103. TEST(MultipartFormDataTest, AlternateFilename) {
  17104. auto handled = false;
  17105. Server svr;
  17106. svr.Post("/test", [&](const Request &req, Response &res) {
  17107. ASSERT_EQ(2u, req.form.files.size());
  17108. ASSERT_EQ(1u, req.form.fields.size());
  17109. // Test files
  17110. const auto &file1 = req.form.get_file("file1");
  17111. ASSERT_EQ("file1", file1.name);
  17112. ASSERT_EQ("A.txt", file1.filename);
  17113. ASSERT_EQ("text/plain", file1.content_type);
  17114. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17115. const auto &file2 = req.form.get_file("file2");
  17116. ASSERT_EQ("file2", file2.name);
  17117. ASSERT_EQ("a.html", file2.filename);
  17118. ASSERT_EQ("text/html", file2.content_type);
  17119. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17120. file2.content);
  17121. // Test text field
  17122. const auto &text = req.form.get_field("text");
  17123. ASSERT_EQ("text default", text);
  17124. res.set_content("ok", "text/plain");
  17125. handled = true;
  17126. });
  17127. thread t = thread([&] { svr.listen(HOST, PORT); });
  17128. auto se = detail::scope_exit([&] {
  17129. svr.stop();
  17130. t.join();
  17131. ASSERT_FALSE(svr.is_running());
  17132. ASSERT_TRUE(handled);
  17133. });
  17134. svr.wait_until_ready();
  17135. auto req = "POST /test HTTP/1.1\r\n"
  17136. "Host: localhost\r\n"
  17137. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17138. "Content-Length: 399\r\n"
  17139. "\r\n"
  17140. "----------\r\n"
  17141. "Content-Disposition: form-data; name=\"text\"\r\n"
  17142. "\r\n"
  17143. "text default\r\n"
  17144. "----------\r\n"
  17145. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17146. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17147. "Content-Type: text/plain\r\n"
  17148. "\r\n"
  17149. "Content of a.txt.\r\n"
  17150. "\r\n"
  17151. "----------\r\n"
  17152. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17153. "\"a.html\"\r\n"
  17154. "Content-Type: text/html\r\n"
  17155. "\r\n"
  17156. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17157. "\r\n"
  17158. "------------\r\n";
  17159. ASSERT_TRUE(send_request(1, req));
  17160. }
  17161. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17162. auto handled = false;
  17163. Server svr;
  17164. svr.Post("/test", [&](const Request &req, Response &res) {
  17165. // Case-insensitive "utf-8''" prefix with a long value
  17166. const auto &file = req.form.get_file("file1");
  17167. ASSERT_EQ("file1", file.name);
  17168. // 8000 chars exercises both the Content-Disposition parser and the
  17169. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17170. // Prior to the fix, std::regex_match on this header would cause O(N)
  17171. // stack recursion in libstdc++, leading to SIGSEGV.
  17172. std::string expected_filename(8000, 'A');
  17173. ASSERT_EQ(expected_filename, file.filename);
  17174. res.set_content("ok", "text/plain");
  17175. handled = true;
  17176. });
  17177. thread t = thread([&] { svr.listen(HOST, PORT); });
  17178. auto se = detail::scope_exit([&] {
  17179. svr.stop();
  17180. t.join();
  17181. ASSERT_FALSE(svr.is_running());
  17182. ASSERT_TRUE(handled);
  17183. });
  17184. svr.wait_until_ready();
  17185. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17186. // Regression test for GHSA-qq6v-r583-3h69
  17187. std::string long_filename(8000, 'A');
  17188. std::string body = "----------\r\n"
  17189. "Content-Disposition: form-data; name=\"file1\"; "
  17190. "filename*=\"Utf-8''" +
  17191. long_filename +
  17192. "\"\r\n"
  17193. "\r\n"
  17194. "hello\r\n"
  17195. "------------\r\n";
  17196. auto req = "POST /test HTTP/1.1\r\n"
  17197. "Host: localhost\r\n"
  17198. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17199. "Content-Length: " +
  17200. std::to_string(body.size()) + "\r\n\r\n" + body;
  17201. ASSERT_TRUE(send_request(1, req));
  17202. }
  17203. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17204. auto handled = false;
  17205. Server svr;
  17206. svr.Post("/test", [&](const Request &req, Response &) {
  17207. ASSERT_EQ(2u, req.form.fields.size());
  17208. const auto &text1 = req.form.get_field("text1");
  17209. ASSERT_EQ("text1", text1);
  17210. const auto &text2 = req.form.get_field("text2");
  17211. ASSERT_EQ("text2", text2);
  17212. handled = true;
  17213. });
  17214. thread t = thread([&] { svr.listen(HOST, PORT); });
  17215. auto se = detail::scope_exit([&] {
  17216. svr.stop();
  17217. t.join();
  17218. ASSERT_FALSE(svr.is_running());
  17219. ASSERT_TRUE(handled);
  17220. });
  17221. svr.wait_until_ready();
  17222. auto req = "POST /test HTTP/1.1\r\n"
  17223. "Host: localhost\r\n"
  17224. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17225. "Content-Length: 146\r\n"
  17226. "\r\n----------\r\n"
  17227. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17228. "\r\n"
  17229. "text1"
  17230. "\r\n----------\r\n"
  17231. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17232. "\r\n"
  17233. "text2"
  17234. "\r\n------------";
  17235. std::string response;
  17236. ASSERT_TRUE(send_request(1, req, &response));
  17237. ASSERT_EQ("200", response.substr(9, 3));
  17238. }
  17239. TEST(MultipartFormDataTest, ContentLength) {
  17240. auto handled = false;
  17241. Server svr;
  17242. svr.Post("/test", [&](const Request &req, Response &) {
  17243. ASSERT_EQ(2u, req.form.fields.size());
  17244. const auto &text1 = req.form.get_field("text1");
  17245. ASSERT_EQ("text1", text1);
  17246. const auto &text2 = req.form.get_field("text2");
  17247. ASSERT_EQ("text2", text2);
  17248. handled = true;
  17249. });
  17250. thread t = thread([&] { svr.listen(HOST, PORT); });
  17251. auto se = detail::scope_exit([&] {
  17252. svr.stop();
  17253. t.join();
  17254. ASSERT_FALSE(svr.is_running());
  17255. ASSERT_TRUE(handled);
  17256. });
  17257. svr.wait_until_ready();
  17258. auto req = "POST /test HTTP/1.1\r\n"
  17259. "Host: localhost\r\n"
  17260. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17261. "Content-Length: 167\r\n"
  17262. "\r\n----------\r\n"
  17263. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17264. "Content-Length: 5\r\n"
  17265. "\r\n"
  17266. "text1"
  17267. "\r\n----------\r\n"
  17268. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17269. "\r\n"
  17270. "text2"
  17271. "\r\n------------\r\n";
  17272. std::string response;
  17273. ASSERT_TRUE(send_request(1, req, &response));
  17274. ASSERT_EQ("200", response.substr(9, 3));
  17275. }
  17276. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17277. auto handled = false;
  17278. Server svr;
  17279. svr.Post("/test", [&](const Request &req, Response &) {
  17280. ASSERT_EQ(2u, req.form.fields.size());
  17281. const auto &text1 = req.form.get_field("text1");
  17282. ASSERT_EQ("text1", text1);
  17283. // TODO: Add header access for text fields if needed
  17284. const auto &text2 = req.form.get_field("text2");
  17285. ASSERT_EQ("text2", text2);
  17286. // TODO: Header access for text fields needs to be implemented
  17287. // auto &headers = it->second.headers;
  17288. // ASSERT_EQ(3U, headers.size());
  17289. // auto custom_header = headers.find("x-whatever");
  17290. // ASSERT_TRUE(custom_header != headers.end());
  17291. // ASSERT_NE("customvalue", custom_header->second);
  17292. // ASSERT_EQ("CustomValue", custom_header->second);
  17293. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17294. handled = true;
  17295. });
  17296. thread t = thread([&] { svr.listen(HOST, PORT); });
  17297. auto se = detail::scope_exit([&] {
  17298. svr.stop();
  17299. t.join();
  17300. ASSERT_FALSE(svr.is_running());
  17301. ASSERT_TRUE(handled);
  17302. });
  17303. svr.wait_until_ready();
  17304. auto req = "POST /test HTTP/1.1\r\n"
  17305. "Host: localhost\r\n"
  17306. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17307. "Content-Length: 232\r\n"
  17308. "\r\n----------\r\n"
  17309. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17310. "Content-Length: 5\r\n"
  17311. "X-Test: 1\r\n"
  17312. "\r\n"
  17313. "text1"
  17314. "\r\n----------\r\n"
  17315. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17316. "Content-Type: text/plain\r\n"
  17317. "X-Whatever: CustomValue\r\n"
  17318. "\r\n"
  17319. "text2"
  17320. "\r\n------------\r\n"
  17321. "That should be disregarded. Not even read";
  17322. std::string response;
  17323. ASSERT_TRUE(send_request(1, req, &response));
  17324. ASSERT_EQ("200", response.substr(9, 3));
  17325. }
  17326. TEST(MultipartFormDataTest, LargeHeader) {
  17327. auto handled = false;
  17328. Server svr;
  17329. svr.Post("/test", [&](const Request &req, Response &) {
  17330. ASSERT_EQ(1u, req.form.fields.size());
  17331. const auto &text = req.form.get_field("name1");
  17332. ASSERT_EQ("text1", text);
  17333. handled = true;
  17334. });
  17335. thread t = thread([&] { svr.listen(HOST, PORT); });
  17336. auto se = detail::scope_exit([&] {
  17337. svr.stop();
  17338. t.join();
  17339. ASSERT_FALSE(svr.is_running());
  17340. ASSERT_TRUE(handled);
  17341. });
  17342. svr.wait_until_ready();
  17343. auto boundary = std::string("cpp-httplib-multipart-data");
  17344. std::string content = "--" + boundary +
  17345. "\r\n"
  17346. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17347. "\r\n"
  17348. "text1\r\n"
  17349. "--" +
  17350. boundary + "--\r\n";
  17351. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17352. "Host: localhost\r\n"
  17353. "Content-Type: multipart/form-data;boundary=" +
  17354. boundary +
  17355. "\r\n"
  17356. "Content-Length: " +
  17357. std::to_string(content.size()) +
  17358. "\r\n"
  17359. "Dummy-Header: ";
  17360. std::string header_suffix = "\r\n"
  17361. "\r\n";
  17362. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17363. size_t header_dummy_size =
  17364. read_buff_size -
  17365. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17366. auto header_dummy = std::string(header_dummy_size, '@');
  17367. auto req = header_prefix + header_dummy + header_suffix + content;
  17368. std::string response;
  17369. ASSERT_TRUE(send_request(1, req, &response));
  17370. ASSERT_EQ("200", response.substr(9, 3));
  17371. }
  17372. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17373. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17374. // (not chunked Transfer-Encoding) after the streaming refactor.
  17375. auto handled = false;
  17376. Server svr;
  17377. svr.Post("/upload", [&](const Request &req, Response &res) {
  17378. auto cl_it = req.headers.find("Content-Length");
  17379. EXPECT_TRUE(cl_it != req.headers.end());
  17380. auto te_it = req.headers.find("Transfer-Encoding");
  17381. EXPECT_TRUE(te_it == req.headers.end());
  17382. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17383. res.set_content("ok", "text/plain");
  17384. handled = true;
  17385. });
  17386. auto port = svr.bind_to_any_port(HOST);
  17387. auto t = thread([&] { svr.listen_after_bind(); });
  17388. auto se = detail::scope_exit([&] {
  17389. svr.stop();
  17390. t.join();
  17391. ASSERT_FALSE(svr.is_running());
  17392. ASSERT_TRUE(handled);
  17393. });
  17394. svr.wait_until_ready();
  17395. UploadFormDataItems items = {
  17396. {"field1", "hello", "", "text/plain"},
  17397. {"file1", "world", "test.txt", "application/octet-stream"},
  17398. };
  17399. Client cli(HOST, port);
  17400. auto res = cli.Post("/upload", {}, items);
  17401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17402. EXPECT_EQ(StatusCode::OK_200, res->status);
  17403. }
  17404. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17405. // Verify that make_multipart_content_provider coalesces many small segments
  17406. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17407. constexpr size_t kItemCount = 1000;
  17408. UploadFormDataItems items;
  17409. items.reserve(kItemCount);
  17410. for (size_t i = 0; i < kItemCount; i++) {
  17411. items.push_back(
  17412. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17413. }
  17414. const std::string boundary = "----test-boundary";
  17415. auto content_length = detail::get_multipart_content_length(items, boundary);
  17416. auto provider = detail::make_multipart_content_provider(items, boundary);
  17417. // Drive the provider the same way write_content_with_progress does
  17418. size_t write_count = 0;
  17419. size_t total_bytes = 0;
  17420. DataSink sink;
  17421. size_t offset = 0;
  17422. sink.write = [&](const char *d, size_t l) -> bool {
  17423. (void)d;
  17424. write_count++;
  17425. total_bytes += l;
  17426. offset += l;
  17427. return true;
  17428. };
  17429. sink.is_writable = []() -> bool { return true; };
  17430. while (offset < content_length) {
  17431. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17432. }
  17433. EXPECT_EQ(content_length, total_bytes);
  17434. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17435. // With buffering into 64KB blocks, write_count should be much smaller.
  17436. auto segment_count = 3 * kItemCount + 1;
  17437. EXPECT_LT(write_count, segment_count / 10);
  17438. }
  17439. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17440. // Integration test: send many UploadFormDataItems and verify the server
  17441. // receives all of them correctly (#2410).
  17442. constexpr size_t kItemCount = 500;
  17443. auto handled = false;
  17444. Server svr;
  17445. svr.Post("/upload", [&](const Request &req, Response &res) {
  17446. EXPECT_EQ(kItemCount, req.form.fields.size());
  17447. for (size_t i = 0; i < kItemCount; i++) {
  17448. auto key = "field" + std::to_string(i);
  17449. auto val = "value" + std::to_string(i);
  17450. auto it = req.form.fields.find(key);
  17451. if (it != req.form.fields.end()) {
  17452. EXPECT_EQ(val, it->second.content);
  17453. } else {
  17454. ADD_FAILURE() << "Missing field: " << key;
  17455. }
  17456. }
  17457. res.set_content("ok", "text/plain");
  17458. handled = true;
  17459. });
  17460. auto port = svr.bind_to_any_port(HOST);
  17461. auto t = thread([&] { svr.listen_after_bind(); });
  17462. auto se = detail::scope_exit([&] {
  17463. svr.stop();
  17464. t.join();
  17465. ASSERT_FALSE(svr.is_running());
  17466. ASSERT_TRUE(handled);
  17467. });
  17468. svr.wait_until_ready();
  17469. UploadFormDataItems items;
  17470. items.reserve(kItemCount);
  17471. for (size_t i = 0; i < kItemCount; i++) {
  17472. items.push_back(
  17473. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17474. }
  17475. Client cli(HOST, port);
  17476. auto res = cli.Post("/upload", items);
  17477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17478. EXPECT_EQ(StatusCode::OK_200, res->status);
  17479. }
  17480. TEST(MultipartFormDataTest, MakeFileProvider) {
  17481. // Verify make_file_provider sends a file's contents correctly.
  17482. const std::string file_content(4096, 'Z');
  17483. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17484. {
  17485. std::ofstream ofs(tmp_path, std::ios::binary);
  17486. ofs.write(file_content.data(),
  17487. static_cast<std::streamsize>(file_content.size()));
  17488. }
  17489. auto handled = false;
  17490. Server svr;
  17491. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17492. const ContentReader &content_reader) {
  17493. ASSERT_TRUE(req.is_multipart_form_data());
  17494. std::vector<FormData> items;
  17495. content_reader(
  17496. [&](const FormData &file) {
  17497. items.push_back(file);
  17498. return true;
  17499. },
  17500. [&](const char *data, size_t data_length) {
  17501. items.back().content.append(data, data_length);
  17502. return true;
  17503. });
  17504. ASSERT_EQ(1u, items.size());
  17505. EXPECT_EQ("myfile", items[0].name);
  17506. EXPECT_EQ("data.bin", items[0].filename);
  17507. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17508. EXPECT_EQ(file_content, items[0].content);
  17509. handled = true;
  17510. });
  17511. auto port = svr.bind_to_any_port(HOST);
  17512. auto t = thread([&] { svr.listen_after_bind(); });
  17513. auto se = detail::scope_exit([&] {
  17514. svr.stop();
  17515. t.join();
  17516. ASSERT_FALSE(svr.is_running());
  17517. ASSERT_TRUE(handled);
  17518. std::remove(tmp_path.c_str());
  17519. });
  17520. svr.wait_until_ready();
  17521. FormDataProviderItems providers;
  17522. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17523. "application/octet-stream"));
  17524. Client cli(HOST, port);
  17525. auto res = cli.Post("/upload", {}, {}, providers);
  17526. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17527. EXPECT_EQ(StatusCode::OK_200, res->status);
  17528. }
  17529. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17530. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17531. // (100) headers is rejected with a 400 Bad Request response.
  17532. Server svr;
  17533. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17534. res.set_content("ok", "text/plain");
  17535. });
  17536. thread t = thread([&] { svr.listen(HOST, PORT); });
  17537. auto se = detail::scope_exit([&] {
  17538. svr.stop();
  17539. t.join();
  17540. ASSERT_FALSE(svr.is_running());
  17541. });
  17542. svr.wait_until_ready();
  17543. // Build a multipart part with 101 custom headers (exceeding
  17544. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17545. std::stringstream body;
  17546. body << "--simpleboundary\r\n"
  17547. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17548. for (int i = 0; i < 101; i++) {
  17549. body << "X-Custom-Header-" << i << ": value\r\n";
  17550. }
  17551. body << "\r\n"
  17552. << "value1\r\n"
  17553. << "--simpleboundary--\r\n";
  17554. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17555. Client cli(HOST, PORT);
  17556. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17557. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17558. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17559. }
  17560. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17561. // A body that never contains the declared boundary must not be accumulated
  17562. // while the parser waits for it. Buffering it would also make every read
  17563. // rescan everything seen so far, which is quadratic in the body size.
  17564. Server svr;
  17565. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17566. res.set_content("ok", "text/plain");
  17567. });
  17568. auto port = svr.bind_to_any_port(HOST);
  17569. thread t = thread([&] { svr.listen_after_bind(); });
  17570. auto se = detail::scope_exit([&] {
  17571. svr.stop();
  17572. t.join();
  17573. ASSERT_FALSE(svr.is_running());
  17574. });
  17575. svr.wait_until_ready();
  17576. Client cli(HOST, port);
  17577. cli.set_read_timeout(60, 0);
  17578. cli.set_write_timeout(60, 0);
  17579. // '-' is the worst case: it matches the first character of the boundary, so
  17580. // every position has to be checked against it.
  17581. auto post_dashes = [&](size_t size) {
  17582. const std::string body(size, '-');
  17583. auto start = std::chrono::steady_clock::now();
  17584. auto res =
  17585. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17586. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17587. std::chrono::steady_clock::now() - start)
  17588. .count();
  17589. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17590. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17591. return ms;
  17592. };
  17593. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17594. // Windows.
  17595. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17596. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17597. // Comparing the two sizes rather than checking an absolute duration keeps
  17598. // this meaningful across build types and CI load, both of which move the
  17599. // absolute numbers by more than an order of magnitude. Four times the bytes
  17600. // costs about four times the time when parsing is linear, and about sixteen
  17601. // times when the body is buffered and rescanned.
  17602. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17603. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17604. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17605. << "ms, which suggests the body is being buffered and rescanned";
  17606. }
  17607. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17608. // A boundary can only be followed by CRLF or by "--", so anything else is
  17609. // malformed no matter what comes next. The parser must say so right away
  17610. // instead of buffering the rest of the declared body.
  17611. Server svr;
  17612. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17613. res.set_content("ok", "text/plain");
  17614. });
  17615. auto port = svr.bind_to_any_port(HOST);
  17616. thread t = thread([&] { svr.listen_after_bind(); });
  17617. auto se = detail::scope_exit([&] {
  17618. svr.stop();
  17619. t.join();
  17620. ASSERT_FALSE(svr.is_running());
  17621. });
  17622. svr.wait_until_ready();
  17623. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17624. // buffers instead of failing would still be waiting for the remaining bytes.
  17625. const std::string body = "--zzzz\r\n"
  17626. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17627. "\r\n"
  17628. "text1"
  17629. "\r\n--zzzzXX";
  17630. const std::string req = "POST /post HTTP/1.1\r\n"
  17631. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17632. "Content-Length: 1048576\r\n"
  17633. "\r\n" +
  17634. body;
  17635. std::string response;
  17636. ASSERT_TRUE(send_request(3, req, &response, port));
  17637. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17638. EXPECT_EQ("400", response.substr(9, 3));
  17639. }
  17640. // Posts a multipart body split into two writes, so that the server sees the
  17641. // split at whatever offset the caller chose, and expects the single "text1"
  17642. // field to come through.
  17643. static void expect_split_multipart_ok(const std::string &body1,
  17644. const std::string &body2) {
  17645. auto handled = false;
  17646. Server svr;
  17647. svr.Post("/post", [&](const Request &req, Response &) {
  17648. EXPECT_EQ(1u, req.form.fields.size());
  17649. EXPECT_EQ("text1", req.form.get_field("text1"));
  17650. handled = true;
  17651. });
  17652. auto port = svr.bind_to_any_port(HOST);
  17653. thread t = thread([&] { svr.listen_after_bind(); });
  17654. auto se = detail::scope_exit([&] {
  17655. svr.stop();
  17656. t.join();
  17657. ASSERT_FALSE(svr.is_running());
  17658. ASSERT_TRUE(handled);
  17659. });
  17660. svr.wait_until_ready();
  17661. // "Connection: close" makes the server close once it has answered, so the
  17662. // response drain ends immediately instead of idling until the read timeout.
  17663. const std::string head =
  17664. "POST /post HTTP/1.1\r\n"
  17665. "Host: localhost\r\n"
  17666. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17667. "Connection: close\r\n"
  17668. "Content-Length: " +
  17669. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17670. std::string response;
  17671. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17672. ASSERT_GE(response.size(), 12u) << "no response";
  17673. EXPECT_EQ("200", response.substr(9, 3));
  17674. }
  17675. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17676. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17677. // ignored, including when it does not arrive in the same read as the
  17678. // close-delimiter itself.
  17679. expect_split_multipart_ok("--zzzz\r\n"
  17680. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17681. "\r\n"
  17682. "text1"
  17683. "\r\n--zzzz--",
  17684. "\r\nthis epilogue must be ignored\r\n");
  17685. }
  17686. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17687. // The initial boundary may be preceded by a preamble of any length and may
  17688. // straddle a read boundary. Discarding data while waiting for it must not
  17689. // throw away a partial boundary sitting at the end of the buffer.
  17690. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17691. "zz\r\n"
  17692. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17693. "\r\n"
  17694. "text1"
  17695. "\r\n--zzzz--\r\n");
  17696. }
  17697. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17698. // The received boundary was only checked for being non-empty, so it could be
  17699. // as long as a header is allowed to be. The parser scans the body for
  17700. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17701. // costs a nearly full comparison at nearly every position, making the
  17702. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17703. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17704. Server svr;
  17705. svr.Post("/post", [](const Request &req, Response &res) {
  17706. EXPECT_EQ(1u, req.form.fields.size());
  17707. EXPECT_EQ("text1", req.form.get_field("text1"));
  17708. res.set_content("ok", "text/plain");
  17709. });
  17710. auto port = svr.bind_to_any_port(HOST);
  17711. thread t = thread([&] { svr.listen_after_bind(); });
  17712. auto se = detail::scope_exit([&] {
  17713. svr.stop();
  17714. t.join();
  17715. ASSERT_FALSE(svr.is_running());
  17716. });
  17717. svr.wait_until_ready();
  17718. Client cli(HOST, port);
  17719. auto post_with_boundary_of_length = [&](size_t len) {
  17720. const std::string boundary(len, 'a');
  17721. const std::string body =
  17722. "--" + boundary +
  17723. "\r\n"
  17724. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17725. "\r\n"
  17726. "text1"
  17727. "\r\n--" +
  17728. boundary + "--\r\n";
  17729. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17730. };
  17731. auto res = post_with_boundary_of_length(70);
  17732. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17733. EXPECT_EQ(StatusCode::OK_200, res->status);
  17734. res = post_with_boundary_of_length(71);
  17735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17736. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17737. }
  17738. TEST(MakeFileBodyTest, Basic) {
  17739. const std::string file_content(4096, 'Z');
  17740. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17741. {
  17742. std::ofstream ofs(tmp_path, std::ios::binary);
  17743. ofs.write(file_content.data(),
  17744. static_cast<std::streamsize>(file_content.size()));
  17745. }
  17746. auto handled = false;
  17747. Server svr;
  17748. svr.Post("/upload", [&](const Request &req, Response &res) {
  17749. EXPECT_EQ(file_content, req.body);
  17750. handled = true;
  17751. res.status = StatusCode::OK_200;
  17752. });
  17753. auto port = svr.bind_to_any_port(HOST);
  17754. auto t = thread([&] { svr.listen_after_bind(); });
  17755. auto se = detail::scope_exit([&] {
  17756. svr.stop();
  17757. t.join();
  17758. ASSERT_FALSE(svr.is_running());
  17759. ASSERT_TRUE(handled);
  17760. std::remove(tmp_path.c_str());
  17761. });
  17762. svr.wait_until_ready();
  17763. auto fb = make_file_body(tmp_path);
  17764. ASSERT_GT(fb.first, 0u);
  17765. Client cli(HOST, port);
  17766. auto res =
  17767. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17769. EXPECT_EQ(StatusCode::OK_200, res->status);
  17770. }
  17771. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17772. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17773. {
  17774. std::ofstream ofs(path, std::ios::binary);
  17775. const std::string content(100, 'A');
  17776. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17777. }
  17778. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17779. auto body = make_file_body(path);
  17780. ASSERT_EQ(100u, body.first);
  17781. ASSERT_TRUE(static_cast<bool>(body.second));
  17782. // Rewritten shorter after its length was measured - and, on a server, after
  17783. // that length has already gone out as Content-Length.
  17784. {
  17785. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17786. const std::string content(10, 'A');
  17787. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17788. }
  17789. std::string written;
  17790. DataSink sink;
  17791. sink.write = [&](const char *d, size_t l) {
  17792. written.append(d, l);
  17793. return true;
  17794. };
  17795. // The provider has to report failure. write_content_with_progress() advances
  17796. // its offset only by what was written, so a provider that returns true
  17797. // without completing the length it promised is called again straight away,
  17798. // and again.
  17799. EXPECT_FALSE(body.second(0, body.first, sink));
  17800. EXPECT_EQ(std::string(10, 'A'), written);
  17801. }
  17802. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17803. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17804. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17805. {
  17806. std::ofstream ofs(path, std::ios::binary);
  17807. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17808. }
  17809. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17810. auto body = make_file_body(path);
  17811. ASSERT_EQ(content.size(), body.first);
  17812. ASSERT_TRUE(static_cast<bool>(body.second));
  17813. std::string written;
  17814. DataSink sink;
  17815. sink.write = [&](const char *d, size_t l) {
  17816. written.append(d, l);
  17817. return true;
  17818. };
  17819. EXPECT_TRUE(body.second(0, body.first, sink));
  17820. EXPECT_EQ(content, written);
  17821. }
  17822. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17823. static constexpr unsigned int number_of_tasks{1000000};
  17824. std::atomic_uint count{0};
  17825. std::unique_ptr<TaskQueue> task_queue{
  17826. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17827. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17828. auto queued = task_queue->enqueue(
  17829. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17830. EXPECT_TRUE(queued);
  17831. }
  17832. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17833. task_queue->shutdown();
  17834. #else
  17835. EXPECT_NO_THROW(task_queue->shutdown());
  17836. #endif
  17837. EXPECT_EQ(number_of_tasks, count.load());
  17838. }
  17839. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17840. static constexpr unsigned int number_of_tasks{1000000};
  17841. static constexpr unsigned int qlimit{2};
  17842. unsigned int queued_count{0};
  17843. std::atomic_uint count{0};
  17844. std::unique_ptr<TaskQueue> task_queue{
  17845. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17846. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17847. if (task_queue->enqueue(
  17848. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17849. queued_count++;
  17850. }
  17851. }
  17852. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17853. task_queue->shutdown();
  17854. #else
  17855. EXPECT_NO_THROW(task_queue->shutdown());
  17856. #endif
  17857. EXPECT_EQ(queued_count, count.load());
  17858. EXPECT_TRUE(queued_count <= number_of_tasks);
  17859. EXPECT_TRUE(queued_count >= qlimit);
  17860. }
  17861. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17862. // Use a short idle timeout so a dynamic thread spawns, times out and
  17863. // exits during the test, and the pool keeps working afterwards.
  17864. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17865. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17866. /*idle_timeout_sec=*/1}};
  17867. std::atomic_uint count{0};
  17868. std::condition_variable cv;
  17869. std::mutex mtx;
  17870. bool release = false;
  17871. // Block the base thread so the second task spawns a dynamic thread.
  17872. EXPECT_TRUE(task_queue->enqueue([&] {
  17873. std::unique_lock<std::mutex> lock(mtx);
  17874. while (!release) {
  17875. cv.wait(lock);
  17876. }
  17877. count++;
  17878. }));
  17879. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17880. // Let the dynamic thread finish its task and exceed the idle timeout.
  17881. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17882. {
  17883. std::unique_lock<std::mutex> lock(mtx);
  17884. release = true;
  17885. }
  17886. cv.notify_all();
  17887. // The pool must still accept and run tasks after the dynamic thread exited.
  17888. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17889. task_queue->shutdown();
  17890. EXPECT_EQ(3u, count.load());
  17891. }
  17892. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17893. static constexpr size_t number_of_tasks{32};
  17894. std::unique_ptr<TaskQueue> task_queue{
  17895. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17896. // Let the base threads go idle so the burst below finds them waiting.
  17897. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17898. std::mutex mtx;
  17899. std::condition_variable cv;
  17900. size_t running = 0;
  17901. bool release = false;
  17902. for (size_t i = 0; i < number_of_tasks; i++) {
  17903. EXPECT_TRUE(task_queue->enqueue([&] {
  17904. std::unique_lock<std::mutex> lock(mtx);
  17905. running++;
  17906. cv.notify_all();
  17907. cv.wait(lock, [&] { return release; });
  17908. }));
  17909. }
  17910. {
  17911. std::unique_lock<std::mutex> lock(mtx);
  17912. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17913. [&] { return running == number_of_tasks; }));
  17914. release = true;
  17915. }
  17916. cv.notify_all();
  17917. task_queue->shutdown();
  17918. }
  17919. TEST(TaskQueueTest, MaxQueuedRequests) {
  17920. static constexpr unsigned int qlimit{3};
  17921. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17922. std::condition_variable sem_cv;
  17923. std::mutex sem_mtx;
  17924. int credits = 0;
  17925. bool queued;
  17926. /* Fill up the queue with tasks that will block until we give them credits to
  17927. * complete. */
  17928. for (unsigned int n = 0; n <= qlimit;) {
  17929. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17930. std::unique_lock<std::mutex> lock(sem_mtx);
  17931. while (credits <= 0) {
  17932. sem_cv.wait(lock);
  17933. }
  17934. /* Consume the credit and signal the test code if they are all gone. */
  17935. if (--credits == 0) { sem_cv.notify_one(); }
  17936. });
  17937. if (n < qlimit) {
  17938. /* The first qlimit enqueues must succeed. */
  17939. EXPECT_TRUE(queued);
  17940. } else {
  17941. /* The last one will succeed only when the worker thread
  17942. * starts and dequeues the first blocking task. Although
  17943. * not necessary for the correctness of this test, we sleep for
  17944. * a short while to avoid busy waiting. */
  17945. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17946. }
  17947. if (queued) { n++; }
  17948. }
  17949. /* Further enqueues must fail since the queue is full. */
  17950. for (auto i = 0; i < 4; i++) {
  17951. queued = task_queue->enqueue([] {});
  17952. EXPECT_FALSE(queued);
  17953. }
  17954. /* Give the credits to allow the previous tasks to complete. */
  17955. {
  17956. std::unique_lock<std::mutex> lock(sem_mtx);
  17957. credits += qlimit + 1;
  17958. }
  17959. sem_cv.notify_all();
  17960. /* Wait for all the credits to be consumed. */
  17961. {
  17962. std::unique_lock<std::mutex> lock(sem_mtx);
  17963. while (credits > 0) {
  17964. sem_cv.wait(lock);
  17965. }
  17966. }
  17967. /* Check that we are able again to enqueue at least qlimit tasks. */
  17968. for (unsigned int i = 0; i < qlimit; i++) {
  17969. queued = task_queue->enqueue([] {});
  17970. EXPECT_TRUE(queued);
  17971. }
  17972. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17973. task_queue->shutdown();
  17974. #else
  17975. EXPECT_NO_THROW(task_queue->shutdown());
  17976. #endif
  17977. }
  17978. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17979. Server svr;
  17980. std::string method;
  17981. std::string body;
  17982. auto has_content_length = false;
  17983. auto has_transfer_encoding = false;
  17984. std::atomic<int> bad_requests{0};
  17985. // Leftover body bytes get parsed as a malformed request and answered with
  17986. // 400
  17987. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17988. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17989. });
  17990. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17991. res.set_redirect("/down", StatusCode::SeeOther_303);
  17992. });
  17993. svr.Get("/down", [&](const Request &req, Response &res) {
  17994. method = req.method;
  17995. body = req.body;
  17996. has_content_length = req.has_header("Content-Length");
  17997. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17998. res.set_content("ok", "text/plain");
  17999. });
  18000. auto port = svr.bind_to_any_port(HOST);
  18001. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18002. auto se = detail::scope_exit([&] {
  18003. svr.stop();
  18004. thread.join();
  18005. ASSERT_FALSE(svr.is_running());
  18006. });
  18007. svr.wait_until_ready();
  18008. const std::string payload = "SECRET-BODY";
  18009. auto check = [&](Client &cli, const Result &res) {
  18010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18011. EXPECT_EQ(StatusCode::OK_200, res->status);
  18012. EXPECT_EQ("ok", res->body);
  18013. EXPECT_EQ("GET", method);
  18014. EXPECT_TRUE(body.empty());
  18015. EXPECT_FALSE(has_content_length);
  18016. EXPECT_FALSE(has_transfer_encoding);
  18017. // Nothing of the original body may be left on the connection
  18018. auto res2 = cli.Get("/down");
  18019. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18020. EXPECT_EQ(StatusCode::OK_200, res2->status);
  18021. EXPECT_EQ("ok", res2->body);
  18022. EXPECT_EQ(0, bad_requests);
  18023. };
  18024. // With content length
  18025. {
  18026. Client cli(HOST, port);
  18027. cli.set_keep_alive(true);
  18028. cli.set_follow_location(true);
  18029. auto res = cli.Post(
  18030. "/up", payload.size(),
  18031. [&](size_t offset, size_t length, DataSink &sink) {
  18032. return sink.write(payload.data() + offset, length);
  18033. },
  18034. "text/plain");
  18035. check(cli, res);
  18036. }
  18037. // Without content length (chunked)
  18038. {
  18039. Client cli(HOST, port);
  18040. cli.set_keep_alive(true);
  18041. cli.set_follow_location(true);
  18042. auto res = cli.Post(
  18043. "/up",
  18044. [&](size_t /*offset*/, DataSink &sink) {
  18045. sink.write(payload.data(), payload.size());
  18046. sink.done();
  18047. return true;
  18048. },
  18049. "text/plain");
  18050. check(cli, res);
  18051. }
  18052. }
  18053. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18054. Server svr;
  18055. std::string target;
  18056. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18057. // Echo the still-encoded name back in the Location
  18058. const std::string prefix = "/start/";
  18059. res.status = StatusCode::Found_302;
  18060. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18061. });
  18062. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18063. target = req.target;
  18064. res.set_content("ok", "text/plain");
  18065. });
  18066. auto port = svr.bind_to_any_port(HOST);
  18067. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18068. auto se = detail::scope_exit([&] {
  18069. svr.stop();
  18070. thread.join();
  18071. ASSERT_FALSE(svr.is_running());
  18072. });
  18073. svr.wait_until_ready();
  18074. // Decoding the Location path would turn the first four into a path
  18075. // separator, a query delimiter, a fragment delimiter and a different
  18076. // percent-encoded octet. The rest must keep reaching the server as they are.
  18077. const std::vector<std::string> names = {
  18078. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18079. };
  18080. for (auto path_encode : {true, false}) {
  18081. Client cli(HOST, port);
  18082. cli.set_follow_location(true);
  18083. cli.set_path_encode(path_encode);
  18084. for (const auto &name : names) {
  18085. target.clear();
  18086. auto res = cli.Get("/start/" + name);
  18087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18088. EXPECT_EQ(StatusCode::OK_200, res->status);
  18089. EXPECT_EQ("/dest/" + name, target);
  18090. }
  18091. }
  18092. }
  18093. TEST(RedirectTest, NotModifiedIsReturned) {
  18094. Server svr;
  18095. svr.Get("/cached", [](const Request &, Response &res) {
  18096. res.status = StatusCode::NotModified_304;
  18097. });
  18098. auto port = svr.bind_to_any_port(HOST);
  18099. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18100. auto se = detail::scope_exit([&] {
  18101. svr.stop();
  18102. thread.join();
  18103. ASSERT_FALSE(svr.is_running());
  18104. });
  18105. svr.wait_until_ready();
  18106. Client cli(HOST, port);
  18107. cli.set_follow_location(true);
  18108. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18109. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18110. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18111. }
  18112. TEST(RedirectTest, NoLocationIsReturned) {
  18113. Server svr;
  18114. svr.Get("/no-location", [](const Request &, Response &res) {
  18115. res.status = StatusCode::Found_302;
  18116. res.set_content("no location", "text/plain");
  18117. });
  18118. auto port = svr.bind_to_any_port(HOST);
  18119. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18120. auto se = detail::scope_exit([&] {
  18121. svr.stop();
  18122. thread.join();
  18123. ASSERT_FALSE(svr.is_running());
  18124. });
  18125. svr.wait_until_ready();
  18126. Client cli(HOST, port);
  18127. cli.set_follow_location(true);
  18128. auto res = cli.Get("/no-location");
  18129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18130. EXPECT_EQ(StatusCode::Found_302, res->status);
  18131. EXPECT_EQ("no location", res->body);
  18132. // The callbacks see the body of the response that is returned
  18133. auto handler_called = false;
  18134. auto progress_called = false;
  18135. std::string body;
  18136. auto res2 = cli.Get(
  18137. "/no-location",
  18138. [&](const Response &) {
  18139. handler_called = true;
  18140. return true;
  18141. },
  18142. [&](const char *data, size_t data_length) {
  18143. body.append(data, data_length);
  18144. return true;
  18145. },
  18146. [&](size_t, size_t) {
  18147. progress_called = true;
  18148. return true;
  18149. });
  18150. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18151. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18152. EXPECT_TRUE(handler_called);
  18153. EXPECT_TRUE(progress_called);
  18154. EXPECT_EQ("no location", body);
  18155. }
  18156. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18157. Server svr;
  18158. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18159. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18160. });
  18161. svr.Get("/hello", [](const Request &req, Response &res) {
  18162. res.set_content(req.get_param_value("key"), "text/plain");
  18163. });
  18164. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18165. auto se = detail::scope_exit([&] {
  18166. svr.stop();
  18167. thread.join();
  18168. ASSERT_FALSE(svr.is_running());
  18169. });
  18170. svr.wait_until_ready();
  18171. {
  18172. Client cli(HOST, PORT);
  18173. cli.set_follow_location(true);
  18174. auto res = cli.Get("/");
  18175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18176. EXPECT_EQ(StatusCode::OK_200, res->status);
  18177. EXPECT_EQ("val&key2=val2", res->body);
  18178. }
  18179. }
  18180. #endif
  18181. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18182. Server svr;
  18183. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18184. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18185. });
  18186. svr.Get("/hello", [](const Request &req, Response &res) {
  18187. res.set_content(req.get_param_value("key"), "text/plain");
  18188. });
  18189. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18190. auto se = detail::scope_exit([&] {
  18191. svr.stop();
  18192. thread.join();
  18193. ASSERT_FALSE(svr.is_running());
  18194. });
  18195. svr.wait_until_ready();
  18196. {
  18197. Client cli(HOST, PORT);
  18198. cli.set_follow_location(true);
  18199. auto res = cli.Get("/");
  18200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18201. EXPECT_EQ(StatusCode::OK_200, res->status);
  18202. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18203. }
  18204. }
  18205. TEST(RedirectTest, RedirectWithPlusInPath) {
  18206. Server svr;
  18207. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18208. res.set_redirect("/a+b");
  18209. });
  18210. // Route pattern uses regex; escape + as \\+
  18211. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18212. res.set_content(req.path, "text/plain");
  18213. });
  18214. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18215. auto se = detail::scope_exit([&] {
  18216. svr.stop();
  18217. thread.join();
  18218. ASSERT_FALSE(svr.is_running());
  18219. });
  18220. svr.wait_until_ready();
  18221. {
  18222. Client cli(HOST, PORT);
  18223. cli.set_follow_location(true);
  18224. auto res = cli.Get("/");
  18225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18226. EXPECT_EQ(StatusCode::OK_200, res->status);
  18227. EXPECT_EQ("/a+b", res->body);
  18228. }
  18229. }
  18230. TEST(RedirectTest, ResolveRelativeLocation) {
  18231. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18232. const std::vector<std::pair<std::string, std::string>> cases = {
  18233. {"g", "/b/c/g"},
  18234. {"./g", "/b/c/g"},
  18235. {"g/", "/b/c/g/"},
  18236. {"?y", "/b/c/d;p?y"},
  18237. {"g?y", "/b/c/g?y"},
  18238. {"#s", "/b/c/d;p?q#s"},
  18239. {"g#s", "/b/c/g#s"},
  18240. {"g?y#s", "/b/c/g?y#s"},
  18241. {";x", "/b/c/;x"},
  18242. {"g;x", "/b/c/g;x"},
  18243. {".", "/b/c/"},
  18244. {"./", "/b/c/"},
  18245. {"..", "/b/"},
  18246. {"../", "/b/"},
  18247. {"../g", "/b/g"},
  18248. {"../..", "/"},
  18249. {"../../", "/"},
  18250. {"../../g", "/g"},
  18251. {"../../../g", "/g"},
  18252. {"g.", "/b/c/g."},
  18253. {".g", "/b/c/.g"},
  18254. {"g..", "/b/c/g.."},
  18255. {"..g", "/b/c/..g"},
  18256. {"./../g", "/b/g"},
  18257. {"./g/.", "/b/c/g/"},
  18258. {"g/./h", "/b/c/g/h"},
  18259. {"g/../h", "/b/c/h"},
  18260. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18261. {"g;x=1/../y", "/b/c/y"},
  18262. {"g?y/./x", "/b/c/g?y/./x"},
  18263. {"g#s/../x", "/b/c/g#s/../x"},
  18264. // Not relative-path references, so left for parse_url.
  18265. {"/g", "/g"},
  18266. {"//g", "//g"},
  18267. {"http://g/x", "http://g/x"},
  18268. {"g:h", "g:h"},
  18269. };
  18270. for (const auto &c : cases) {
  18271. EXPECT_EQ(c.second,
  18272. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18273. << c.first;
  18274. }
  18275. // A result starting with "//" is still a path, not a network-path reference
  18276. EXPECT_EQ("/.//g",
  18277. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18278. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18279. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18280. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18281. }
  18282. TEST(RedirectTest, RemoveDotSegments) {
  18283. // RFC 3986 section 5.2.4
  18284. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18285. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18286. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18287. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18288. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18289. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18290. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18291. }
  18292. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18293. Server svr;
  18294. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18295. res.set_redirect("/dir/../target?x=1");
  18296. });
  18297. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18298. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18299. "/dir/./../target");
  18300. });
  18301. svr.Get("/target", [](const Request &req, Response &res) {
  18302. res.set_content(req.path, "text/plain");
  18303. });
  18304. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18305. auto se = detail::scope_exit([&] {
  18306. svr.stop();
  18307. th.join();
  18308. ASSERT_FALSE(svr.is_running());
  18309. });
  18310. svr.wait_until_ready();
  18311. Client cli("localhost", PORT);
  18312. cli.set_follow_location(true);
  18313. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18314. auto res = cli.Get(path);
  18315. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18316. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18317. EXPECT_EQ("/target", res->body) << path;
  18318. }
  18319. }
  18320. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18321. Server svr;
  18322. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18323. res.set_redirect(req.get_param_value("to"));
  18324. });
  18325. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18326. res.set_content(req.target, "text/plain");
  18327. });
  18328. svr.Get("/other", [](const Request &req, Response &res) {
  18329. res.set_content(req.target, "text/plain");
  18330. });
  18331. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18332. auto se = detail::scope_exit([&] {
  18333. svr.stop();
  18334. thread.join();
  18335. ASSERT_FALSE(svr.is_running());
  18336. });
  18337. svr.wait_until_ready();
  18338. const std::vector<std::pair<std::string, std::string>> cases = {
  18339. {"next", "/dir/next"},
  18340. {"./next?x=1", "/dir/next?x=1"},
  18341. {"next?source=https://example.com/catalog",
  18342. "/dir/next?source=https://example.com/catalog"},
  18343. {"../other", "/other"},
  18344. };
  18345. for (const auto &c : cases) {
  18346. Client cli(HOST, PORT);
  18347. cli.set_follow_location(true);
  18348. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18349. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18350. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18351. EXPECT_EQ(c.second, res->body) << c.first;
  18352. }
  18353. }
  18354. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18355. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18356. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18357. Server other;
  18358. std::atomic<int> other_hits{0};
  18359. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18360. other_hits++;
  18361. res.set_content("other", "text/plain");
  18362. });
  18363. auto other_port = other.bind_to_any_port("127.0.0.1");
  18364. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18365. Server svr;
  18366. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18367. res.set_redirect(req.get_param_value("to"));
  18368. });
  18369. svr.Get(".*", [](const Request &req, Response &res) {
  18370. res.set_content(req.path, "text/plain");
  18371. });
  18372. auto port = svr.bind_to_any_port(HOST);
  18373. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18374. auto se = detail::scope_exit([&] {
  18375. svr.stop();
  18376. thread.join();
  18377. other.stop();
  18378. other_thread.join();
  18379. ASSERT_FALSE(svr.is_running());
  18380. ASSERT_FALSE(other.is_running());
  18381. });
  18382. svr.wait_until_ready();
  18383. other.wait_until_ready();
  18384. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18385. for (const auto &to :
  18386. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18387. Client cli(HOST, port);
  18388. cli.set_follow_location(true);
  18389. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18390. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18391. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18392. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18393. }
  18394. EXPECT_EQ(0, other_hits.load());
  18395. }
  18396. #ifdef CPPHTTPLIB_SSL_ENABLED
  18397. TEST(RedirectTest, Issue2185_Online) {
  18398. SSLClient client("github.com");
  18399. client.set_follow_location(true);
  18400. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18401. "Coollab-Windows.zip");
  18402. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18403. EXPECT_EQ(StatusCode::OK_200, res->status);
  18404. EXPECT_EQ(9920427U, res->body.size());
  18405. }
  18406. #endif
  18407. TEST(VulnerabilityTest, CRLFInjection) {
  18408. Server svr;
  18409. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18410. res.set_content("Hello 1", "text/plain");
  18411. });
  18412. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18413. res.set_content("Hello 2", "text/plain");
  18414. });
  18415. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18416. res.set_content("Hello 3", "text/plain");
  18417. });
  18418. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18419. res.set_content("Hello 4", "text/plain");
  18420. });
  18421. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18422. for (const auto &x : req.headers) {
  18423. auto key = x.first;
  18424. EXPECT_STRNE("evil", key.c_str());
  18425. }
  18426. });
  18427. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18428. auto se = detail::scope_exit([&] {
  18429. svr.stop();
  18430. thread.join();
  18431. ASSERT_FALSE(svr.is_running());
  18432. });
  18433. svr.wait_until_ready();
  18434. {
  18435. Client cli(HOST, PORT);
  18436. cli.Post("/test1", "A=B",
  18437. "application/x-www-form-urlencoded\r\nevil: hello1");
  18438. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18439. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18440. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18441. }
  18442. }
  18443. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18444. auto server_thread = std::thread([] {
  18445. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18446. default_socket_options(srv);
  18447. sockaddr_in addr{};
  18448. addr.sin_family = AF_INET;
  18449. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18450. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18451. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18452. ::listen(srv, 1);
  18453. sockaddr_in cli_addr{};
  18454. socklen_t cli_len = sizeof(cli_addr);
  18455. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18456. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18457. std::string buf_all;
  18458. char buf[2048];
  18459. ssize_t n;
  18460. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18461. buf_all.append(buf, static_cast<size_t>(n));
  18462. size_t pos;
  18463. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18464. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18465. auto e = request_block.find("\r\n");
  18466. if (e != std::string::npos) {
  18467. auto request_line = request_block.substr(0, e);
  18468. std::string msg =
  18469. "CRLF injection detected in request line: '" + request_line + "'";
  18470. EXPECT_FALSE(true) << msg;
  18471. }
  18472. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18473. ::send(cli,
  18474. #ifdef _WIN32
  18475. static_cast<const char *>(resp.c_str()),
  18476. static_cast<int>(resp.size()),
  18477. #else
  18478. resp.c_str(), resp.size(),
  18479. #endif
  18480. 0);
  18481. buf_all.erase(0, pos + 4);
  18482. }
  18483. }
  18484. detail::close_socket(cli);
  18485. detail::close_socket(srv);
  18486. });
  18487. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18488. auto cli = Client("127.0.0.1", PORT + 1);
  18489. auto headers = Headers{
  18490. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18491. {"Connection", "keep-alive"}};
  18492. auto res = cli.Get("/hi", headers);
  18493. EXPECT_FALSE(res);
  18494. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18495. server_thread.join();
  18496. }
  18497. // A request rejected before any byte reaches the socket must fail right away
  18498. // instead of waiting for a response the server will never send.
  18499. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18500. // The kernel completes the TCP handshake from the listen backlog, so the
  18501. // client connects, but nothing ever reads, responds or closes.
  18502. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18503. default_socket_options(srv);
  18504. sockaddr_in addr{};
  18505. addr.sin_family = AF_INET;
  18506. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18507. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18508. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18509. ASSERT_EQ(0, ::listen(srv, 8));
  18510. auto cli = Client("127.0.0.1", PORT + 1);
  18511. cli.set_read_timeout(10, 0);
  18512. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18513. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18514. std::chrono::steady_clock::now() - start)
  18515. .count();
  18516. };
  18517. {
  18518. Request req;
  18519. req.method = "GE T";
  18520. req.path = "/";
  18521. auto start = std::chrono::steady_clock::now();
  18522. auto res = cli.send(req);
  18523. EXPECT_FALSE(res);
  18524. EXPECT_EQ(Error::Write, res.error());
  18525. EXPECT_LT(elapsed_ms(start), 1000);
  18526. }
  18527. {
  18528. auto start = std::chrono::steady_clock::now();
  18529. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18530. EXPECT_FALSE(res);
  18531. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18532. EXPECT_LT(elapsed_ms(start), 1000);
  18533. }
  18534. EXPECT_FALSE(cli.is_socket_open());
  18535. detail::close_socket(srv);
  18536. }
  18537. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18538. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18539. default_socket_options(srv);
  18540. sockaddr_in addr{};
  18541. addr.sin_family = AF_INET;
  18542. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18543. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18544. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18545. ASSERT_EQ(0, ::listen(srv, 1));
  18546. std::string received;
  18547. auto server_thread = std::thread([&] {
  18548. auto sock = ::accept(srv, nullptr, nullptr);
  18549. if (sock == INVALID_SOCKET) { return; }
  18550. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18551. char buf[2048];
  18552. ssize_t n;
  18553. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18554. received.append(buf, static_cast<size_t>(n));
  18555. }
  18556. detail::close_socket(sock);
  18557. });
  18558. {
  18559. auto cli = Client("127.0.0.1", PORT + 1);
  18560. // "Z" sorts after the default headers, so writing straight to the socket
  18561. // would have sent the request line and those headers before the rejection.
  18562. auto handle =
  18563. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18564. EXPECT_FALSE(handle.is_valid());
  18565. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18566. }
  18567. server_thread.join();
  18568. detail::close_socket(srv);
  18569. EXPECT_TRUE(received.empty()) << received;
  18570. }
  18571. TEST(PathParamsTest, StaticMatch) {
  18572. const auto pattern = "/users/all";
  18573. detail::PathParamsMatcher matcher(pattern);
  18574. Request request;
  18575. request.path = "/users/all";
  18576. ASSERT_TRUE(matcher.match(request));
  18577. std::unordered_map<std::string, std::string> expected_params = {};
  18578. EXPECT_EQ(request.path_params, expected_params);
  18579. }
  18580. TEST(PathParamsTest, StaticMismatch) {
  18581. const auto pattern = "/users/all";
  18582. detail::PathParamsMatcher matcher(pattern);
  18583. Request request;
  18584. request.path = "/users/1";
  18585. ASSERT_FALSE(matcher.match(request));
  18586. }
  18587. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18588. const auto pattern = "/users/:id/subscriptions";
  18589. detail::PathParamsMatcher matcher(pattern);
  18590. Request request;
  18591. request.path = "/users/42/subscriptions";
  18592. ASSERT_TRUE(matcher.match(request));
  18593. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18594. EXPECT_EQ(request.path_params, expected_params);
  18595. }
  18596. TEST(PathParamsTest, SingleParamInTheEnd) {
  18597. const auto pattern = "/users/:id";
  18598. detail::PathParamsMatcher matcher(pattern);
  18599. Request request;
  18600. request.path = "/users/24";
  18601. ASSERT_TRUE(matcher.match(request));
  18602. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18603. EXPECT_EQ(request.path_params, expected_params);
  18604. }
  18605. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18606. const auto pattern = "/users/:id/";
  18607. detail::PathParamsMatcher matcher(pattern);
  18608. Request request;
  18609. request.path = "/users/42/";
  18610. ASSERT_TRUE(matcher.match(request));
  18611. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18612. EXPECT_EQ(request.path_params, expected_params);
  18613. }
  18614. TEST(PathParamsTest, EmptyParam) {
  18615. const auto pattern = "/users/:id/";
  18616. detail::PathParamsMatcher matcher(pattern);
  18617. Request request;
  18618. request.path = "/users//";
  18619. ASSERT_TRUE(matcher.match(request));
  18620. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18621. EXPECT_EQ(request.path_params, expected_params);
  18622. }
  18623. TEST(PathParamsTest, FragmentMismatch) {
  18624. const auto pattern = "/users/:id/";
  18625. detail::PathParamsMatcher matcher(pattern);
  18626. Request request;
  18627. request.path = "/admins/24/";
  18628. ASSERT_FALSE(matcher.match(request));
  18629. }
  18630. TEST(PathParamsTest, ExtraFragments) {
  18631. const auto pattern = "/users/:id";
  18632. detail::PathParamsMatcher matcher(pattern);
  18633. Request request;
  18634. request.path = "/users/42/subscriptions";
  18635. ASSERT_FALSE(matcher.match(request));
  18636. }
  18637. TEST(PathParamsTest, MissingTrailingParam) {
  18638. const auto pattern = "/users/:id";
  18639. detail::PathParamsMatcher matcher(pattern);
  18640. Request request;
  18641. request.path = "/users";
  18642. ASSERT_FALSE(matcher.match(request));
  18643. }
  18644. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18645. const auto pattern = "/users/:id/subscriptions";
  18646. detail::PathParamsMatcher matcher(pattern);
  18647. Request request;
  18648. request.path = "/users/subscriptions";
  18649. ASSERT_FALSE(matcher.match(request));
  18650. }
  18651. TEST(PathParamsTest, MultipleParams) {
  18652. const auto pattern = "/users/:userid/subscriptions/:subid";
  18653. detail::PathParamsMatcher matcher(pattern);
  18654. Request request;
  18655. request.path = "/users/42/subscriptions/2";
  18656. ASSERT_TRUE(matcher.match(request));
  18657. std::unordered_map<std::string, std::string> expected_params = {
  18658. {"userid", "42"}, {"subid", "2"}};
  18659. EXPECT_EQ(request.path_params, expected_params);
  18660. }
  18661. TEST(PathParamsTest, SequenceOfParams) {
  18662. const auto pattern = "/values/:x/:y/:z";
  18663. detail::PathParamsMatcher matcher(pattern);
  18664. Request request;
  18665. request.path = "/values/1/2/3";
  18666. ASSERT_TRUE(matcher.match(request));
  18667. std::unordered_map<std::string, std::string> expected_params = {
  18668. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18669. EXPECT_EQ(request.path_params, expected_params);
  18670. }
  18671. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18672. const auto pattern = "/prefix:suffix";
  18673. detail::PathParamsMatcher matcher(pattern);
  18674. Request request;
  18675. request.path = "/prefix:suffix";
  18676. ASSERT_TRUE(matcher.match(request));
  18677. const std::unordered_map<std::string, std::string> expected_params = {};
  18678. EXPECT_EQ(request.path_params, expected_params);
  18679. }
  18680. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18681. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18682. // calling thread's stack on a long enough path for a quantified pattern;
  18683. // RegexMatcher must refuse to run regex matching on paths beyond
  18684. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18685. detail::RegexMatcher matcher("/files/(.*)");
  18686. Request within_limit;
  18687. within_limit.path = "/files/" + std::string(10, 'A');
  18688. EXPECT_TRUE(matcher.match(within_limit));
  18689. Request over_limit;
  18690. over_limit.path =
  18691. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18692. EXPECT_FALSE(matcher.match(over_limit));
  18693. }
  18694. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18695. Server svr;
  18696. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18697. res.set_content("ok", "text/plain");
  18698. });
  18699. auto port = svr.bind_to_any_port(HOST);
  18700. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18701. auto se = detail::scope_exit([&] {
  18702. svr.stop();
  18703. thread.join();
  18704. ASSERT_FALSE(svr.is_running());
  18705. });
  18706. svr.wait_until_ready();
  18707. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18708. // request URI limit; this used to be able to crash the process.
  18709. std::string path =
  18710. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18711. std::string req = "GET " + path +
  18712. " HTTP/1.1\r\n"
  18713. "Host: " +
  18714. std::string(HOST) + ":" + std::to_string(port) +
  18715. "\r\n"
  18716. "Connection: close\r\n"
  18717. "\r\n";
  18718. std::string response;
  18719. ASSERT_TRUE(send_request(5, req, &response, port));
  18720. EXPECT_NE(std::string::npos, response.find("404"));
  18721. }
  18722. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18723. Server svr;
  18724. auto handler = [](const Request & /*req*/, Response &res) {
  18725. res.set_content("hit", "text/plain");
  18726. };
  18727. // No regex metacharacter, so this one is compared literally
  18728. svr.Get("/literal/route", handler);
  18729. // '.' is a regex metacharacter, so this one must keep regex semantics
  18730. svr.Get("/a.c", handler);
  18731. auto port = svr.bind_to_any_port(HOST);
  18732. std::thread t([&]() { svr.listen_after_bind(); });
  18733. auto se = detail::scope_exit([&] {
  18734. svr.stop();
  18735. t.join();
  18736. ASSERT_FALSE(svr.is_running());
  18737. });
  18738. svr.wait_until_ready();
  18739. Client cli(HOST, port);
  18740. struct {
  18741. const char *path;
  18742. int status;
  18743. } cases[] = {
  18744. {"/literal/route", StatusCode::OK_200},
  18745. {"/literal/routes", StatusCode::NotFound_404},
  18746. {"/literal/rout", StatusCode::NotFound_404},
  18747. {"/abc", StatusCode::OK_200},
  18748. {"/a.c", StatusCode::OK_200},
  18749. };
  18750. for (const auto &x : cases) {
  18751. auto res = cli.Get(x.path);
  18752. ASSERT_TRUE(res) << x.path;
  18753. EXPECT_EQ(x.status, res->status) << x.path;
  18754. }
  18755. }
  18756. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18757. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18758. // from exhausting the stack, so it must only constrain routes that actually
  18759. // run a regular expression. A literal route is matched by comparison and
  18760. // stays usable at any length.
  18761. Server svr;
  18762. const std::string pattern =
  18763. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18764. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18765. res.set_content("hit", "text/plain");
  18766. });
  18767. auto port = svr.bind_to_any_port(HOST);
  18768. std::thread t([&]() { svr.listen_after_bind(); });
  18769. auto se = detail::scope_exit([&] {
  18770. svr.stop();
  18771. t.join();
  18772. ASSERT_FALSE(svr.is_running());
  18773. });
  18774. svr.wait_until_ready();
  18775. Client cli(HOST, port);
  18776. auto res = cli.Get(pattern);
  18777. ASSERT_TRUE(res);
  18778. EXPECT_EQ(StatusCode::OK_200, res->status);
  18779. }
  18780. TEST(ParseUrlTest, VariousPatterns) {
  18781. {
  18782. detail::UrlComponents uc;
  18783. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18784. EXPECT_EQ("http", uc.scheme);
  18785. EXPECT_EQ("example.com", uc.host);
  18786. EXPECT_EQ("8080", uc.port);
  18787. EXPECT_EQ("/path", uc.path);
  18788. EXPECT_EQ("?q=1", uc.query);
  18789. }
  18790. {
  18791. detail::UrlComponents uc;
  18792. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18793. EXPECT_EQ("https", uc.scheme);
  18794. EXPECT_EQ("example.com", uc.host);
  18795. EXPECT_TRUE(uc.port.empty());
  18796. EXPECT_EQ("/path", uc.path);
  18797. }
  18798. {
  18799. detail::UrlComponents uc;
  18800. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18801. EXPECT_EQ("::1", uc.host);
  18802. EXPECT_EQ("8080", uc.port);
  18803. EXPECT_EQ("/path", uc.path);
  18804. }
  18805. {
  18806. detail::UrlComponents uc;
  18807. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18808. }
  18809. {
  18810. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18811. // the path while the connection still targets the bracketed host.
  18812. detail::UrlComponents uc;
  18813. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18814. }
  18815. {
  18816. detail::UrlComponents uc;
  18817. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18818. }
  18819. {
  18820. detail::UrlComponents uc;
  18821. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18822. EXPECT_EQ("::1", uc.host);
  18823. EXPECT_TRUE(uc.port.empty());
  18824. EXPECT_EQ("/path", uc.path);
  18825. }
  18826. {
  18827. detail::UrlComponents uc;
  18828. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18829. EXPECT_TRUE(uc.scheme.empty());
  18830. EXPECT_EQ("example.com", uc.host);
  18831. EXPECT_EQ("/path", uc.path);
  18832. EXPECT_EQ("?q=1", uc.query);
  18833. }
  18834. {
  18835. detail::UrlComponents uc;
  18836. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18837. EXPECT_TRUE(uc.host.empty());
  18838. EXPECT_EQ("/path", uc.path);
  18839. EXPECT_EQ("?q=1", uc.query);
  18840. }
  18841. {
  18842. detail::UrlComponents uc;
  18843. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18844. EXPECT_EQ("example.com", uc.host);
  18845. EXPECT_EQ("8080", uc.port);
  18846. }
  18847. {
  18848. // Unix socket path — must not be parsed as host
  18849. detail::UrlComponents uc;
  18850. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18851. EXPECT_TRUE(uc.host.empty());
  18852. }
  18853. {
  18854. detail::UrlComponents uc;
  18855. ASSERT_TRUE(detail::parse_url("", uc));
  18856. EXPECT_TRUE(uc.host.empty());
  18857. EXPECT_TRUE(uc.path.empty());
  18858. }
  18859. {
  18860. detail::UrlComponents uc;
  18861. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18862. EXPECT_EQ("http", uc.scheme);
  18863. }
  18864. {
  18865. detail::UrlComponents uc;
  18866. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18867. }
  18868. {
  18869. // Accepted by parse_url; callers restrict to http/https
  18870. detail::UrlComponents uc;
  18871. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18872. EXPECT_EQ("ftp", uc.scheme);
  18873. }
  18874. {
  18875. detail::UrlComponents uc;
  18876. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18877. }
  18878. {
  18879. detail::UrlComponents uc;
  18880. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18881. }
  18882. }
  18883. TEST(ParseUrlTest, FragmentHandling) {
  18884. {
  18885. detail::UrlComponents uc;
  18886. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18887. EXPECT_EQ("/path", uc.path);
  18888. EXPECT_TRUE(uc.query.empty());
  18889. }
  18890. {
  18891. detail::UrlComponents uc;
  18892. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18893. EXPECT_TRUE(uc.path.empty());
  18894. EXPECT_TRUE(uc.query.empty());
  18895. }
  18896. }
  18897. TEST(ParseUrlTest, UserinfoHandling) {
  18898. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18899. // parsers would see evil.com as the host.
  18900. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18901. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18902. for (auto url : urls) {
  18903. detail::UrlComponents uc;
  18904. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18905. }
  18906. }
  18907. TEST(ParseUrlTest, IPv6EdgeCases) {
  18908. {
  18909. detail::UrlComponents uc;
  18910. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18911. EXPECT_TRUE(uc.scheme.empty());
  18912. EXPECT_EQ("::1", uc.host);
  18913. EXPECT_EQ("8080", uc.port);
  18914. }
  18915. {
  18916. // Zone ID '%25' is not in [a-fA-F0-9:]
  18917. detail::UrlComponents uc;
  18918. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18919. }
  18920. }
  18921. TEST(ParseUrlTest, SchemeEdgeCases) {
  18922. {
  18923. detail::UrlComponents uc;
  18924. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18925. }
  18926. {
  18927. detail::UrlComponents uc;
  18928. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18929. }
  18930. {
  18931. detail::UrlComponents uc;
  18932. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18933. }
  18934. {
  18935. detail::UrlComponents uc;
  18936. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18937. EXPECT_EQ("https", uc.scheme);
  18938. }
  18939. {
  18940. detail::UrlComponents uc;
  18941. ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
  18942. EXPECT_TRUE(uc.scheme.empty());
  18943. EXPECT_TRUE(uc.host.empty());
  18944. EXPECT_EQ("/path", uc.path);
  18945. EXPECT_EQ("?next=https://example.com/", uc.query);
  18946. }
  18947. }
  18948. TEST(ParseUrlTest, PortEdgeCases) {
  18949. {
  18950. detail::UrlComponents uc;
  18951. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18952. EXPECT_TRUE(uc.port.empty());
  18953. EXPECT_EQ("/path", uc.path);
  18954. }
  18955. {
  18956. // parse_url accepts any port string; validation is done by parse_port
  18957. detail::UrlComponents uc;
  18958. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18959. EXPECT_EQ("abc", uc.port);
  18960. }
  18961. }
  18962. TEST(ParseUrlTest, WebSocketPatterns) {
  18963. {
  18964. detail::UrlComponents uc;
  18965. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18966. EXPECT_EQ("ws", uc.scheme);
  18967. EXPECT_EQ("echo.example.com", uc.host);
  18968. EXPECT_EQ("8080", uc.port);
  18969. EXPECT_EQ("/ws", uc.path);
  18970. }
  18971. {
  18972. detail::UrlComponents uc;
  18973. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18974. EXPECT_EQ("wss", uc.scheme);
  18975. EXPECT_EQ("echo.example.com", uc.host);
  18976. EXPECT_TRUE(uc.port.empty());
  18977. EXPECT_EQ("/ws", uc.path);
  18978. }
  18979. }
  18980. TEST(ParseUrlTest, QueryOnly) {
  18981. detail::UrlComponents uc;
  18982. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18983. EXPECT_TRUE(uc.host.empty());
  18984. EXPECT_TRUE(uc.path.empty());
  18985. EXPECT_EQ("?q=1&r=2", uc.query);
  18986. }
  18987. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18988. detail::UrlComponents uc;
  18989. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18990. EXPECT_TRUE(uc.scheme.empty());
  18991. EXPECT_EQ("example.com", uc.host);
  18992. EXPECT_EQ("443", uc.port);
  18993. EXPECT_EQ("/path", uc.path);
  18994. }
  18995. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18996. // If ipv6 regex working, regex match codepath is taken.
  18997. // else port will default to 80 in Client impl
  18998. int clientImplMagicPort = 80;
  18999. int port = 4321;
  19000. // above ports must be different to avoid false negative
  19001. EXPECT_NE(clientImplMagicPort, port);
  19002. std::string ipV6TestURL = "http://[ff06::c3]";
  19003. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  19004. CLIENT_PRIVATE_KEY_FILE);
  19005. EXPECT_EQ(cli.port(), port);
  19006. }
  19007. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  19008. auto file_path = "./www/dir/index.html";
  19009. auto dir_path = "./www/dir";
  19010. detail::FileStat stat_file(file_path);
  19011. EXPECT_TRUE(stat_file.is_file());
  19012. EXPECT_FALSE(stat_file.is_dir());
  19013. detail::FileStat stat_dir(dir_path);
  19014. EXPECT_FALSE(stat_dir.is_file());
  19015. EXPECT_TRUE(stat_dir.is_dir());
  19016. }
  19017. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  19018. // IPv4 with default HTTP port (80)
  19019. EXPECT_EQ("example.com",
  19020. detail::make_host_and_port_string("example.com", 80, false));
  19021. // IPv4 with default HTTPS port (443)
  19022. EXPECT_EQ("example.com",
  19023. detail::make_host_and_port_string("example.com", 443, true));
  19024. // IPv4 with non-default HTTP port
  19025. EXPECT_EQ("example.com:8080",
  19026. detail::make_host_and_port_string("example.com", 8080, false));
  19027. // IPv4 with non-default HTTPS port
  19028. EXPECT_EQ("example.com:8443",
  19029. detail::make_host_and_port_string("example.com", 8443, true));
  19030. // IPv6 with default HTTP port (80)
  19031. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  19032. // IPv6 with default HTTPS port (443)
  19033. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  19034. // IPv6 with non-default HTTP port
  19035. EXPECT_EQ("[::1]:8080",
  19036. detail::make_host_and_port_string("::1", 8080, false));
  19037. // IPv6 with non-default HTTPS port
  19038. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  19039. // IPv6 full address with default port
  19040. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  19041. detail::make_host_and_port_string(
  19042. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  19043. // IPv6 full address with non-default port
  19044. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  19045. detail::make_host_and_port_string(
  19046. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  19047. // IPv6 localhost with non-default port
  19048. EXPECT_EQ("[::1]:3000",
  19049. detail::make_host_and_port_string("::1", 3000, false));
  19050. // IPv6 with zone ID (link-local address) with default port
  19051. EXPECT_EQ("[fe80::1%eth0]",
  19052. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19053. // IPv6 with zone ID (link-local address) with non-default port
  19054. EXPECT_EQ("[fe80::1%eth0]:8080",
  19055. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19056. // Edge case: Port 443 with is_ssl=false (should add port)
  19057. EXPECT_EQ("example.com:443",
  19058. detail::make_host_and_port_string("example.com", 443, false));
  19059. // Edge case: Port 80 with is_ssl=true (should add port)
  19060. EXPECT_EQ("example.com:80",
  19061. detail::make_host_and_port_string("example.com", 80, true));
  19062. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19063. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19064. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19065. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19066. // Security fix: Already bracketed IPv6 should not get double brackets
  19067. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19068. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19069. EXPECT_EQ("[::1]:8080",
  19070. detail::make_host_and_port_string("[::1]", 8080, false));
  19071. EXPECT_EQ("[2001:db8::1]:8080",
  19072. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19073. EXPECT_EQ("[fe80::1%eth0]",
  19074. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19075. EXPECT_EQ("[fe80::1%eth0]:8080",
  19076. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19077. // Edge case: Empty host (should return as-is)
  19078. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19079. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19080. // This is a known limitation but shouldn't crash
  19081. EXPECT_EQ("[host:name]",
  19082. detail::make_host_and_port_string("host:name", 80, false));
  19083. // Port number edge cases (no validation, but should not crash)
  19084. EXPECT_EQ("example.com:0",
  19085. detail::make_host_and_port_string("example.com", 0, false));
  19086. EXPECT_EQ("example.com:-1",
  19087. detail::make_host_and_port_string("example.com", -1, false));
  19088. EXPECT_EQ("example.com:65535",
  19089. detail::make_host_and_port_string("example.com", 65535, false));
  19090. EXPECT_EQ("example.com:65536",
  19091. detail::make_host_and_port_string("example.com", 65536, false));
  19092. }
  19093. namespace httplib {
  19094. namespace detail {
  19095. std::string
  19096. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19097. const std::string &host, int port);
  19098. } // namespace detail
  19099. } // namespace httplib
  19100. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19101. std::map<std::string, std::string> addr_map = {
  19102. {"ipv4.example", "192.0.2.10"},
  19103. {"ipv6.example", "2001:db8::1"},
  19104. {"name.example", "internal.example.lan"},
  19105. {"empty.example", ""}};
  19106. EXPECT_EQ("192.0.2.10:443",
  19107. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19108. EXPECT_EQ("[2001:db8::1]:443",
  19109. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19110. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19111. addr_map, "name.example", 8443));
  19112. // An empty or absent mapping keeps the hostname as the target
  19113. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19114. addr_map, "empty.example", 443));
  19115. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19116. addr_map, "other.example", 443));
  19117. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19118. }
  19119. #ifdef CPPHTTPLIB_SSL_ENABLED
  19120. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19121. httplib::SSLClient cli("roblox.com", 443);
  19122. cli.set_follow_location(true);
  19123. auto res = cli.Get("/");
  19124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19125. EXPECT_EQ(StatusCode::OK_200, res->status);
  19126. }
  19127. #endif
  19128. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19129. Server svr;
  19130. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19131. EXPECT_EQ(res.status, 400);
  19132. });
  19133. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19134. auto se = detail::scope_exit([&] {
  19135. svr.stop();
  19136. thread.join();
  19137. ASSERT_FALSE(svr.is_running());
  19138. });
  19139. svr.wait_until_ready();
  19140. Client cli(HOST, PORT);
  19141. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19142. }
  19143. TEST(InvalidHeaderCharsTest, is_field_name) {
  19144. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19145. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19146. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19147. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19148. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19149. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19150. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19151. EXPECT_FALSE(detail::fields::is_field_name(""));
  19152. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19153. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19154. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19155. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19156. }
  19157. TEST(InvalidHeaderCharsTest, is_field_value) {
  19158. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19159. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19160. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19161. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19162. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19163. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19164. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19165. EXPECT_TRUE(detail::fields::is_field_value(""));
  19166. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19167. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19168. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19169. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19170. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19171. }
  19172. TEST(InvalidHeaderCharsTest, OnServer) {
  19173. Server svr;
  19174. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19175. std::string header = "Not Set";
  19176. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19177. res.set_header(header, "value");
  19178. res.set_content("Page Content Page Content", "text/plain");
  19179. });
  19180. svr.Get("/test_value", [&](const Request &req, Response &res) {
  19181. std::string header = "Not Set";
  19182. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19183. res.set_header("X-Test", header);
  19184. res.set_content("Page Content Page Content", "text/plain");
  19185. });
  19186. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19187. auto se = detail::scope_exit([&] {
  19188. svr.stop();
  19189. thread.join();
  19190. ASSERT_FALSE(svr.is_running());
  19191. });
  19192. svr.wait_until_ready();
  19193. Client cli(HOST, PORT);
  19194. {
  19195. auto res = cli.Get(
  19196. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19197. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19198. EXPECT_EQ("Page Content Page Content", res->body);
  19199. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19200. }
  19201. {
  19202. auto res = cli.Get(
  19203. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19205. EXPECT_EQ("Page Content Page Content", res->body);
  19206. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19207. }
  19208. }
  19209. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19210. auto handled = false;
  19211. Server svr;
  19212. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19213. thread t = thread([&] { svr.listen(HOST, PORT); });
  19214. auto se = detail::scope_exit([&] {
  19215. svr.stop();
  19216. t.join();
  19217. ASSERT_FALSE(svr.is_running());
  19218. ASSERT_FALSE(handled);
  19219. });
  19220. svr.wait_until_ready();
  19221. auto req = "POST /test HTTP/1.1\r\n"
  19222. "Content-Length: x\r\n"
  19223. "\r\n";
  19224. std::string response;
  19225. ASSERT_TRUE(send_request(1, req, &response));
  19226. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19227. response.substr(0, response.find("\r\n")));
  19228. }
  19229. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19230. // case-insensitive, and a server that receives a 100-continue expectation in
  19231. // an HTTP/1.0 request MUST ignore it.
  19232. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19233. std::string response;
  19234. ASSERT_TRUE(send_request(1, req, &response, port));
  19235. *got_100 = response.find("100 Continue") != std::string::npos;
  19236. }
  19237. class ExpectTokenTest : public ::testing::Test {
  19238. protected:
  19239. void SetUp() override {
  19240. svr_.Post("/p", [](const Request &, Response &res) {
  19241. res.set_content("ok", "text/plain");
  19242. });
  19243. port_ = svr_.bind_to_any_port(HOST);
  19244. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19245. svr_.wait_until_ready();
  19246. }
  19247. void TearDown() override {
  19248. svr_.stop();
  19249. if (thread_.joinable()) { thread_.join(); }
  19250. }
  19251. std::string request(const char *version, const char *expect_value) const {
  19252. return std::string("POST /p ") + version +
  19253. "\r\n"
  19254. "Host: localhost\r\n"
  19255. "Content-Length: 2\r\n"
  19256. "Connection: close\r\n"
  19257. "Expect: " +
  19258. expect_value +
  19259. "\r\n"
  19260. "\r\n"
  19261. "hi";
  19262. }
  19263. Server svr_;
  19264. int port_ = 0;
  19265. thread thread_;
  19266. };
  19267. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19268. bool got_100 = false;
  19269. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19270. EXPECT_TRUE(got_100);
  19271. }
  19272. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19273. bool got_100 = true;
  19274. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19275. EXPECT_FALSE(got_100);
  19276. }
  19277. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19278. bool got_100 = false;
  19279. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19280. EXPECT_TRUE(got_100);
  19281. }
  19282. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19283. bool got_100 = false;
  19284. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19285. EXPECT_TRUE(got_100);
  19286. }
  19287. // `100 Continue` is sent only when the server starts reading the body, so a
  19288. // request rejected before that never invites the client to send it. The
  19289. // requests below carry the expectation but withhold the body, as a client
  19290. // waiting for `100 Continue` would.
  19291. // A POST that expects `100 Continue` and withholds its two-byte body.
  19292. static std::string expect_headers_only(const std::string &path) {
  19293. return "POST " + path +
  19294. " HTTP/1.1\r\n"
  19295. "Host: localhost\r\n"
  19296. "Content-Length: 2\r\n"
  19297. "Expect: 100-continue\r\n"
  19298. "\r\n";
  19299. }
  19300. class ExpectLazyContinueTest : public ::testing::Test {
  19301. protected:
  19302. void SetUp() override {
  19303. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19304. if (req.path == "/pre-routing") {
  19305. res.status = StatusCode::Unauthorized_401;
  19306. return Server::HandlerResponse::Handled;
  19307. }
  19308. return Server::HandlerResponse::Unhandled;
  19309. });
  19310. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19311. if (req.matched_route == "/pre-request") {
  19312. res.status = StatusCode::Forbidden_403;
  19313. return Server::HandlerResponse::Handled;
  19314. }
  19315. return Server::HandlerResponse::Unhandled;
  19316. });
  19317. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19318. res.set_content("ok", "text/plain");
  19319. });
  19320. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19321. res.set_content("ok", "text/plain");
  19322. });
  19323. svr_.Post("/reader-used", [](const Request &, Response &res,
  19324. const ContentReader &content_reader) {
  19325. std::string body;
  19326. content_reader([&](const char *data, size_t len) {
  19327. body.append(data, len);
  19328. return true;
  19329. });
  19330. res.set_content(body, "text/plain");
  19331. });
  19332. svr_.Post("/reader-unused",
  19333. [](const Request &, Response &res, const ContentReader &) {
  19334. res.set_content("ignored", "text/plain");
  19335. });
  19336. port_ = svr_.bind_to_any_port(HOST);
  19337. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19338. svr_.wait_until_ready();
  19339. }
  19340. void TearDown() override {
  19341. svr_.stop();
  19342. if (thread_.joinable()) { thread_.join(); }
  19343. }
  19344. // Sends `req` and reads until the server closes the connection. Returns
  19345. // false if the read had to wait for the client-side timeout instead.
  19346. bool send_until_closed(const std::string &req, std::string *resp) const {
  19347. auto start = std::chrono::steady_clock::now();
  19348. if (!send_request(3, req, resp, port_)) { return false; }
  19349. auto elapsed = std::chrono::steady_clock::now() - start;
  19350. return elapsed < std::chrono::seconds(2);
  19351. }
  19352. // The final response comes without `100 Continue`, and the server closes
  19353. // the connection since the body may or may not follow.
  19354. void expect_final_without_interim(const std::string &path,
  19355. const char *status_line) const {
  19356. std::string resp;
  19357. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19358. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19359. EXPECT_EQ(0u, resp.find(status_line));
  19360. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19361. }
  19362. Server svr_;
  19363. int port_ = 0;
  19364. thread thread_;
  19365. };
  19366. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19367. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19368. }
  19369. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19370. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19371. }
  19372. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19373. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19374. }
  19375. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19376. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19377. }
  19378. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19379. // The body follows once `100 Continue` has had time to arrive.
  19380. auto req = expect_headers_only("/reader-used");
  19381. req.insert(req.size() - 2, "Connection: close\r\n");
  19382. std::string resp;
  19383. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19384. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19385. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19386. EXPECT_NE(std::string::npos, resp.find("hi"));
  19387. }
  19388. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19389. // Large enough for the client to add `Expect: 100-continue` itself.
  19390. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19391. std::atomic<bool> body_sent{false};
  19392. Client cli(HOST, port_);
  19393. auto res = cli.Post(
  19394. "/pre-request", length,
  19395. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19396. body_sent = true;
  19397. std::string chunk(len, 'x');
  19398. sink.write(chunk.data(), chunk.size());
  19399. return true;
  19400. },
  19401. "application/octet-stream");
  19402. ASSERT_TRUE(res);
  19403. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19404. EXPECT_FALSE(body_sent);
  19405. }
  19406. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19407. Server svr;
  19408. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19409. return StatusCode::ExpectationFailed_417;
  19410. });
  19411. svr.Post("/p", [](const Request &, Response &res) {
  19412. res.set_content("ok", "text/plain");
  19413. });
  19414. auto port = svr.bind_to_any_port(HOST);
  19415. thread t = thread([&] { svr.listen_after_bind(); });
  19416. auto se = detail::scope_exit([&] {
  19417. svr.stop();
  19418. t.join();
  19419. });
  19420. svr.wait_until_ready();
  19421. std::string resp;
  19422. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19423. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19424. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19425. // Exactly one response: the route handler must not run after the 417.
  19426. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19427. }
  19428. #ifndef _WIN32
  19429. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19430. static constexpr char reject[] = "Unauthorized";
  19431. static constexpr char accept[] = "Upload accepted";
  19432. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19433. Server svr;
  19434. svr.set_expect_100_continue_handler(
  19435. [](const Request & /*req*/, Response &res) {
  19436. res.status = StatusCode::Unauthorized_401;
  19437. res.set_content(reject, "text/plain");
  19438. return res.status;
  19439. });
  19440. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19441. res.set_content(accept, "text/plain");
  19442. });
  19443. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19444. auto se = detail::scope_exit([&] {
  19445. svr.stop();
  19446. thread.join();
  19447. ASSERT_FALSE(svr.is_running());
  19448. });
  19449. svr.wait_until_ready();
  19450. {
  19451. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19452. curl_easy_init(), &curl_easy_cleanup};
  19453. ASSERT_NE(curl, nullptr);
  19454. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19455. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19456. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19457. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19458. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19459. &curl_slist_free_all};
  19460. ASSERT_NE(list, nullptr);
  19461. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19462. struct read_data {
  19463. uint64_t read_size;
  19464. uint64_t total_size;
  19465. } data = {0, total_size};
  19466. using read_callback_t =
  19467. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19468. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19469. void *userdata) -> size_t {
  19470. read_data *d = (read_data *)userdata;
  19471. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19472. std::fill_n(ptr, size * nmemb, 'A');
  19473. d->read_size += size * nmemb;
  19474. return size * nmemb;
  19475. };
  19476. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19477. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19478. std::vector<char> buffer;
  19479. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19480. using write_callback_t =
  19481. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19482. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19483. void *userdata) -> size_t {
  19484. std::vector<char> *buf = (std::vector<char> *)userdata;
  19485. buf->reserve(buf->size() + size * nmemb + 1);
  19486. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19487. return size * nmemb;
  19488. };
  19489. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19490. {
  19491. const auto res = curl_easy_perform(curl.get());
  19492. ASSERT_EQ(res, CURLE_OK);
  19493. }
  19494. {
  19495. auto response_code = long{};
  19496. const auto res =
  19497. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19498. ASSERT_EQ(res, CURLE_OK);
  19499. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19500. }
  19501. {
  19502. auto dl = curl_off_t{};
  19503. const auto res =
  19504. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19505. ASSERT_EQ(res, CURLE_OK);
  19506. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19507. }
  19508. {
  19509. buffer.push_back('\0');
  19510. ASSERT_STRCASEEQ(buffer.data(), reject);
  19511. }
  19512. }
  19513. }
  19514. #endif
  19515. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19516. // Regression test for #2458.
  19517. //
  19518. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19519. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19520. // ticket can make the client socket spuriously readable during the
  19521. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19522. // the client withholds the body and then blocks reading a response that never
  19523. // comes, failing with `Failed to read connection`.
  19524. //
  19525. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19526. // within the timeout. This raw OpenSSL server deliberately never sends
  19527. // `100 Continue`; the client must still deliver the body and receive 200.
  19528. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19529. signal(SIGPIPE, SIG_IGN);
  19530. const auto port = PORT + 4;
  19531. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19532. ASSERT_NE(srv, INVALID_SOCKET);
  19533. int opt = 1;
  19534. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19535. sockaddr_in addr{};
  19536. addr.sin_family = AF_INET;
  19537. addr.sin_port = htons(static_cast<uint16_t>(port));
  19538. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19539. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19540. ASSERT_EQ(0, ::listen(srv, 1));
  19541. std::atomic<size_t> server_body_bytes{0};
  19542. auto server_thread = std::thread([&] {
  19543. sockaddr_in cli_addr{};
  19544. socklen_t cli_len = sizeof(cli_addr);
  19545. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19546. if (cli == INVALID_SOCKET) { return; }
  19547. // Bound the lifetime of the server side so a buggy client (which never
  19548. // sends the body) cannot make this thread block forever on join.
  19549. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19550. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19551. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19552. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19553. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19554. SSL *ssl = SSL_new(ctx);
  19555. SSL_set_fd(ssl, static_cast<int>(cli));
  19556. if (SSL_accept(ssl) > 0) {
  19557. // Read the request headers. Reading here also flushes the TLS 1.3
  19558. // session tickets to the client. Deliberately do NOT send
  19559. // `100 Continue`.
  19560. std::string buf;
  19561. char tmp[1024];
  19562. while (buf.find("\r\n\r\n") == std::string::npos) {
  19563. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19564. if (n <= 0) { break; }
  19565. buf.append(tmp, static_cast<size_t>(n));
  19566. }
  19567. // A correct client sends the body now; count what arrives.
  19568. auto pos = buf.find("\r\n\r\n");
  19569. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19570. while (body < 4096) {
  19571. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19572. if (n <= 0) { break; }
  19573. body += static_cast<size_t>(n);
  19574. }
  19575. server_body_bytes = body;
  19576. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19577. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19578. SSL_shutdown(ssl);
  19579. }
  19580. SSL_free(ssl);
  19581. detail::close_socket(cli);
  19582. SSL_CTX_free(ctx);
  19583. });
  19584. auto se = detail::scope_exit([&] {
  19585. server_thread.join();
  19586. detail::close_socket(srv);
  19587. });
  19588. SSLClient cli("127.0.0.1", port);
  19589. cli.enable_server_certificate_verification(false);
  19590. cli.set_connection_timeout(5, 0);
  19591. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19592. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19593. std::string body(4096, 'A');
  19594. auto res = cli.Put("/api/test", body, "application/json");
  19595. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19596. EXPECT_EQ(StatusCode::OK_200, res->status);
  19597. EXPECT_EQ(body.size(), server_body_bytes.load());
  19598. }
  19599. #endif
  19600. template <typename S, typename C>
  19601. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19602. svr.Get("/stream", [&](const Request &, Response &res) {
  19603. auto data = new std::string("01234567890123456789");
  19604. res.set_content_provider(
  19605. data->size(), "text/plain",
  19606. [&, data](size_t offset, size_t length, DataSink &sink) {
  19607. const size_t DATA_CHUNK_SIZE = 4;
  19608. const auto &d = *data;
  19609. std::this_thread::sleep_for(std::chrono::seconds(1));
  19610. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19611. return true;
  19612. },
  19613. [data](bool success) {
  19614. EXPECT_FALSE(success);
  19615. delete data;
  19616. });
  19617. });
  19618. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19619. auto i = new size_t(0);
  19620. res.set_content_provider(
  19621. "text/plain",
  19622. [i](size_t, DataSink &sink) {
  19623. if (*i < 5) {
  19624. std::this_thread::sleep_for(std::chrono::seconds(1));
  19625. sink.write("abcd", 4);
  19626. (*i)++;
  19627. } else {
  19628. sink.done();
  19629. }
  19630. return true;
  19631. },
  19632. [i](bool success) {
  19633. EXPECT_FALSE(success);
  19634. delete i;
  19635. });
  19636. });
  19637. svr.Get("/chunked", [&](const Request &, Response &res) {
  19638. auto i = new size_t(0);
  19639. res.set_chunked_content_provider(
  19640. "text/plain",
  19641. [i](size_t, DataSink &sink) {
  19642. if (*i < 5) {
  19643. std::this_thread::sleep_for(std::chrono::seconds(1));
  19644. sink.os << "abcd";
  19645. (*i)++;
  19646. } else {
  19647. sink.done();
  19648. }
  19649. return true;
  19650. },
  19651. [i](bool success) {
  19652. EXPECT_FALSE(success);
  19653. delete i;
  19654. });
  19655. });
  19656. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19657. auto se = detail::scope_exit([&] {
  19658. svr.stop();
  19659. listen_thread.join();
  19660. ASSERT_FALSE(svr.is_running());
  19661. });
  19662. svr.wait_until_ready();
  19663. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19664. {
  19665. auto start = std::chrono::steady_clock::now();
  19666. auto res = cli.Get("/stream");
  19667. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19668. std::chrono::steady_clock::now() - start)
  19669. .count();
  19670. ASSERT_FALSE(res);
  19671. EXPECT_EQ(Error::Read, res.error());
  19672. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19673. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19674. }
  19675. {
  19676. auto start = std::chrono::steady_clock::now();
  19677. auto res = cli.Get("/stream_without_length");
  19678. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19679. std::chrono::steady_clock::now() - start)
  19680. .count();
  19681. ASSERT_FALSE(res);
  19682. EXPECT_EQ(Error::Read, res.error());
  19683. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19684. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19685. }
  19686. {
  19687. auto start = std::chrono::steady_clock::now();
  19688. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19689. EXPECT_EQ("abcd", string(data, data_length));
  19690. return true;
  19691. });
  19692. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19693. std::chrono::steady_clock::now() - start)
  19694. .count();
  19695. ASSERT_FALSE(res);
  19696. EXPECT_EQ(Error::Read, res.error());
  19697. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19698. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19699. }
  19700. }
  19701. TEST(MaxTimeoutTest, ContentStream) {
  19702. time_t timeout = 2000;
  19703. time_t threshold = 200;
  19704. Server svr;
  19705. Client cli("localhost", PORT);
  19706. max_timeout_test(svr, cli, timeout, threshold);
  19707. }
  19708. #ifdef CPPHTTPLIB_SSL_ENABLED
  19709. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19710. time_t timeout = 2000;
  19711. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19712. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19713. SSLClient cli("localhost", PORT);
  19714. cli.enable_server_certificate_verification(false);
  19715. max_timeout_test(svr, cli, timeout, threshold);
  19716. }
  19717. #endif
  19718. class EventDispatcher {
  19719. public:
  19720. EventDispatcher() {}
  19721. bool wait_event(DataSink *sink) {
  19722. unique_lock<mutex> lk(m_);
  19723. int id = id_;
  19724. // Wait with timeout to prevent hanging if client disconnects
  19725. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19726. [&] { return cid_ == id; })) {
  19727. return false; // Timeout occurred
  19728. }
  19729. sink->write(message_.data(), message_.size());
  19730. return true;
  19731. }
  19732. void send_event(const string &message) {
  19733. lock_guard<mutex> lk(m_);
  19734. cid_ = id_++;
  19735. message_ = message;
  19736. cv_.notify_all();
  19737. }
  19738. private:
  19739. mutex m_;
  19740. condition_variable cv_;
  19741. atomic_int id_{0};
  19742. atomic_int cid_{-1};
  19743. string message_;
  19744. };
  19745. TEST(ClientInThreadTest, Issue2068) {
  19746. EventDispatcher ed;
  19747. Server svr;
  19748. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19749. res.set_chunked_content_provider("text/event-stream",
  19750. [&](size_t /*offset*/, DataSink &sink) {
  19751. return ed.wait_event(&sink);
  19752. });
  19753. });
  19754. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19755. svr.wait_until_ready();
  19756. thread event_thread([&] {
  19757. int id = 0;
  19758. while (svr.is_running()) {
  19759. this_thread::sleep_for(chrono::milliseconds(500));
  19760. std::stringstream ss;
  19761. ss << "data: " << id << "\n\n";
  19762. ed.send_event(ss.str());
  19763. id++;
  19764. }
  19765. });
  19766. auto se = detail::scope_exit([&] {
  19767. svr.stop();
  19768. listen_thread.join();
  19769. event_thread.join();
  19770. ASSERT_FALSE(svr.is_running());
  19771. });
  19772. {
  19773. auto client = detail::make_unique<Client>(HOST, PORT);
  19774. client->set_read_timeout(std::chrono::minutes(10));
  19775. std::atomic<bool> stop{false};
  19776. std::thread t([&] {
  19777. client->Get("/event1",
  19778. [&](const char *, size_t) -> bool { return !stop; });
  19779. });
  19780. std::this_thread::sleep_for(std::chrono::seconds(2));
  19781. stop = true;
  19782. client->stop();
  19783. t.join();
  19784. // Reset client after thread has finished
  19785. client.reset();
  19786. }
  19787. }
  19788. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19789. auto handled = false;
  19790. Server svr;
  19791. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19792. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19793. auto se = detail::scope_exit([&] {
  19794. svr.stop();
  19795. t.join();
  19796. ASSERT_FALSE(svr.is_running());
  19797. ASSERT_FALSE(handled);
  19798. });
  19799. svr.wait_until_ready();
  19800. // Two Content-Length headers with different values — must be rejected
  19801. auto req = "POST /test HTTP/1.1\r\n"
  19802. "Content-Length: 5\r\n"
  19803. "Content-Length: 10\r\n"
  19804. "\r\n"
  19805. "hello";
  19806. std::string response;
  19807. ASSERT_TRUE(send_request(1, req, &response));
  19808. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19809. response.substr(0, response.find("\r\n")));
  19810. }
  19811. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19812. auto handled = false;
  19813. Server svr;
  19814. svr.Post("/test", [&](const Request &, Response &res) {
  19815. handled = true;
  19816. res.set_content("ok", "text/plain");
  19817. });
  19818. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19819. auto se = detail::scope_exit([&] {
  19820. svr.stop();
  19821. t.join();
  19822. ASSERT_FALSE(svr.is_running());
  19823. ASSERT_TRUE(handled);
  19824. });
  19825. svr.wait_until_ready();
  19826. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19827. auto req = "POST /test HTTP/1.1\r\n"
  19828. "Host: localhost\r\n"
  19829. "Content-Length: 5\r\n"
  19830. "Content-Length: 5\r\n"
  19831. "\r\n"
  19832. "hello";
  19833. std::string response;
  19834. ASSERT_TRUE(send_request(1, req, &response));
  19835. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19836. }
  19837. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19838. Server svr;
  19839. svr.Get("/test", [](const Request &, Response &res) {
  19840. res.set_content("ok", "text/plain");
  19841. });
  19842. auto port = svr.bind_to_any_port(HOST);
  19843. thread t = thread([&] { svr.listen_after_bind(); });
  19844. auto se = detail::scope_exit([&] {
  19845. svr.stop();
  19846. t.join();
  19847. ASSERT_FALSE(svr.is_running());
  19848. });
  19849. svr.wait_until_ready();
  19850. auto status_line = [&](const std::string &host_lines) {
  19851. std::string res;
  19852. send_request(
  19853. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19854. &res, port);
  19855. return res.substr(0, res.find("\r\n"));
  19856. };
  19857. const char *accepted[] = {
  19858. "Host: localhost\r\n",
  19859. "Host: a.example:8080\r\n",
  19860. "Host: my_service\r\n",
  19861. "Host: [::1]:8080\r\n",
  19862. "Host: [fe80::1%25eth0]\r\n",
  19863. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19864. };
  19865. for (auto host_lines : accepted) {
  19866. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19867. }
  19868. const char *rejected[] = {
  19869. "Host: a.example\r\nHost: b.example\r\n",
  19870. "Host: a.example\r\nHost: a.example\r\n",
  19871. "Host: a@b.example\r\n",
  19872. "Host: a.example/b\r\n",
  19873. "Host: a.example\\b\r\n",
  19874. "Host: a.example?b\r\n",
  19875. "Host: a.example#b\r\n",
  19876. "Host: a.example b.example\r\n",
  19877. };
  19878. for (auto host_lines : rejected) {
  19879. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19880. << host_lines;
  19881. }
  19882. }
  19883. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19884. Server svr;
  19885. svr.Get("/", [](const Request &req, Response &res) {
  19886. EXPECT_EQ(2U, req.trailers.size());
  19887. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19888. // Denied
  19889. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19890. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19891. // Accepted
  19892. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19893. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19894. EXPECT_TRUE(req.has_trailer("X-World"));
  19895. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19896. res.set_content("ok", "text/plain");
  19897. });
  19898. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19899. auto se = detail::scope_exit([&] {
  19900. svr.stop();
  19901. t.join();
  19902. ASSERT_FALSE(svr.is_running());
  19903. });
  19904. svr.wait_until_ready();
  19905. const std::string req = "GET / HTTP/1.1\r\n"
  19906. "Transfer-Encoding: chunked\r\n"
  19907. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19908. "\r\n"
  19909. "0\r\n"
  19910. "Content-Length: 10\r\n"
  19911. "Host: internal.local\r\n"
  19912. "Content-Type: malicious/content\r\n"
  19913. "Cookie: any\r\n"
  19914. "Set-Cookie: any\r\n"
  19915. "X-Forwarded-For: attacker.com\r\n"
  19916. "X-Real-Ip: 1.1.1.1\r\n"
  19917. "X-Hello: hello\r\n"
  19918. "X-World: world\r\n"
  19919. "\r\n";
  19920. std::string res;
  19921. ASSERT_TRUE(send_request(1, req, &res));
  19922. }
  19923. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19924. // several field lines, and the combined value is what has to be parsed. A
  19925. // Trailer field split across lines therefore declares every name it lists;
  19926. // reading only the first line silently drops the trailers the later lines
  19927. // declare. The prohibited-trailer filter still applies to every line.
  19928. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19929. Server svr;
  19930. size_t observed_trailer_count = 0;
  19931. std::string observed_hello;
  19932. std::string observed_world;
  19933. bool observed_content_length = true;
  19934. svr.Get("/", [&](const Request &req, Response &res) {
  19935. observed_trailer_count = req.trailers.size();
  19936. observed_hello = req.get_trailer_value("X-Hello");
  19937. observed_world = req.get_trailer_value("X-World");
  19938. observed_content_length = req.has_trailer("Content-Length");
  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. const std::string req = "GET / HTTP/1.1\r\n"
  19950. "Host: localhost\r\n"
  19951. "Transfer-Encoding: chunked\r\n"
  19952. "Trailer: X-Hello\r\n"
  19953. "Trailer: X-World, Content-Length\r\n"
  19954. "\r\n"
  19955. "0\r\n"
  19956. "X-Hello: hello\r\n"
  19957. "X-World: world\r\n"
  19958. "Content-Length: 10\r\n"
  19959. "\r\n";
  19960. std::string res;
  19961. ASSERT_TRUE(send_request(1, req, &res, port));
  19962. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19963. // Accepted: both field lines contribute to the declared set
  19964. EXPECT_EQ(2U, observed_trailer_count);
  19965. EXPECT_EQ(observed_hello, "hello");
  19966. EXPECT_EQ(observed_world, "world");
  19967. // Denied: a prohibited name stays prohibited on a later field line
  19968. EXPECT_FALSE(observed_content_length);
  19969. }
  19970. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19971. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19972. // unbounded run of fields that are never declared, because the counter would
  19973. // only advance for declared fields.
  19974. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19975. Server svr;
  19976. bool handler_called = false;
  19977. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19978. handler_called = true;
  19979. res.set_content("ok", "text/plain");
  19980. });
  19981. auto port = svr.bind_to_any_port(HOST);
  19982. thread t = thread([&]() { svr.listen_after_bind(); });
  19983. auto se = detail::scope_exit([&] {
  19984. svr.stop();
  19985. t.join();
  19986. ASSERT_FALSE(svr.is_running());
  19987. });
  19988. svr.wait_until_ready();
  19989. // Declare nothing, then send far more undeclared trailer fields than the
  19990. // header-count limit. Parsing must stop and reject the request rather than
  19991. // read every line.
  19992. std::string req = "GET / HTTP/1.1\r\n"
  19993. "Transfer-Encoding: chunked\r\n"
  19994. "\r\n"
  19995. "0\r\n";
  19996. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19997. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19998. }
  19999. req += "\r\n";
  20000. std::string res;
  20001. ASSERT_TRUE(send_request(1, req, &res, port));
  20002. // The request is rejected before the handler runs.
  20003. EXPECT_FALSE(handler_called);
  20004. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  20005. }
  20006. // The set of declared trailer names is capped so a peer cannot grow it without
  20007. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  20008. // declared past the cap is not honored, even if the field is actually sent.
  20009. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  20010. Server svr;
  20011. // One name inside the cap and one past it, so the test tracks the cap rather
  20012. // than a fixed count.
  20013. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  20014. const std::string within_cap_name = "X-T-0";
  20015. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  20016. bool observed_within_cap = false;
  20017. bool observed_past_cap = false;
  20018. svr.Get("/", [&](const Request &req, Response &res) {
  20019. observed_within_cap = req.has_trailer(within_cap_name);
  20020. observed_past_cap = req.has_trailer(past_cap_name);
  20021. res.set_content("ok", "text/plain");
  20022. });
  20023. auto port = svr.bind_to_any_port(HOST);
  20024. thread t = thread([&]() { svr.listen_after_bind(); });
  20025. auto se = detail::scope_exit([&] {
  20026. svr.stop();
  20027. t.join();
  20028. ASSERT_FALSE(svr.is_running());
  20029. });
  20030. svr.wait_until_ready();
  20031. // Declare more trailer names than the cap in a single Trailer field, then
  20032. // actually send the first (within the cap) and the last (past it).
  20033. std::string trailer_decl = "Trailer: ";
  20034. for (int i = 0; i < declared_count; i++) {
  20035. if (i != 0) { trailer_decl += ", "; }
  20036. trailer_decl += "X-T-" + std::to_string(i);
  20037. }
  20038. trailer_decl += "\r\n";
  20039. const std::string req = "GET / HTTP/1.1\r\n"
  20040. "Host: localhost\r\n"
  20041. "Transfer-Encoding: chunked\r\n" +
  20042. trailer_decl +
  20043. "\r\n"
  20044. "0\r\n" +
  20045. within_cap_name + ": a\r\n" + past_cap_name +
  20046. ": b\r\n"
  20047. "\r\n";
  20048. std::string res;
  20049. ASSERT_TRUE(send_request(1, req, &res, port));
  20050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  20051. // A name within the cap is honored; one declared past the cap is dropped.
  20052. EXPECT_TRUE(observed_within_cap);
  20053. EXPECT_FALSE(observed_past_cap);
  20054. }
  20055. // A direct client that is not listed in trusted_proxies must not be able to
  20056. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20057. // the peer address on the actual TCP connection determines whether the
  20058. // header is honored.
  20059. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20060. Server svr;
  20061. // Deliberately does NOT include the loopback address the test client
  20062. // actually connects from, so the direct connection is not a trusted proxy.
  20063. svr.set_trusted_proxies({"203.0.113.66"});
  20064. std::string observed_remote_addr;
  20065. svr.Get("/ip", [&](const Request &req, Response &res) {
  20066. observed_remote_addr = req.remote_addr;
  20067. res.set_content("ok", "text/plain");
  20068. });
  20069. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20070. auto se = detail::scope_exit([&] {
  20071. svr.stop();
  20072. t.join();
  20073. ASSERT_FALSE(svr.is_running());
  20074. });
  20075. svr.wait_until_ready();
  20076. Client cli(HOST, PORT);
  20077. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20078. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20079. EXPECT_EQ(StatusCode::OK_200, res->status);
  20080. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20081. // ignored entirely and the real connection-level address retained.
  20082. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20083. observed_remote_addr == "127.0.0.1");
  20084. }
  20085. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20086. Server svr;
  20087. std::string observed_remote_addr;
  20088. std::string observed_xff;
  20089. svr.Get("/ip", [&](const Request &req, Response &res) {
  20090. observed_remote_addr = req.remote_addr;
  20091. observed_xff = req.get_header_value("X-Forwarded-For");
  20092. res.set_content("ok", "text/plain");
  20093. });
  20094. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20095. auto se = detail::scope_exit([&] {
  20096. svr.stop();
  20097. t.join();
  20098. ASSERT_FALSE(svr.is_running());
  20099. });
  20100. svr.wait_until_ready();
  20101. Client cli(HOST, PORT);
  20102. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20104. EXPECT_EQ(StatusCode::OK_200, res->status);
  20105. EXPECT_EQ(observed_xff, "203.0.113.66");
  20106. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20107. observed_remote_addr == "127.0.0.1");
  20108. }
  20109. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20110. Server svr;
  20111. svr.set_trusted_proxies({"203.0.113.66"});
  20112. std::string observed_remote_addr;
  20113. std::string observed_xff;
  20114. svr.Get("/ip", [&](const Request &req, Response &res) {
  20115. observed_remote_addr = req.remote_addr;
  20116. observed_xff = req.get_header_value("X-Forwarded-For");
  20117. res.set_content("ok", "text/plain");
  20118. });
  20119. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20120. auto se = detail::scope_exit([&] {
  20121. svr.stop();
  20122. t.join();
  20123. ASSERT_FALSE(svr.is_running());
  20124. });
  20125. svr.wait_until_ready();
  20126. Client cli(HOST, PORT);
  20127. auto res = cli.Get("/ip");
  20128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20129. EXPECT_EQ(StatusCode::OK_200, res->status);
  20130. EXPECT_EQ(observed_xff, "");
  20131. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20132. observed_remote_addr == "127.0.0.1");
  20133. }
  20134. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20135. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20136. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20137. Server svr;
  20138. svr.set_trusted_proxies({"127.0.0.1"});
  20139. svr.Get("/ip", [](const Request &req, Response &res) {
  20140. res.set_content(req.remote_addr, "text/plain");
  20141. });
  20142. auto port = svr.bind_to_any_port("::");
  20143. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20144. thread t = thread([&] { svr.listen_after_bind(); });
  20145. auto se = detail::scope_exit([&] {
  20146. svr.stop();
  20147. t.join();
  20148. ASSERT_FALSE(svr.is_running());
  20149. });
  20150. svr.wait_until_ready();
  20151. Client cli("127.0.0.1", port);
  20152. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20154. EXPECT_EQ("198.51.100.23", res->body);
  20155. }
  20156. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20157. Server svr;
  20158. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20159. svr.Get("/ip", [](const Request &req, Response &res) {
  20160. res.set_content(req.remote_addr, "text/plain");
  20161. });
  20162. auto port = svr.bind_to_any_port(HOST);
  20163. ASSERT_GT(port, 0);
  20164. thread t = thread([&] { svr.listen_after_bind(); });
  20165. auto se = detail::scope_exit([&] {
  20166. svr.stop();
  20167. t.join();
  20168. ASSERT_FALSE(svr.is_running());
  20169. });
  20170. svr.wait_until_ready();
  20171. Client cli(HOST, port);
  20172. auto res = cli.Get(
  20173. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20175. EXPECT_EQ("198.51.100.23", res->body);
  20176. }
  20177. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20178. Server svr;
  20179. // Include the loopback address the test client actually connects from, so
  20180. // the direct connection itself is recognized as the trusted proxy hop.
  20181. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20182. std::string observed_remote_addr;
  20183. std::string observed_xff;
  20184. svr.Get("/ip", [&](const Request &req, Response &res) {
  20185. observed_remote_addr = req.remote_addr;
  20186. observed_xff = req.get_header_value("X-Forwarded-For");
  20187. res.set_content("ok", "text/plain");
  20188. });
  20189. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20190. auto se = detail::scope_exit([&] {
  20191. svr.stop();
  20192. t.join();
  20193. ASSERT_FALSE(svr.is_running());
  20194. });
  20195. svr.wait_until_ready();
  20196. Client cli(HOST, PORT);
  20197. auto res = cli.Get(
  20198. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20200. EXPECT_EQ(StatusCode::OK_200, res->status);
  20201. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20202. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20203. }
  20204. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20205. Server svr;
  20206. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20207. std::string observed_remote_addr;
  20208. std::string observed_xff;
  20209. svr.Get("/ip", [&](const Request &req, Response &res) {
  20210. observed_remote_addr = req.remote_addr;
  20211. observed_xff = req.get_header_value("X-Forwarded-For");
  20212. res.set_content("ok", "text/plain");
  20213. });
  20214. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20215. auto se = detail::scope_exit([&] {
  20216. svr.stop();
  20217. t.join();
  20218. ASSERT_FALSE(svr.is_running());
  20219. });
  20220. svr.wait_until_ready();
  20221. Client cli(HOST, PORT);
  20222. auto res = cli.Get(
  20223. "/ip",
  20224. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20226. EXPECT_EQ(StatusCode::OK_200, res->status);
  20227. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20228. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20229. }
  20230. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20231. Server svr;
  20232. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20233. std::string observed_remote_addr;
  20234. std::string observed_xff;
  20235. svr.Get("/ip", [&](const Request &req, Response &res) {
  20236. observed_remote_addr = req.remote_addr;
  20237. observed_xff = req.get_header_value("X-Forwarded-For");
  20238. res.set_content("ok", "text/plain");
  20239. });
  20240. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20241. auto se = detail::scope_exit([&] {
  20242. svr.stop();
  20243. t.join();
  20244. ASSERT_FALSE(svr.is_running());
  20245. });
  20246. svr.wait_until_ready();
  20247. Client cli(HOST, PORT);
  20248. auto res = cli.Get(
  20249. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20251. EXPECT_EQ(StatusCode::OK_200, res->status);
  20252. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20253. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20254. // and must not be selected.
  20255. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20256. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20257. }
  20258. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20259. Server svr;
  20260. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20261. std::string observed_remote_addr;
  20262. svr.Get("/ip", [&](const Request &req, Response &res) {
  20263. observed_remote_addr = req.remote_addr;
  20264. res.set_content("ok", "text/plain");
  20265. });
  20266. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20267. auto se = detail::scope_exit([&] {
  20268. svr.stop();
  20269. t.join();
  20270. ASSERT_FALSE(svr.is_running());
  20271. });
  20272. svr.wait_until_ready();
  20273. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20274. // a forged address and the trusted proxy's own address; the forged value must
  20275. // not win over the address the trusted proxy actually recorded.
  20276. Client cli(HOST, PORT);
  20277. auto res = cli.Get(
  20278. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20280. EXPECT_EQ(StatusCode::OK_200, res->status);
  20281. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20282. }
  20283. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20284. Server svr;
  20285. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20286. std::string observed_remote_addr;
  20287. std::string observed_xff;
  20288. svr.Get("/ip", [&](const Request &req, Response &res) {
  20289. observed_remote_addr = req.remote_addr;
  20290. observed_xff = req.get_header_value("X-Forwarded-For");
  20291. res.set_content("ok", "text/plain");
  20292. });
  20293. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20294. auto se = detail::scope_exit([&] {
  20295. svr.stop();
  20296. t.join();
  20297. ASSERT_FALSE(svr.is_running());
  20298. });
  20299. svr.wait_until_ready();
  20300. Client cli(HOST, PORT);
  20301. auto res = cli.Get(
  20302. "/ip",
  20303. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20305. EXPECT_EQ(StatusCode::OK_200, res->status);
  20306. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20307. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20308. }
  20309. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20310. Server svr;
  20311. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20312. std::string observed_remote_addr;
  20313. std::string observed_xff;
  20314. svr.Get("/ip", [&](const Request &req, Response &res) {
  20315. observed_remote_addr = req.remote_addr;
  20316. observed_xff = req.get_header_value("X-Forwarded-For");
  20317. res.set_content("ok", "text/plain");
  20318. });
  20319. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20320. auto se = detail::scope_exit([&] {
  20321. svr.stop();
  20322. t.join();
  20323. ASSERT_FALSE(svr.is_running());
  20324. });
  20325. svr.wait_until_ready();
  20326. std::string raw_req =
  20327. "GET /ip HTTP/1.1\r\n"
  20328. "Host: localhost\r\n"
  20329. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20330. "Connection: close\r\n"
  20331. "\r\n";
  20332. std::string out;
  20333. ASSERT_TRUE(send_request(5, raw_req, &out));
  20334. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20335. // Header parser trims surrounding whitespace of the header value
  20336. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20337. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20338. }
  20339. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20340. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20341. // their own X-Forwarded-For as a separate field line rather than extending the
  20342. // one the client sent, so every occurrence has to be taken into account.
  20343. // Reading only the first one hands back the address the client chose.
  20344. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20345. Server svr;
  20346. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20347. std::string observed_remote_addr;
  20348. size_t observed_xff_count = 0;
  20349. svr.Get("/ip", [&](const Request &req, Response &res) {
  20350. observed_remote_addr = req.remote_addr;
  20351. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20352. res.set_content("ok", "text/plain");
  20353. });
  20354. auto port = svr.bind_to_any_port(HOST);
  20355. thread t = thread([&]() { svr.listen_after_bind(); });
  20356. auto se = detail::scope_exit([&] {
  20357. svr.stop();
  20358. t.join();
  20359. ASSERT_FALSE(svr.is_running());
  20360. });
  20361. svr.wait_until_ready();
  20362. // The client supplies the first field line; the trusted proxy appends the
  20363. // address it observed as a second one.
  20364. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20365. "Host: localhost\r\n"
  20366. "X-Forwarded-For: 1.2.3.4\r\n"
  20367. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20368. "Connection: close\r\n"
  20369. "\r\n";
  20370. std::string out;
  20371. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20372. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20373. EXPECT_EQ(observed_xff_count, 2U);
  20374. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20375. // The same chain spread over one field line per hop derives the same client
  20376. // address, i.e. the split and the comma-joined representations agree.
  20377. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20378. "Host: localhost\r\n"
  20379. "X-Forwarded-For: 1.2.3.4\r\n"
  20380. "X-Forwarded-For: 198.51.100.23\r\n"
  20381. "X-Forwarded-For: 192.0.2.45\r\n"
  20382. "Connection: close\r\n"
  20383. "\r\n";
  20384. out.clear();
  20385. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20386. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20387. EXPECT_EQ(observed_xff_count, 3U);
  20388. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20389. }
  20390. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20391. // crash the server (it used to call front() on an empty vector inside
  20392. // get_client_ip). The connection-level remote address must be retained instead.
  20393. static void run_malformed_xff_test(const std::string &xff_value) {
  20394. Server svr;
  20395. svr.set_trusted_proxies({"192.0.2.45"});
  20396. std::string observed_remote_addr;
  20397. svr.Get("/ip", [&](const Request &req, Response &res) {
  20398. observed_remote_addr = req.remote_addr;
  20399. res.set_content("ok", "text/plain");
  20400. });
  20401. int port = 0;
  20402. thread t = thread([&]() {
  20403. port = svr.bind_to_any_port(HOST);
  20404. svr.listen_after_bind();
  20405. });
  20406. auto se = detail::scope_exit([&] {
  20407. svr.stop();
  20408. t.join();
  20409. ASSERT_FALSE(svr.is_running());
  20410. });
  20411. svr.wait_until_ready();
  20412. Client cli(HOST, port);
  20413. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20415. EXPECT_EQ(StatusCode::OK_200, res->status);
  20416. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20417. observed_remote_addr == "127.0.0.1");
  20418. }
  20419. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20420. run_malformed_xff_test("");
  20421. }
  20422. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20423. run_malformed_xff_test(",");
  20424. }
  20425. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20426. run_malformed_xff_test(", , ,");
  20427. }
  20428. // The same rule applies to Accept: a request whose acceptable types are spread
  20429. // over several field lines must be negotiated against all of them.
  20430. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20431. // case-insensitive connection options. Comparing the whole field value against
  20432. // one option misses a client that sends several of them, and misses every
  20433. // casing but the one written in the comparison.
  20434. //
  20435. // Sends req, reads the response, then reuses the same socket for a second
  20436. // request to find out whether the server kept the connection.
  20437. static void probe_connection_reuse(int port, const std::string &req,
  20438. bool *announced_close, bool *reusable) {
  20439. auto error = Error::Success;
  20440. auto sock = detail::create_client_socket(
  20441. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20442. /*connection_timeout_sec=*/5, 0,
  20443. /*read_timeout_sec=*/1, 0,
  20444. /*write_timeout_sec=*/5, 0, std::string(), error);
  20445. ASSERT_NE(sock, INVALID_SOCKET);
  20446. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20447. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20448. "Host: localhost\r\n"
  20449. "Connection: close\r\n"
  20450. "\r\n";
  20451. std::string first_response;
  20452. std::string second_response;
  20453. detail::process_client_socket(
  20454. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20455. [&](Stream &strm) {
  20456. if (strm.write(req.data(), req.size()) !=
  20457. static_cast<ssize_t>(req.size())) {
  20458. return false;
  20459. }
  20460. char buf[512];
  20461. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20462. // Headers plus the two-byte body of the handler below
  20463. while (reader.getline()) {
  20464. first_response += reader.ptr();
  20465. if (first_response.find("ok") != std::string::npos) { break; }
  20466. }
  20467. if (strm.write(second.data(), second.size()) !=
  20468. static_cast<ssize_t>(second.size())) {
  20469. return true;
  20470. }
  20471. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20472. while (reader2.getline()) {
  20473. second_response += reader2.ptr();
  20474. if (second_response.find("ok") != std::string::npos) { break; }
  20475. }
  20476. return true;
  20477. });
  20478. *announced_close =
  20479. first_response.find("Connection: close") != std::string::npos;
  20480. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20481. }
  20482. class ConnectionTokenTest : public ::testing::Test {
  20483. protected:
  20484. void SetUp() override {
  20485. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20486. res.set_content("ok", "text/plain");
  20487. });
  20488. port_ = svr_.bind_to_any_port(HOST);
  20489. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20490. svr_.wait_until_ready();
  20491. }
  20492. void TearDown() override {
  20493. svr_.stop();
  20494. if (thread_.joinable()) { thread_.join(); }
  20495. }
  20496. Server svr_;
  20497. int port_ = 0;
  20498. thread thread_;
  20499. };
  20500. // "close" alongside another option still closes the connection, and the
  20501. // response says so rather than leaving the peer to discover it.
  20502. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20503. bool announced_close = false;
  20504. bool reusable = true;
  20505. probe_connection_reuse(port_,
  20506. "GET /keepalive HTTP/1.1\r\n"
  20507. "Host: localhost\r\n"
  20508. "Connection: keep-alive, close\r\n"
  20509. "\r\n",
  20510. &announced_close, &reusable);
  20511. EXPECT_TRUE(announced_close);
  20512. EXPECT_FALSE(reusable);
  20513. }
  20514. // "close" split over two field lines is the same list, so it is honored too.
  20515. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20516. bool announced_close = false;
  20517. bool reusable = true;
  20518. probe_connection_reuse(port_,
  20519. "GET /keepalive HTTP/1.1\r\n"
  20520. "Host: localhost\r\n"
  20521. "Connection: keep-alive\r\n"
  20522. "Connection: close\r\n"
  20523. "\r\n",
  20524. &announced_close, &reusable);
  20525. EXPECT_TRUE(announced_close);
  20526. EXPECT_FALSE(reusable);
  20527. }
  20528. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20529. // keep-alive in the spelling everyone actually sends keeps its connection.
  20530. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20531. bool announced_close = false;
  20532. bool reusable = false;
  20533. probe_connection_reuse(port_,
  20534. "GET /keepalive HTTP/1.0\r\n"
  20535. "Host: localhost\r\n"
  20536. "Connection: keep-alive\r\n"
  20537. "\r\n",
  20538. &announced_close, &reusable);
  20539. EXPECT_FALSE(announced_close);
  20540. EXPECT_TRUE(reusable);
  20541. }
  20542. // A token the value merely contains is not the token itself.
  20543. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20544. bool announced_close = false;
  20545. bool reusable = false;
  20546. probe_connection_reuse(port_,
  20547. "GET /keepalive HTTP/1.1\r\n"
  20548. "Host: localhost\r\n"
  20549. "Connection: notclose\r\n"
  20550. "\r\n",
  20551. &announced_close, &reusable);
  20552. EXPECT_FALSE(announced_close);
  20553. EXPECT_TRUE(reusable);
  20554. }
  20555. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20556. Server svr;
  20557. std::vector<std::string> observed_types;
  20558. svr.Get("/", [&](const Request &req, Response &res) {
  20559. observed_types = req.accept_content_types;
  20560. res.set_content("ok", "text/plain");
  20561. });
  20562. auto port = svr.bind_to_any_port(HOST);
  20563. thread t = thread([&]() { svr.listen_after_bind(); });
  20564. auto se = detail::scope_exit([&] {
  20565. svr.stop();
  20566. t.join();
  20567. ASSERT_FALSE(svr.is_running());
  20568. });
  20569. svr.wait_until_ready();
  20570. Client cli(HOST, port);
  20571. Headers headers;
  20572. headers.emplace("Accept", "text/plain;q=0.5");
  20573. headers.emplace("Accept", "application/json");
  20574. auto res = cli.Get("/", headers);
  20575. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20576. EXPECT_EQ(StatusCode::OK_200, res->status);
  20577. // Sorted by q-value, so the second field line's type comes first
  20578. ASSERT_EQ(2U, observed_types.size());
  20579. EXPECT_EQ("application/json", observed_types[0]);
  20580. EXPECT_EQ("text/plain", observed_types[1]);
  20581. }
  20582. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20583. // empty field line must not contribute a bare comma to the combined value.
  20584. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20585. Server svr;
  20586. std::vector<std::string> observed_types;
  20587. svr.Get("/", [&](const Request &req, Response &res) {
  20588. observed_types = req.accept_content_types;
  20589. res.set_content("ok", "text/plain");
  20590. });
  20591. auto port = svr.bind_to_any_port(HOST);
  20592. thread t = thread([&]() { svr.listen_after_bind(); });
  20593. auto se = detail::scope_exit([&] {
  20594. svr.stop();
  20595. t.join();
  20596. ASSERT_FALSE(svr.is_running());
  20597. });
  20598. svr.wait_until_ready();
  20599. // Empty first field line, then a real one
  20600. std::string raw_req = "GET / HTTP/1.1\r\n"
  20601. "Host: localhost\r\n"
  20602. "Accept:\r\n"
  20603. "Accept: application/json\r\n"
  20604. "Connection: close\r\n"
  20605. "\r\n";
  20606. std::string out;
  20607. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20608. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20609. ASSERT_EQ(1U, observed_types.size());
  20610. EXPECT_EQ("application/json", observed_types[0]);
  20611. }
  20612. // The skip in get_combined_header_value() is what keeps an empty field line
  20613. // from contributing a bare comma. Only a trailing empty field line exercises
  20614. // it: a leading one is already covered by the "combined is still empty" check,
  20615. // and parse_accept_header() now ignores the empty element either way, so the
  20616. // request-level test above can no longer tell the two apart.
  20617. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20618. Headers headers;
  20619. headers.emplace("Accept", "text/html");
  20620. headers.emplace("Accept", "");
  20621. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20622. headers.clear();
  20623. headers.emplace("Accept", "");
  20624. headers.emplace("Accept", "application/json");
  20625. EXPECT_EQ("application/json",
  20626. detail::get_combined_header_value(headers, "Accept"));
  20627. }
  20628. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20629. // An encoding offered on a later Accept-Encoding field line is still offered.
  20630. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20631. Server svr;
  20632. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20633. res.set_content(std::string(1024, 'x'), "text/plain");
  20634. });
  20635. auto port = svr.bind_to_any_port(HOST);
  20636. thread t = thread([&]() { svr.listen_after_bind(); });
  20637. auto se = detail::scope_exit([&] {
  20638. svr.stop();
  20639. t.join();
  20640. ASSERT_FALSE(svr.is_running());
  20641. });
  20642. svr.wait_until_ready();
  20643. Client cli(HOST, port);
  20644. cli.set_decompress(false);
  20645. Headers headers;
  20646. headers.emplace("Accept-Encoding", "identity");
  20647. headers.emplace("Accept-Encoding", "gzip");
  20648. auto res = cli.Get("/", headers);
  20649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20650. EXPECT_EQ(StatusCode::OK_200, res->status);
  20651. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20652. }
  20653. #endif
  20654. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20655. // Transfer-Encoding is not its body.
  20656. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20657. Server svr;
  20658. svr.set_payload_max_length(8);
  20659. svr.Post("/test", [](const Request &, Response &res) {
  20660. res.set_content("ok", "text/plain");
  20661. });
  20662. auto port = svr.bind_to_any_port(HOST);
  20663. ASSERT_GT(port, 0);
  20664. thread t = thread([&] { svr.listen_after_bind(); });
  20665. auto se = detail::scope_exit([&] {
  20666. svr.stop();
  20667. t.join();
  20668. ASSERT_FALSE(svr.is_running());
  20669. });
  20670. svr.wait_until_ready();
  20671. std::string resp;
  20672. ASSERT_TRUE(send_request(1,
  20673. "POST /test HTTP/1.1\r\n"
  20674. "Host: localhost\r\n"
  20675. "Connection: close\r\n"
  20676. "\r\n" +
  20677. std::string(16, 'X'),
  20678. &resp, port));
  20679. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20680. }
  20681. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20682. Server svr;
  20683. svr.Post("/post", [&](const Request &req, Response &res) {
  20684. res.set_content(req.body, "text/plain");
  20685. });
  20686. svr.Put("/put", [&](const Request &req, Response &res) {
  20687. res.set_content(req.body, "text/plain");
  20688. });
  20689. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20690. res.set_content(req.body, "text/plain");
  20691. });
  20692. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20693. res.set_content(req.body, "text/plain");
  20694. });
  20695. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20696. auto se = detail::scope_exit([&] {
  20697. svr.stop();
  20698. t.join();
  20699. ASSERT_FALSE(svr.is_running());
  20700. });
  20701. svr.wait_until_ready();
  20702. std::string resp;
  20703. // POST without Content-Length
  20704. ASSERT_TRUE(send_request(5,
  20705. "POST /post HTTP/1.1\r\n"
  20706. "Host: localhost\r\n"
  20707. "Connection: close\r\n"
  20708. "\r\n",
  20709. &resp));
  20710. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20711. // PUT without Content-Length
  20712. resp.clear();
  20713. ASSERT_TRUE(send_request(5,
  20714. "PUT /put HTTP/1.1\r\n"
  20715. "Host: localhost\r\n"
  20716. "Connection: close\r\n"
  20717. "\r\n",
  20718. &resp));
  20719. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20720. // PATCH without Content-Length
  20721. resp.clear();
  20722. ASSERT_TRUE(send_request(5,
  20723. "PATCH /patch HTTP/1.1\r\n"
  20724. "Host: localhost\r\n"
  20725. "Connection: close\r\n"
  20726. "\r\n",
  20727. &resp));
  20728. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20729. // DELETE without Content-Length
  20730. resp.clear();
  20731. ASSERT_TRUE(send_request(5,
  20732. "DELETE /delete HTTP/1.1\r\n"
  20733. "Host: localhost\r\n"
  20734. "Connection: close\r\n"
  20735. "\r\n",
  20736. &resp));
  20737. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20738. }
  20739. //==============================================================================
  20740. // open_stream() Tests
  20741. //==============================================================================
  20742. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20743. std::string result;
  20744. char buf[8192];
  20745. ssize_t n;
  20746. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20747. result.append(buf, static_cast<size_t>(n));
  20748. }
  20749. return result;
  20750. }
  20751. // Mock stream for unit tests
  20752. class MockStream : public Stream {
  20753. public:
  20754. std::string data;
  20755. size_t pos = 0;
  20756. ssize_t error_after = -1; // -1 = no error
  20757. explicit MockStream(const std::string &d, ssize_t err = -1)
  20758. : data(d), error_after(err) {}
  20759. bool is_readable() const override { return true; }
  20760. bool wait_readable() const override { return true; }
  20761. bool wait_writable() const override { return true; }
  20762. ssize_t read(char *ptr, size_t size) override {
  20763. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20764. if (pos >= data.size()) return 0;
  20765. size_t limit =
  20766. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20767. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20768. std::memcpy(ptr, data.data() + pos, to_read);
  20769. pos += to_read;
  20770. return static_cast<ssize_t>(to_read);
  20771. }
  20772. ssize_t write(const char *, size_t) override { return -1; }
  20773. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20774. ip = "127.0.0.1";
  20775. port = 0;
  20776. }
  20777. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20778. ip = "127.0.0.1";
  20779. port = 0;
  20780. }
  20781. socket_t socket() const override { return INVALID_SOCKET; }
  20782. time_t duration() const override { return 0; }
  20783. };
  20784. TEST(StreamHandleTest, Basic) {
  20785. ClientImpl::StreamHandle handle;
  20786. EXPECT_FALSE(handle.is_valid());
  20787. handle.response = detail::make_unique<Response>();
  20788. handle.error = Error::Connection;
  20789. EXPECT_FALSE(handle.is_valid());
  20790. handle.error = Error::Success;
  20791. EXPECT_TRUE(handle.is_valid());
  20792. }
  20793. TEST(BodyReaderTest, Basic) {
  20794. MockStream stream("Hello, World!");
  20795. detail::BodyReader reader;
  20796. reader.stream = &stream;
  20797. reader.content_length = 13;
  20798. char buf[32];
  20799. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20800. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20801. EXPECT_TRUE(reader.eof);
  20802. }
  20803. TEST(BodyReaderTest, NoStream) {
  20804. detail::BodyReader reader;
  20805. char buf[32];
  20806. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20807. EXPECT_EQ(Error::Connection, reader.last_error);
  20808. }
  20809. TEST(BodyReaderTest, Error) {
  20810. MockStream stream("Hello, World!", 5);
  20811. detail::BodyReader reader;
  20812. reader.stream = &stream;
  20813. reader.content_length = 13;
  20814. char buf[32];
  20815. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20816. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20817. EXPECT_EQ(Error::Read, reader.last_error);
  20818. }
  20819. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20820. // Mock-based StreamHandle tests relying on private internals are removed.
  20821. class OpenStreamTest : public ::testing::Test {
  20822. protected:
  20823. void SetUp() override {
  20824. svr_.Get("/hello", [](const Request &, Response &res) {
  20825. res.set_content("Hello World!", "text/plain");
  20826. });
  20827. svr_.Get("/large", [](const Request &, Response &res) {
  20828. res.set_content(std::string(10000, 'X'), "text/plain");
  20829. });
  20830. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20831. res.set_content("Hello World!", "image/jpeg");
  20832. res.set_header("Content-Encoding", "UTF-8");
  20833. });
  20834. svr_.Get("/chunked", [](const Request &, Response &res) {
  20835. res.set_chunked_content_provider("text/plain",
  20836. [](size_t offset, DataSink &sink) {
  20837. if (offset < 15) {
  20838. sink.write("chunk", 5);
  20839. return true;
  20840. }
  20841. sink.done();
  20842. return true;
  20843. });
  20844. });
  20845. svr_.Get("/compressible", [](const Request &, Response &res) {
  20846. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20847. DataSink &sink) {
  20848. if (offset < 100 * 1024) {
  20849. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20850. sink.write(chunk.data(), chunk.size());
  20851. return true;
  20852. }
  20853. sink.done();
  20854. return true;
  20855. });
  20856. });
  20857. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20858. [](const Request & /*req*/, Response &res) {
  20859. auto i = new int(0);
  20860. res.set_header("Trailer", "Content-Length, X-Allowed");
  20861. res.set_chunked_content_provider(
  20862. "text/plain",
  20863. [i](size_t /*offset*/, DataSink &sink) {
  20864. switch (*i) {
  20865. case 0: sink.os << "123"; break;
  20866. case 1: sink.os << "456"; break;
  20867. case 2: sink.os << "789"; break;
  20868. case 3: {
  20869. sink.done_with_trailer(
  20870. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20871. } break;
  20872. }
  20873. (*i)++;
  20874. return true;
  20875. },
  20876. [i](bool success) {
  20877. EXPECT_TRUE(success);
  20878. delete i;
  20879. });
  20880. });
  20881. // Echo headers endpoint for header-related tests
  20882. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20883. std::string body;
  20884. for (const auto &h : req.headers) {
  20885. body.append(h.first);
  20886. body.push_back(':');
  20887. body.append(h.second);
  20888. body.push_back('\n');
  20889. }
  20890. res.set_content(body, "text/plain");
  20891. });
  20892. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20893. std::string body;
  20894. for (const auto &h : req.headers) {
  20895. body.append(h.first);
  20896. body.push_back(':');
  20897. body.append(h.second);
  20898. body.push_back('\n');
  20899. }
  20900. res.set_content(body, "text/plain");
  20901. });
  20902. port_ = svr_.bind_to_any_port("127.0.0.1");
  20903. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20904. svr_.wait_until_ready();
  20905. }
  20906. void TearDown() override {
  20907. svr_.stop();
  20908. if (thread_.joinable()) thread_.join();
  20909. }
  20910. Server svr_;
  20911. std::thread thread_;
  20912. int port_ = 0;
  20913. };
  20914. TEST_F(OpenStreamTest, Basic) {
  20915. Client cli("127.0.0.1", port_);
  20916. auto handle = cli.open_stream("GET", "/hello");
  20917. EXPECT_TRUE(handle.is_valid());
  20918. EXPECT_EQ("Hello World!", read_all(handle));
  20919. }
  20920. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20921. Client cli("127.0.0.1", port_);
  20922. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20923. ASSERT_TRUE(handle.is_valid());
  20924. EXPECT_EQ("Hello World!", read_all(handle));
  20925. }
  20926. TEST_F(OpenStreamTest, SmallBuffer) {
  20927. Client cli("127.0.0.1", port_);
  20928. auto handle = cli.open_stream("GET", "/hello");
  20929. std::string result;
  20930. char buf[4];
  20931. ssize_t n;
  20932. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20933. result.append(buf, static_cast<size_t>(n));
  20934. EXPECT_EQ("Hello World!", result);
  20935. }
  20936. TEST_F(OpenStreamTest, DefaultHeaders) {
  20937. Client cli("127.0.0.1", port_);
  20938. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20939. {
  20940. auto handle = cli.open_stream("GET", "/echo-headers");
  20941. ASSERT_TRUE(handle.is_valid());
  20942. auto body = read_all(handle);
  20943. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20944. std::string::npos);
  20945. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20946. std::string::npos);
  20947. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20948. }
  20949. // open_stream POST with body and no explicit content_type should NOT add
  20950. // text/plain Content-Type (behavior differs from non-streaming path), but
  20951. // should include Content-Length
  20952. {
  20953. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20954. ASSERT_TRUE(handle.is_valid());
  20955. auto body = read_all(handle);
  20956. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20957. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20958. }
  20959. // open_stream POST with explicit Content-Type should preserve it
  20960. {
  20961. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20962. {{"Content-Type", "application/custom"}},
  20963. "{}", "application/custom");
  20964. ASSERT_TRUE(handle.is_valid());
  20965. auto body = read_all(handle);
  20966. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20967. }
  20968. // User-specified User-Agent must not be overwritten for stream API
  20969. {
  20970. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20971. {{"User-Agent", "MyAgent/1.2"}});
  20972. ASSERT_TRUE(handle.is_valid());
  20973. auto body = read_all(handle);
  20974. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20975. }
  20976. }
  20977. TEST_F(OpenStreamTest, Large) {
  20978. Client cli("127.0.0.1", port_);
  20979. auto handle = cli.open_stream("GET", "/large");
  20980. EXPECT_EQ(10000u, read_all(handle).size());
  20981. }
  20982. TEST_F(OpenStreamTest, ConnectionError) {
  20983. Client cli("127.0.0.1", 9999);
  20984. auto handle = cli.open_stream("GET", "/hello");
  20985. EXPECT_FALSE(handle.is_valid());
  20986. }
  20987. TEST_F(OpenStreamTest, Chunked) {
  20988. Client cli("127.0.0.1", port_);
  20989. auto handle = cli.open_stream("GET", "/chunked");
  20990. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20991. "Transfer-Encoding") == "chunked");
  20992. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20993. }
  20994. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20995. Client cli("127.0.0.1", port_);
  20996. auto handle =
  20997. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20998. ASSERT_TRUE(handle.is_valid());
  20999. // Consume body to allow trailers to be received/parsed
  21000. auto body = read_all(handle);
  21001. // Explicitly parse trailers (ensure trailers are available for assertion)
  21002. handle.parse_trailers_if_needed();
  21003. EXPECT_EQ(std::string("123456789"), body);
  21004. // The response should include a Trailer header declaring both names
  21005. ASSERT_TRUE(handle.response);
  21006. EXPECT_TRUE(handle.response->has_header("Trailer"));
  21007. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  21008. handle.response->get_header_value("Trailer"));
  21009. // Prohibited trailer must not be present
  21010. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  21011. // Allowed trailer should be present
  21012. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  21013. EXPECT_EQ(std::string("yes"),
  21014. handle.response->get_trailer_value("X-Allowed"));
  21015. // Verify trailers are NOT present as regular headers
  21016. EXPECT_EQ(std::string(""),
  21017. handle.response->get_header_value("Content-Length"));
  21018. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  21019. }
  21020. // Accepts one connection on an OS-assigned port, which it hands over through
  21021. // port_promise, reads the request head and sends back response. after_send,
  21022. // if given, runs on the connection before it is closed.
  21023. static std::thread
  21024. serve_single_response(std::promise<int> &port_promise,
  21025. const std::string &response,
  21026. std::function<void(socket_t)> after_send = nullptr) {
  21027. return std::thread([&port_promise, response, after_send] {
  21028. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21029. default_socket_options(srv);
  21030. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21031. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21032. sockaddr_in addr{};
  21033. addr.sin_family = AF_INET;
  21034. addr.sin_port = htons(0); // Let OS assign a free port
  21035. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21036. int opt = 1;
  21037. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  21038. #ifdef _WIN32
  21039. reinterpret_cast<const char *>(&opt),
  21040. #else
  21041. &opt,
  21042. #endif
  21043. sizeof(opt));
  21044. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21045. ::listen(srv, 1) != 0) {
  21046. port_promise.set_value(-1);
  21047. detail::close_socket(srv);
  21048. return;
  21049. }
  21050. socklen_t addr_len = sizeof(addr);
  21051. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21052. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21053. sockaddr_in cli_addr{};
  21054. socklen_t cli_len = sizeof(cli_addr);
  21055. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21056. if (cli != INVALID_SOCKET) {
  21057. // Read the complete HTTP request (until the blank line that terminates
  21058. // headers) before sending the response. If the server closes the socket
  21059. // while the client's request data is still unread in the kernel receive
  21060. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21061. // connection on both sides: it discards the client's receive buffer
  21062. // (which already holds our response) and causes any in-progress write on
  21063. // the client to fail with ECONNRESET. Reading all request data first
  21064. // ensures close() emits a graceful FIN.
  21065. {
  21066. char rbuf[256];
  21067. std::string req;
  21068. while (req.find("\r\n\r\n") == std::string::npos) {
  21069. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21070. if (n <= 0) { break; }
  21071. req.append(rbuf, static_cast<size_t>(n));
  21072. }
  21073. }
  21074. ::send(cli,
  21075. #ifdef _WIN32
  21076. static_cast<const char *>(response.c_str()),
  21077. static_cast<int>(response.size()),
  21078. #else
  21079. response.c_str(), response.size(),
  21080. #endif
  21081. 0);
  21082. if (after_send) { after_send(cli); }
  21083. detail::close_socket(cli);
  21084. }
  21085. detail::close_socket(srv);
  21086. });
  21087. }
  21088. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21089. #ifndef _WIN32
  21090. signal(SIGPIPE, SIG_IGN);
  21091. #endif
  21092. std::promise<int> port_promise;
  21093. auto port_future = port_promise.get_future();
  21094. auto server_thread =
  21095. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21096. "Content-Type: text/plain\r\n"
  21097. "Content-Length: not-a-number\r\n"
  21098. "Connection: close\r\n"
  21099. "\r\n"
  21100. "hello");
  21101. auto port = port_future.get();
  21102. ASSERT_GT(port, 0);
  21103. Client cli("127.0.0.1", port);
  21104. auto handle = cli.open_stream("GET", "/");
  21105. EXPECT_FALSE(handle.is_valid());
  21106. server_thread.join();
  21107. }
  21108. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21109. #ifndef _WIN32
  21110. signal(SIGPIPE, SIG_IGN);
  21111. #endif
  21112. std::promise<int> port_promise;
  21113. auto port_future = port_promise.get_future();
  21114. auto server_thread = serve_single_response(
  21115. port_promise, "HTTP/1.1 200 OK\r\n"
  21116. "Content-Type: text/plain\r\n"
  21117. "Content-Length: 99999999999999999999999999\r\n"
  21118. "Connection: close\r\n"
  21119. "\r\n"
  21120. "hello");
  21121. auto port = port_future.get();
  21122. ASSERT_GT(port, 0);
  21123. // Historically std::stoull would throw std::out_of_range here and crash
  21124. // the process, then parsing silently clamped to a bogus framing length and
  21125. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21126. // so the stream fails to open, matching the not-a-number case above. The
  21127. // process still must NOT terminate.
  21128. Client cli("127.0.0.1", port);
  21129. auto handle = cli.open_stream("GET", "/");
  21130. EXPECT_FALSE(handle.is_valid());
  21131. server_thread.join();
  21132. }
  21133. #ifndef _WIN32
  21134. // As above for the body of a streamed request: a send() cut short by the write
  21135. // timeout must not leave the rest of the body unsent.
  21136. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21137. signal(SIGPIPE, SIG_IGN);
  21138. Server svr;
  21139. svr.set_socket_options([](socket_t sock) {
  21140. int size = 8192;
  21141. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21142. reinterpret_cast<const char *>(&size), sizeof(size));
  21143. });
  21144. svr.Post("/size", [](const Request &, Response &res,
  21145. const ContentReader &content_reader) {
  21146. // Outlast the client's write timeout before reading the body.
  21147. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21148. size_t received = 0;
  21149. content_reader([&](const char *, size_t len) {
  21150. received += len;
  21151. return true;
  21152. });
  21153. res.set_content(std::to_string(received), "text/plain");
  21154. });
  21155. auto port = svr.bind_to_any_port(HOST);
  21156. std::thread t([&]() { svr.listen_after_bind(); });
  21157. auto se = detail::scope_exit([&] {
  21158. svr.stop();
  21159. t.join();
  21160. });
  21161. svr.wait_until_ready();
  21162. Client cli(HOST, port);
  21163. cli.set_write_timeout(0, 500000);
  21164. cli.set_socket_options([](socket_t sock) {
  21165. int size = 8192;
  21166. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21167. reinterpret_cast<const char *>(&size), sizeof(size));
  21168. });
  21169. const std::string body(4 * 1024 * 1024, 'A');
  21170. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21171. "application/octet-stream");
  21172. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21173. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21174. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21175. }
  21176. #endif
  21177. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21178. std::promise<void> slow_started;
  21179. auto slow_started_future = slow_started.get_future();
  21180. Server svr;
  21181. svr.Get("/slow", [&](const Request &, Response &res) {
  21182. slow_started.set_value();
  21183. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21184. res.set_content("slow", "text/plain");
  21185. });
  21186. svr.Get("/fast", [](const Request &, Response &res) {
  21187. res.set_content("fast", "text/plain");
  21188. });
  21189. auto port = svr.bind_to_any_port(HOST);
  21190. std::thread t([&]() { svr.listen_after_bind(); });
  21191. auto se = detail::scope_exit([&] {
  21192. svr.stop();
  21193. t.join();
  21194. });
  21195. svr.wait_until_ready();
  21196. Client cli(HOST, port);
  21197. std::string slow_body;
  21198. std::thread slow_thread([&] {
  21199. auto res = cli.Get("/slow");
  21200. if (res) { slow_body = res->body; }
  21201. });
  21202. slow_started_future.wait();
  21203. auto result = stream::Get(cli, "/fast");
  21204. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21205. slow_thread.join();
  21206. EXPECT_EQ("slow", slow_body);
  21207. EXPECT_EQ("fast", fast_body);
  21208. }
  21209. // Serves `response` to the single request `fn` makes with a fresh client.
  21210. template <typename Fn>
  21211. static void with_single_response(const std::string &response, Fn fn) {
  21212. #ifndef _WIN32
  21213. signal(SIGPIPE, SIG_IGN);
  21214. #endif
  21215. std::promise<int> port_promise;
  21216. auto port_future = port_promise.get_future();
  21217. auto server_thread = serve_single_response(port_promise, response);
  21218. auto se = detail::scope_exit([&] { server_thread.join(); });
  21219. auto port = port_future.get();
  21220. ASSERT_GT(port, 0);
  21221. Client cli("127.0.0.1", port);
  21222. fn(cli);
  21223. }
  21224. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21225. // too, also in a build without the decoder for the advertised coding.
  21226. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21227. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21228. const auto response = "HTTP/1.1 200 OK\r\n"
  21229. "Content-Encoding: gzip\r\n"
  21230. "Content-Length: " +
  21231. std::to_string(gzipped.size()) +
  21232. "\r\n"
  21233. "Connection: close\r\n\r\n" +
  21234. gzipped;
  21235. with_single_response(response, [&](Client &cli) {
  21236. cli.set_decompress(false);
  21237. auto handle = cli.open_stream("GET", "/");
  21238. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21239. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21240. EXPECT_EQ(gzipped, read_all(handle));
  21241. EXPECT_FALSE(handle.has_read_error());
  21242. });
  21243. with_single_response(response, [&](Client &cli) {
  21244. cli.set_decompress(false);
  21245. auto res = stream::Get(cli, "/", 7);
  21246. ASSERT_TRUE(res) << to_string(res.error());
  21247. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21248. EXPECT_EQ(gzipped, res.read_all());
  21249. EXPECT_FALSE(res.has_read_error());
  21250. });
  21251. }
  21252. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21253. // Neither Content-Length nor chunked: the body ends at the close
  21254. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21255. "Connection: close\r\n"
  21256. "\r\n"
  21257. "hello";
  21258. with_single_response(close_delimited, [](Client &cli) {
  21259. auto handle = cli.open_stream("GET", "/");
  21260. ASSERT_TRUE(handle.is_valid());
  21261. EXPECT_EQ("hello", read_all(handle));
  21262. EXPECT_FALSE(handle.has_read_error());
  21263. });
  21264. // A close before the end of the Content-Length is still an error
  21265. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21266. "Content-Length: 10\r\n"
  21267. "\r\n"
  21268. "hello";
  21269. with_single_response(short_content_length, [](Client &cli) {
  21270. auto handle = cli.open_stream("GET", "/");
  21271. ASSERT_TRUE(handle.is_valid());
  21272. read_all(handle);
  21273. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21274. });
  21275. // So is a close before the last chunk
  21276. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21277. "Transfer-Encoding: chunked\r\n"
  21278. "\r\n"
  21279. "5\r\nhello\r\n";
  21280. with_single_response(short_chunked, [](Client &cli) {
  21281. auto handle = cli.open_stream("GET", "/");
  21282. ASSERT_TRUE(handle.is_valid());
  21283. read_all(handle);
  21284. EXPECT_TRUE(handle.has_read_error());
  21285. });
  21286. }
  21287. #ifdef CPPHTTPLIB_SSL_ENABLED
  21288. // Serves `response` to one request, then closes with or without a close_notify
  21289. template <typename Fn>
  21290. static void with_single_tls_response(const std::string &response,
  21291. bool close_notify, Fn fn) {
  21292. #ifndef _WIN32
  21293. signal(SIGPIPE, SIG_IGN);
  21294. #endif
  21295. std::promise<int> port_promise;
  21296. auto port_future = port_promise.get_future();
  21297. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21298. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21299. default_socket_options(srv);
  21300. sockaddr_in addr{};
  21301. addr.sin_family = AF_INET;
  21302. addr.sin_port = htons(0);
  21303. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21304. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21305. ::listen(srv, 1) != 0) {
  21306. port_promise.set_value(-1);
  21307. detail::close_socket(srv);
  21308. return;
  21309. }
  21310. socklen_t addr_len = sizeof(addr);
  21311. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21312. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21313. auto cli = ::accept(srv, nullptr, nullptr);
  21314. if (cli != INVALID_SOCKET) {
  21315. auto ctx = tls::create_server_context();
  21316. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21317. nullptr);
  21318. auto session = tls::create_session(ctx, cli);
  21319. tls::TlsError err;
  21320. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21321. // The request head first, so that closing the socket sends a FIN
  21322. // rather than an RST for the unread bytes.
  21323. std::string req;
  21324. char buf[256];
  21325. while (req.find("\r\n\r\n") == std::string::npos) {
  21326. auto n = tls::read(session, buf, sizeof(buf), err);
  21327. if (n <= 0) { break; }
  21328. req.append(buf, static_cast<size_t>(n));
  21329. }
  21330. size_t sent = 0;
  21331. while (sent < response.size()) {
  21332. auto n = tls::write(session, response.data() + sent,
  21333. response.size() - sent, err);
  21334. if (n <= 0) { break; }
  21335. sent += static_cast<size_t>(n);
  21336. }
  21337. if (close_notify) { tls::shutdown(session, true); }
  21338. }
  21339. tls::free_session(session);
  21340. detail::close_socket(cli);
  21341. tls::free_context(ctx);
  21342. }
  21343. detail::close_socket(srv);
  21344. });
  21345. auto se = detail::scope_exit([&] { server_thread.join(); });
  21346. auto port = port_future.get();
  21347. ASSERT_GT(port, 0);
  21348. SSLClient cli("127.0.0.1", port);
  21349. cli.enable_server_certificate_verification(false);
  21350. fn(cli);
  21351. }
  21352. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21353. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21354. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21355. "Connection: close\r\n"
  21356. "\r\n"
  21357. "hello";
  21358. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21359. auto res = cli.Get("/");
  21360. ASSERT_TRUE(res) << to_string(res.error());
  21361. EXPECT_EQ("hello", res->body);
  21362. });
  21363. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21364. auto res = cli.Get("/");
  21365. ASSERT_FALSE(res);
  21366. EXPECT_EQ(Error::Read, res.error());
  21367. });
  21368. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21369. auto handle = cli.open_stream("GET", "/");
  21370. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21371. read_all(handle);
  21372. EXPECT_TRUE(handle.has_read_error());
  21373. });
  21374. // A framed body ends where its framing says, with or without the alert
  21375. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21376. "Content-Length: 5\r\n"
  21377. "Connection: close\r\n"
  21378. "\r\n"
  21379. "hello";
  21380. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21381. auto res = cli.Get("/");
  21382. ASSERT_TRUE(res) << to_string(res.error());
  21383. EXPECT_EQ("hello", res->body);
  21384. });
  21385. }
  21386. #endif
  21387. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21388. const char *responses[] = {
  21389. "HTTP/1.1 103 Early Hints\r\n"
  21390. "Link: </style.css>; rel=preload\r\n"
  21391. "\r\n"
  21392. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21393. "HTTP/1.1 100 Continue\r\n"
  21394. "X-Note: interim\r\n"
  21395. "\r\n"
  21396. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21397. };
  21398. for (auto response : responses) {
  21399. with_single_response(response, [](Client &cli) {
  21400. auto res = cli.Get("/");
  21401. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21402. EXPECT_EQ(StatusCode::OK_200, res->status);
  21403. EXPECT_EQ("ok", res->body);
  21404. });
  21405. }
  21406. }
  21407. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21408. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21409. const std::string final_response =
  21410. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21411. std::string interims;
  21412. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21413. interims += interim;
  21414. }
  21415. with_single_response(interims + final_response, [](Client &cli) {
  21416. auto res = cli.Get("/");
  21417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21418. EXPECT_EQ("ok", res->body);
  21419. });
  21420. with_single_response(interims + interim + final_response, [](Client &cli) {
  21421. auto res = cli.Get("/");
  21422. ASSERT_FALSE(res);
  21423. EXPECT_EQ(Error::Read, res.error());
  21424. });
  21425. }
  21426. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21427. #ifndef _WIN32
  21428. signal(SIGPIPE, SIG_IGN);
  21429. #endif
  21430. // The server answers the head without asking for the body. Bytes it then
  21431. // reads on the connection would be taken for the body the request declared.
  21432. auto closed_by_client = false;
  21433. std::promise<int> port_promise;
  21434. auto server_thread = serve_single_response(
  21435. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21436. [&](socket_t sock) {
  21437. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21438. char buf[256];
  21439. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21440. });
  21441. Client cli("127.0.0.1", port_promise.get_future().get());
  21442. cli.set_keep_alive(true);
  21443. cli.set_read_timeout(1, 0);
  21444. // Long enough for the client to send Expect: 100-continue.
  21445. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21447. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21448. cli.Get("/second");
  21449. server_thread.join();
  21450. EXPECT_TRUE(closed_by_client);
  21451. }
  21452. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21453. // Long enough for the client to send Expect: 100-continue
  21454. with_single_response(
  21455. "HTTP/1.1 103 Early Hints\r\n"
  21456. "Link: </style.css>; rel=preload\r\n"
  21457. "\r\n"
  21458. "HTTP/1.1 401 Unauthorized\r\n"
  21459. "Content-Length: 0\r\n\r\n",
  21460. [](Client &cli) {
  21461. cli.set_read_timeout(2, 0);
  21462. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21464. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21465. });
  21466. }
  21467. #ifdef CPPHTTPLIB_SSL_ENABLED
  21468. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21469. #ifndef _WIN32
  21470. signal(SIGPIPE, SIG_IGN);
  21471. #endif
  21472. auto reused = false;
  21473. std::promise<int> port_promise;
  21474. auto server_thread = serve_single_response(
  21475. port_promise,
  21476. "HTTP/1.1 401 Unauthorized\r\n"
  21477. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21478. "Content-Length: 0\r\n\r\n",
  21479. [&](socket_t sock) {
  21480. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21481. char buf[256];
  21482. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21483. });
  21484. Client cli("127.0.0.1", port_promise.get_future().get());
  21485. cli.set_keep_alive(true);
  21486. cli.set_digest_auth("user", "pass");
  21487. cli.set_read_timeout(1, 0);
  21488. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21489. server_thread.join();
  21490. EXPECT_FALSE(reused);
  21491. }
  21492. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21493. // Any other answer to CONNECT would read as the origin's response.
  21494. struct {
  21495. const char *response;
  21496. bool passed_on;
  21497. } cases[] = {
  21498. {"HTTP/1.1 201 Created\r\n"
  21499. "Set-Cookie: session=from-proxy\r\n"
  21500. "Content-Length: 0\r\n\r\n",
  21501. false},
  21502. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21503. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21504. "Content-Length: 0\r\n\r\n",
  21505. true},
  21506. };
  21507. for (const auto &c : cases) {
  21508. std::promise<int> port_promise;
  21509. auto server_thread = serve_single_response(port_promise, c.response);
  21510. SSLClient cli("example.com", 443);
  21511. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21512. auto res = cli.Get("/");
  21513. server_thread.join();
  21514. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21515. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21516. if (res) {
  21517. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21518. }
  21519. }
  21520. }
  21521. #endif
  21522. // Records the client's error logger calls as "error METHOD path", or
  21523. // "error null" for a call without a request
  21524. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21525. return [&log](const Error &err, const Request *req) {
  21526. log.push_back(to_string(err) + " " +
  21527. (req ? req->method + " " + req->path : "null"));
  21528. };
  21529. }
  21530. // A failed request is reported once, with the request the caller made
  21531. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21532. Server svr;
  21533. svr.Get("/big", [](const Request &, Response &res) {
  21534. res.set_content(std::string(100000, 'b'), "text/plain");
  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. std::vector<std::string> log;
  21545. cli.set_error_logger(record_errors(log));
  21546. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21547. cli.Get("/big", [](const char *, size_t) { return false; });
  21548. EXPECT_EQ(expected, log);
  21549. log.clear();
  21550. cli.Get("/big", [](size_t, size_t) { return false; });
  21551. EXPECT_EQ(expected, log);
  21552. }
  21553. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21554. // Fails while the body is read
  21555. auto broken = [](const Request &, Response &res) {
  21556. res.set_content_provider(10, "text/plain",
  21557. [](size_t, size_t, DataSink &) { return false; });
  21558. };
  21559. Server other;
  21560. other.Get("/broken", broken);
  21561. auto other_port = other.bind_to_any_port(HOST);
  21562. std::thread other_t([&]() { other.listen_after_bind(); });
  21563. auto other_se = detail::scope_exit([&] {
  21564. other.stop();
  21565. other_t.join();
  21566. });
  21567. other.wait_until_ready();
  21568. Server svr;
  21569. svr.Get("/broken", broken);
  21570. svr.Get("/same-origin",
  21571. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21572. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21573. res.set_redirect("http://" + std::string(HOST) + ":" +
  21574. std::to_string(other_port) + "/broken");
  21575. });
  21576. auto port = svr.bind_to_any_port(HOST);
  21577. std::thread t([&]() { svr.listen_after_bind(); });
  21578. auto se = detail::scope_exit([&] {
  21579. svr.stop();
  21580. t.join();
  21581. });
  21582. svr.wait_until_ready();
  21583. Client cli(HOST, port);
  21584. cli.set_follow_location(true);
  21585. std::vector<std::string> log;
  21586. cli.set_error_logger(record_errors(log));
  21587. for (auto path : {"/same-origin", "/cross-origin"}) {
  21588. log.clear();
  21589. auto res = cli.Get(path);
  21590. ASSERT_FALSE(res);
  21591. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21592. log);
  21593. }
  21594. }
  21595. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21596. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21597. std::vector<std::string> log;
  21598. cli.set_error_logger(record_errors(log));
  21599. auto handle = cli.open_stream("GET", "/x");
  21600. EXPECT_FALSE(handle.is_valid());
  21601. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21602. log);
  21603. });
  21604. }
  21605. #ifdef CPPHTTPLIB_SSL_ENABLED
  21606. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21607. // Not a TLS server, so the handshake fails. It waits for a request line in
  21608. // the handshake bytes, so a short read timeout lets it close quickly.
  21609. Server svr;
  21610. svr.set_read_timeout(0, 100000);
  21611. svr.Get("/x", [](const Request &, Response &res) {
  21612. res.set_content("x", "text/plain");
  21613. });
  21614. auto port = svr.bind_to_any_port(HOST);
  21615. std::thread t([&]() { svr.listen_after_bind(); });
  21616. auto se = detail::scope_exit([&] {
  21617. svr.stop();
  21618. t.join();
  21619. });
  21620. svr.wait_until_ready();
  21621. std::vector<std::string> log;
  21622. SSLClient cli(HOST, port);
  21623. cli.enable_server_certificate_verification(false);
  21624. cli.set_error_logger(record_errors(log));
  21625. auto res = cli.Get("/x");
  21626. ASSERT_FALSE(res);
  21627. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21628. log.clear();
  21629. auto handle = cli.open_stream("GET", "/x");
  21630. EXPECT_FALSE(handle.is_valid());
  21631. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21632. log.clear();
  21633. SSLClient no_ca(HOST, port);
  21634. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21635. no_ca.set_error_logger(record_errors(log));
  21636. res = no_ca.Get("/x");
  21637. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21638. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21639. }
  21640. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21641. #ifndef _WIN32
  21642. signal(SIGPIPE, SIG_IGN);
  21643. #endif
  21644. // Refused, answered with a challenge, or closed without an answer
  21645. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21646. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21647. "Content-Length: 0\r\n\r\n",
  21648. ""}) {
  21649. std::promise<int> port_promise;
  21650. auto server_thread = serve_single_response(port_promise, response);
  21651. SSLClient cli("example.com", 443);
  21652. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21653. std::vector<std::string> log;
  21654. cli.set_error_logger(record_errors(log));
  21655. auto res = cli.Get("/");
  21656. server_thread.join();
  21657. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21658. << response;
  21659. }
  21660. }
  21661. #endif
  21662. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21663. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21664. // the chunked coding and drop Content-Length, so a front-end that trusts
  21665. // Content-Length would disagree about where the body ends (response
  21666. // smuggling). The client must reject such a response.
  21667. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21668. for (const char *te : {"chunked", "gzip, chunked"}) {
  21669. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21670. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21671. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21672. "5\r\nhello\r\n0\r\n\r\n";
  21673. with_single_response(response, [&](Client &cli) {
  21674. auto res = cli.Get("/");
  21675. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21676. EXPECT_EQ(Error::Read, res.error()) << te;
  21677. });
  21678. with_single_response(response, [&](Client &cli) {
  21679. auto handle = cli.open_stream("GET", "/");
  21680. EXPECT_FALSE(handle.is_valid()) << te;
  21681. EXPECT_EQ(Error::Read, handle.error) << te;
  21682. });
  21683. }
  21684. }
  21685. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21686. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21687. // closing the connection (unlike a request, which must be rejected).
  21688. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21689. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21690. "Transfer-Encoding: chunked\r\n"
  21691. "Connection: close\r\n"
  21692. "\r\n"
  21693. "5\r\nhello\r\n0\r\n\r\n",
  21694. "HTTP/1.1 200 OK\r\n"
  21695. "Transfer-Encoding: gzip\r\n"
  21696. "Connection: close\r\n"
  21697. "\r\n"
  21698. "hello"}) {
  21699. with_single_response(response, [&](Client &cli) {
  21700. auto res = cli.Get("/");
  21701. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21702. EXPECT_EQ("hello", res->body);
  21703. });
  21704. with_single_response(response, [&](Client &cli) {
  21705. auto handle = cli.open_stream("GET", "/");
  21706. ASSERT_TRUE(handle.is_valid()) << response;
  21707. EXPECT_EQ("hello", read_all(handle));
  21708. });
  21709. }
  21710. }
  21711. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21712. // framing headers describe nothing to read and must not be rejected.
  21713. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21714. const std::string framing = "Content-Length: 5\r\n"
  21715. "Transfer-Encoding: chunked\r\n"
  21716. "Connection: close\r\n"
  21717. "\r\n";
  21718. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21719. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21720. });
  21721. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21722. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21723. });
  21724. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21725. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21726. with_single_response(response, [&](Client &cli) {
  21727. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21728. });
  21729. with_single_response(response, [&](Client &cli) {
  21730. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21731. });
  21732. }
  21733. }
  21734. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21735. // header section, so a stream opened on one has nothing to read, whatever
  21736. // framing or coding headers it carries.
  21737. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21738. struct Case {
  21739. const char *method;
  21740. const char *status;
  21741. };
  21742. // A reader of the declared body reports an early close when nothing
  21743. // follows, and hands back what does.
  21744. struct Framing {
  21745. const char *headers;
  21746. const char *after;
  21747. };
  21748. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21749. Case{"GET", "304 Not Modified"}}) {
  21750. for (const auto &f :
  21751. {Framing{"Content-Length: 5\r\n", ""},
  21752. Framing{"Content-Length: 5\r\n", "hello"},
  21753. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21754. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21755. // Not decoded, so a build without Brotli opens it too
  21756. Framing{"Content-Encoding: br\r\n", ""}}) {
  21757. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21758. "Connection: close\r\n"
  21759. "\r\n" +
  21760. f.after;
  21761. with_single_response(response, [&](Client &cli) {
  21762. auto handle = cli.open_stream(c.method, "/");
  21763. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21764. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21765. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21766. });
  21767. }
  21768. }
  21769. }
  21770. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21771. // response, is faulty framing, so the connection is not reused after it.
  21772. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21773. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21774. "Content-Length: 0\r\n"
  21775. "Transfer-Encoding: chunked\r\n"
  21776. "\r\n"
  21777. "5\r\nhello\r\n0\r\n\r\n",
  21778. "HTTP/1.0 200 Connection established\r\n"
  21779. "Connection: keep-alive\r\n"
  21780. "Transfer-Encoding: chunked\r\n"
  21781. "\r\n"
  21782. "5\r\nhello\r\n0\r\n\r\n"}) {
  21783. with_single_response(response, [&](Client &cli) {
  21784. cli.set_keep_alive(true);
  21785. auto res = cli.Get("/");
  21786. ASSERT_TRUE(res) << response;
  21787. EXPECT_EQ("hello", res->body);
  21788. EXPECT_FALSE(cli.is_socket_open()) << response;
  21789. });
  21790. }
  21791. }
  21792. // A payload max length of 0 means no limit, however the body is framed.
  21793. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21794. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21795. "Transfer-Encoding: chunked\r\n"
  21796. "\r\n"
  21797. "5\r\nhello\r\n0\r\n\r\n",
  21798. "HTTP/1.1 200 OK\r\n"
  21799. "Connection: close\r\n"
  21800. "\r\n"
  21801. "hello"}) {
  21802. with_single_response(response, [&](Client &cli) {
  21803. cli.set_payload_max_length(0);
  21804. auto res = cli.Get("/");
  21805. ASSERT_TRUE(res) << response;
  21806. EXPECT_EQ("hello", res->body) << response;
  21807. });
  21808. }
  21809. }
  21810. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21811. Server svr;
  21812. svr.set_payload_max_length(0);
  21813. svr.Post("/echo", [](const Request &req, Response &res) {
  21814. res.set_content(req.body, "text/plain");
  21815. });
  21816. auto port = svr.bind_to_any_port(HOST);
  21817. thread t = thread([&] { svr.listen_after_bind(); });
  21818. auto se = detail::scope_exit([&] {
  21819. svr.stop();
  21820. t.join();
  21821. ASSERT_FALSE(svr.is_running());
  21822. });
  21823. svr.wait_until_ready();
  21824. Client cli(HOST, port);
  21825. auto res = cli.Post(
  21826. "/echo",
  21827. [](size_t /*offset*/, DataSink &sink) {
  21828. sink.write("hello", 5);
  21829. sink.done();
  21830. return true;
  21831. },
  21832. "text/plain");
  21833. ASSERT_TRUE(res);
  21834. EXPECT_EQ(StatusCode::OK_200, res->status);
  21835. EXPECT_EQ("hello", res->body);
  21836. }
  21837. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21838. TEST_F(OpenStreamTest, Gzip) {
  21839. Client cli("127.0.0.1", port_);
  21840. auto handle = cli.open_stream("GET", "/compressible", {},
  21841. {{"Accept-Encoding", "gzip"}});
  21842. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21843. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21844. }
  21845. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21846. Client cli("127.0.0.1", port_);
  21847. auto handle =
  21848. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21849. {{"Accept-Encoding", "gzip"}});
  21850. ASSERT_TRUE(handle.is_valid());
  21851. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21852. EXPECT_EQ("123456789", read_all(handle));
  21853. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21854. }
  21855. #endif
  21856. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21857. TEST_F(OpenStreamTest, Brotli) {
  21858. Client cli("127.0.0.1", port_);
  21859. auto handle =
  21860. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21861. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21862. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21863. }
  21864. #endif
  21865. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21866. TEST_F(OpenStreamTest, Zstd) {
  21867. Client cli("127.0.0.1", port_);
  21868. auto handle = cli.open_stream("GET", "/compressible", {},
  21869. {{"Accept-Encoding", "zstd"}});
  21870. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21871. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21872. }
  21873. #endif
  21874. #ifdef CPPHTTPLIB_SSL_ENABLED
  21875. class SSLOpenStreamTest : public ::testing::Test {
  21876. protected:
  21877. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21878. void SetUp() override {
  21879. svr_.Get("/hello", [](const Request &, Response &res) {
  21880. res.set_content("Hello SSL World!", "text/plain");
  21881. });
  21882. svr_.Get("/chunked", [](const Request &, Response &res) {
  21883. res.set_chunked_content_provider("text/plain",
  21884. [](size_t offset, DataSink &sink) {
  21885. if (offset < 15) {
  21886. sink.write("chunk", 5);
  21887. return true;
  21888. }
  21889. sink.done();
  21890. return true;
  21891. });
  21892. });
  21893. svr_.Post("/echo", [](const Request &req, Response &res) {
  21894. res.set_content(req.body, req.get_header_value("Content-Type"));
  21895. });
  21896. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21897. std::string body = req.body;
  21898. res.set_chunked_content_provider(
  21899. "text/plain", [body](size_t offset, DataSink &sink) {
  21900. if (offset < body.size()) {
  21901. sink.write(body.data() + offset, body.size() - offset);
  21902. }
  21903. sink.done();
  21904. return true;
  21905. });
  21906. });
  21907. port_ = svr_.bind_to_any_port("127.0.0.1");
  21908. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21909. svr_.wait_until_ready();
  21910. }
  21911. void TearDown() override {
  21912. svr_.stop();
  21913. if (thread_.joinable()) thread_.join();
  21914. }
  21915. SSLServer svr_;
  21916. std::thread thread_;
  21917. int port_ = 0;
  21918. };
  21919. TEST_F(SSLOpenStreamTest, Basic) {
  21920. SSLClient cli("127.0.0.1", port_);
  21921. cli.enable_server_certificate_verification(false);
  21922. auto handle = cli.open_stream("GET", "/hello");
  21923. ASSERT_TRUE(handle.is_valid());
  21924. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21925. }
  21926. TEST_F(SSLOpenStreamTest, Chunked) {
  21927. SSLClient cli("127.0.0.1", port_);
  21928. cli.enable_server_certificate_verification(false);
  21929. auto handle = cli.open_stream("GET", "/chunked");
  21930. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21931. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21932. "Transfer-Encoding") == "chunked");
  21933. auto body = read_all(handle);
  21934. EXPECT_EQ("chunkchunkchunk", body);
  21935. }
  21936. TEST_F(SSLOpenStreamTest, Post) {
  21937. SSLClient cli("127.0.0.1", port_);
  21938. cli.enable_server_certificate_verification(false);
  21939. auto handle =
  21940. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21941. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21942. EXPECT_EQ(200, handle.response->status);
  21943. auto body = read_all(handle);
  21944. EXPECT_EQ("Hello SSL POST", body);
  21945. }
  21946. TEST_F(SSLOpenStreamTest, PostChunked) {
  21947. SSLClient cli("127.0.0.1", port_);
  21948. cli.enable_server_certificate_verification(false);
  21949. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21950. "Chunked SSL Data", "text/plain");
  21951. ASSERT_TRUE(handle.is_valid());
  21952. EXPECT_EQ(200, handle.response->status);
  21953. auto body = read_all(handle);
  21954. EXPECT_EQ("Chunked SSL Data", body);
  21955. }
  21956. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21957. // Content-Length is terminated by the server closing the connection. When the
  21958. // SSL peer sends a close_notify after the body, the client must treat it as a
  21959. // clean EOF and return a successful response rather than an error.
  21960. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21961. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21962. ASSERT_TRUE(svr.is_valid());
  21963. svr.set_keep_alive_max_count(1);
  21964. const std::string expected_body = "Hello from connection-close response!";
  21965. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21966. res.set_content_provider("text/plain",
  21967. [&](size_t offset, DataSink &sink) -> bool {
  21968. if (offset < expected_body.size()) {
  21969. sink.write(expected_body.data() + offset,
  21970. expected_body.size() - offset);
  21971. }
  21972. sink.done();
  21973. return true;
  21974. });
  21975. });
  21976. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21977. auto se = detail::scope_exit([&] {
  21978. svr.stop();
  21979. listen_thread.join();
  21980. ASSERT_FALSE(svr.is_running());
  21981. });
  21982. svr.wait_until_ready();
  21983. SSLClient cli(HOST, PORT);
  21984. cli.enable_server_certificate_verification(false);
  21985. auto res = cli.Get("/no-content-length");
  21986. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21987. EXPECT_EQ(StatusCode::OK_200, res->status);
  21988. EXPECT_EQ(expected_body, res->body);
  21989. }
  21990. // Without Content-Length, the full buffer size reaches tls::read().
  21991. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21992. if (sizeof(size_t) <= sizeof(int)) {
  21993. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21994. }
  21995. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21996. ASSERT_TRUE(svr.is_valid());
  21997. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21998. res.set_content_provider("text/plain",
  21999. [&](size_t offset, DataSink &sink) -> bool {
  22000. if (offset == 0) { sink.write("Hello", 5); }
  22001. sink.done();
  22002. return true;
  22003. });
  22004. });
  22005. auto port = svr.bind_to_any_port(HOST);
  22006. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  22007. auto se = detail::scope_exit([&] {
  22008. svr.stop();
  22009. listen_thread.join();
  22010. });
  22011. svr.wait_until_ready();
  22012. SSLClient cli(HOST, port);
  22013. cli.enable_server_certificate_verification(false);
  22014. auto handle = cli.open_stream("GET", "/no-content-length");
  22015. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  22016. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  22017. std::unique_ptr<char[]> buf(new char[len]);
  22018. std::string body;
  22019. ssize_t n;
  22020. while ((n = handle.read(buf.get(), len)) > 0) {
  22021. body.append(buf.get(), static_cast<size_t>(n));
  22022. }
  22023. EXPECT_EQ(0, n);
  22024. EXPECT_EQ("Hello", body);
  22025. }
  22026. #endif // CPPHTTPLIB_SSL_ENABLED
  22027. //==============================================================================
  22028. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  22029. // results for various scenarios.
  22030. //==============================================================================
  22031. TEST(ParityTest, GetVsOpenStream) {
  22032. Server svr;
  22033. const std::string path = "/parity";
  22034. const std::string content = "Parity test content: hello world";
  22035. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22036. res.set_content(content, "text/plain");
  22037. });
  22038. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22039. auto se = detail::scope_exit([&] {
  22040. svr.stop();
  22041. t.join();
  22042. ASSERT_FALSE(svr.is_running());
  22043. });
  22044. svr.wait_until_ready();
  22045. Client cli(HOST, PORT);
  22046. // Non-stream path
  22047. auto r1 = cli.Get(path);
  22048. ASSERT_TRUE(r1);
  22049. EXPECT_EQ(StatusCode::OK_200, r1->status);
  22050. // Stream path
  22051. auto h = cli.open_stream("GET", path);
  22052. ASSERT_TRUE(h.is_valid());
  22053. EXPECT_EQ(r1->body, read_all(h));
  22054. }
  22055. // Helper to compress data with provided compressor type T
  22056. template <typename Compressor>
  22057. static std::string compress_payload_for_parity(const std::string &in) {
  22058. std::string out;
  22059. Compressor compressor;
  22060. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22061. [&](const char *data, size_t n) {
  22062. out.append(data, n);
  22063. return true;
  22064. });
  22065. EXPECT_TRUE(ok);
  22066. return out;
  22067. }
  22068. // Helper function for compression parity tests
  22069. template <typename Compressor>
  22070. static void test_compression_parity(const std::string &original,
  22071. const std::string &path,
  22072. const std::string &encoding) {
  22073. const std::string compressed =
  22074. compress_payload_for_parity<Compressor>(original);
  22075. Server svr;
  22076. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22077. res.set_content(compressed, "application/octet-stream");
  22078. res.set_header("Content-Encoding", encoding);
  22079. });
  22080. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22081. auto se = detail::scope_exit([&] {
  22082. svr.stop();
  22083. t.join();
  22084. ASSERT_FALSE(svr.is_running());
  22085. });
  22086. svr.wait_until_ready();
  22087. Client cli(HOST, PORT);
  22088. // Non-streaming
  22089. {
  22090. auto res = cli.Get(path);
  22091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22092. EXPECT_EQ(StatusCode::OK_200, res->status);
  22093. EXPECT_EQ(original, res->body);
  22094. }
  22095. // Streaming
  22096. {
  22097. auto h = cli.open_stream("GET", path);
  22098. ASSERT_TRUE(h.is_valid());
  22099. EXPECT_EQ(original, read_all(h));
  22100. }
  22101. }
  22102. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22103. TEST(ParityTest, Gzip) {
  22104. test_compression_parity<detail::gzip_compressor>(
  22105. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22106. }
  22107. #endif
  22108. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22109. TEST(ParityTest, Brotli) {
  22110. test_compression_parity<detail::brotli_compressor>(
  22111. "Hello, brotli parity test payload", "/parity-br", "br");
  22112. }
  22113. #endif
  22114. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22115. TEST(ParityTest, Zstd) {
  22116. test_compression_parity<detail::zstd_compressor>(
  22117. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22118. }
  22119. #endif
  22120. //==============================================================================
  22121. // New Stream API Tests
  22122. //==============================================================================
  22123. inline std::string read_body(httplib::stream::Result &result) {
  22124. std::string body;
  22125. while (result.next()) {
  22126. body.append(result.data(), result.size());
  22127. }
  22128. return body;
  22129. }
  22130. TEST(ClientConnectionTest, Basic) {
  22131. httplib::ClientConnection conn;
  22132. EXPECT_FALSE(conn.is_open());
  22133. conn.sock = 1;
  22134. EXPECT_TRUE(conn.is_open());
  22135. httplib::ClientConnection conn2(std::move(conn));
  22136. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22137. conn2.sock = INVALID_SOCKET;
  22138. }
  22139. // Unified test server for all stream::* tests
  22140. class StreamApiTest : public ::testing::Test {
  22141. protected:
  22142. void SetUp() override {
  22143. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22144. res.set_content("Hello World!", "text/plain");
  22145. });
  22146. svr_.Get("/echo-params",
  22147. [](const httplib::Request &req, httplib::Response &res) {
  22148. std::string r;
  22149. for (const auto &p : req.params) {
  22150. if (!r.empty()) r += "&";
  22151. r += p.first + "=" + p.second;
  22152. }
  22153. res.set_content(r, "text/plain");
  22154. });
  22155. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22156. res.set_content(req.body, req.get_header_value("Content-Type"));
  22157. });
  22158. svr_.Post("/echo-headers",
  22159. [](const httplib::Request &req, httplib::Response &res) {
  22160. std::string r;
  22161. for (const auto &h : req.headers)
  22162. r += h.first + ": " + h.second + "\n";
  22163. res.set_content(r, "text/plain");
  22164. });
  22165. svr_.Post("/echo-params",
  22166. [](const httplib::Request &req, httplib::Response &res) {
  22167. std::string r = "params:";
  22168. for (const auto &p : req.params)
  22169. r += p.first + "=" + p.second + ";";
  22170. res.set_content(r + " body:" + req.body, "text/plain");
  22171. });
  22172. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22173. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22174. });
  22175. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22176. res.set_content("PUT:" + req.body, "text/plain");
  22177. });
  22178. svr_.Patch("/echo",
  22179. [](const httplib::Request &req, httplib::Response &res) {
  22180. res.set_content("PATCH:" + req.body, "text/plain");
  22181. });
  22182. svr_.Delete(
  22183. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22184. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22185. "text/plain");
  22186. });
  22187. svr_.Get("/head-test",
  22188. [](const httplib::Request &, httplib::Response &res) {
  22189. res.set_content("body for HEAD", "text/plain");
  22190. });
  22191. svr_.Options("/options",
  22192. [](const httplib::Request &, httplib::Response &res) {
  22193. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22194. });
  22195. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22196. svr_.wait_until_ready();
  22197. }
  22198. void TearDown() override {
  22199. svr_.stop();
  22200. if (thread_.joinable()) thread_.join();
  22201. }
  22202. httplib::Server svr_;
  22203. std::thread thread_;
  22204. };
  22205. // stream::Get tests
  22206. TEST_F(StreamApiTest, GetBasic) {
  22207. httplib::Client cli(HOST, PORT);
  22208. auto result = httplib::stream::Get(cli, "/hello");
  22209. ASSERT_TRUE(result.is_valid());
  22210. EXPECT_EQ(200, result.status());
  22211. EXPECT_EQ("Hello World!", read_body(result));
  22212. }
  22213. TEST_F(StreamApiTest, GetWithParams) {
  22214. httplib::Client cli(HOST, PORT);
  22215. httplib::Params params{{"foo", "bar"}};
  22216. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22217. ASSERT_TRUE(result.is_valid());
  22218. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22219. }
  22220. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22221. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22222. httplib::Client cli(HOST, PORT);
  22223. cli.set_payload_max_length(0);
  22224. auto result = httplib::stream::Get(cli, "/hello");
  22225. ASSERT_TRUE(result.is_valid());
  22226. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22227. EXPECT_EQ("Hello World!", read_body(result));
  22228. }
  22229. #endif
  22230. TEST_F(StreamApiTest, GetConnectionError) {
  22231. httplib::Client cli(HOST, 9999);
  22232. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22233. }
  22234. TEST_F(StreamApiTest, Get404) {
  22235. httplib::Client cli(HOST, PORT);
  22236. auto result = httplib::stream::Get(cli, "/nonexistent");
  22237. EXPECT_TRUE(result.is_valid());
  22238. EXPECT_EQ(404, result.status());
  22239. }
  22240. // stream::Post tests
  22241. TEST_F(StreamApiTest, PostBasic) {
  22242. httplib::Client cli(HOST, PORT);
  22243. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22244. "application/json");
  22245. ASSERT_TRUE(result.is_valid());
  22246. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22247. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22248. }
  22249. TEST_F(StreamApiTest, PostWithHeaders) {
  22250. httplib::Client cli(HOST, PORT);
  22251. httplib::Headers headers{{"X-Custom", "value"}};
  22252. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22253. "text/plain");
  22254. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22255. }
  22256. TEST_F(StreamApiTest, PostWithParams) {
  22257. httplib::Client cli(HOST, PORT);
  22258. httplib::Params params{{"k", "v"}};
  22259. auto result =
  22260. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22261. auto body = read_body(result);
  22262. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22263. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22264. }
  22265. TEST_F(StreamApiTest, PostLarge) {
  22266. httplib::Client cli(HOST, PORT);
  22267. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22268. size_t total = 0;
  22269. while (result.next()) {
  22270. total += result.size();
  22271. }
  22272. EXPECT_EQ(100u * 1024u, total);
  22273. }
  22274. // stream::Put/Patch tests
  22275. TEST_F(StreamApiTest, PutAndPatch) {
  22276. httplib::Client cli(HOST, PORT);
  22277. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22278. EXPECT_EQ("PUT:test", read_body(put));
  22279. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22280. EXPECT_EQ("PATCH:test", read_body(patch));
  22281. }
  22282. // stream::Delete tests
  22283. TEST_F(StreamApiTest, Delete) {
  22284. httplib::Client cli(HOST, PORT);
  22285. auto del1 = httplib::stream::Delete(cli, "/resource");
  22286. EXPECT_EQ("Deleted", read_body(del1));
  22287. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22288. EXPECT_EQ("Deleted:data", read_body(del2));
  22289. }
  22290. // stream::Head/Options tests
  22291. TEST_F(StreamApiTest, HeadAndOptions) {
  22292. httplib::Client cli(HOST, PORT);
  22293. auto head = httplib::stream::Head(cli, "/head-test");
  22294. EXPECT_TRUE(head.is_valid());
  22295. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22296. auto opts = httplib::stream::Options(cli, "/options");
  22297. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22298. }
  22299. // SSL stream::* tests
  22300. #ifdef CPPHTTPLIB_SSL_ENABLED
  22301. class SSLStreamApiTest : public ::testing::Test {
  22302. protected:
  22303. void SetUp() override {
  22304. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22305. res.set_content("Hello SSL!", "text/plain");
  22306. });
  22307. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22308. res.set_content(req.body, "text/plain");
  22309. });
  22310. port_ = svr_.bind_to_any_port("127.0.0.1");
  22311. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22312. svr_.wait_until_ready();
  22313. }
  22314. void TearDown() override {
  22315. svr_.stop();
  22316. if (thread_.joinable()) thread_.join();
  22317. }
  22318. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22319. std::thread thread_;
  22320. int port_ = 0;
  22321. };
  22322. TEST_F(SSLStreamApiTest, GetAndPost) {
  22323. httplib::SSLClient cli("127.0.0.1", port_);
  22324. cli.enable_server_certificate_verification(false);
  22325. auto get = httplib::stream::Get(cli, "/hello");
  22326. EXPECT_EQ("Hello SSL!", read_body(get));
  22327. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22328. EXPECT_EQ("test", read_body(post));
  22329. }
  22330. #endif
  22331. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22332. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22333. // BodyReader
  22334. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22335. // Test that read timeout during streaming is detected
  22336. // Use a large content-length response where server delays mid-stream
  22337. Server svr;
  22338. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22339. // Send a large response with delay in the middle
  22340. res.set_content_provider(
  22341. 1000, // content_length
  22342. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22343. if (offset < 100) {
  22344. // Send first 100 bytes immediately
  22345. std::string data(100, 'A');
  22346. sink.write(data.c_str(), data.size());
  22347. return true;
  22348. }
  22349. // Then delay longer than client timeout
  22350. std::this_thread::sleep_for(std::chrono::seconds(3));
  22351. std::string data(900, 'B');
  22352. sink.write(data.c_str(), data.size());
  22353. return true;
  22354. });
  22355. });
  22356. auto port = 8091;
  22357. std::thread t([&]() { svr.listen("localhost", port); });
  22358. svr.wait_until_ready();
  22359. Client cli("localhost", port);
  22360. cli.set_read_timeout(1, 0); // 1 second timeout
  22361. auto handle = cli.open_stream("GET", "/slow-stream");
  22362. ASSERT_TRUE(handle.is_valid());
  22363. char buf[256];
  22364. ssize_t total = 0;
  22365. ssize_t n;
  22366. bool got_error = false;
  22367. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22368. total += n;
  22369. }
  22370. if (n < 0) {
  22371. got_error = true;
  22372. // Should be timeout or read error
  22373. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22374. handle.get_read_error() == Error::Read)
  22375. << "Actual error: " << to_string(handle.get_read_error());
  22376. }
  22377. // Either we got an error, or we got less data than expected
  22378. EXPECT_TRUE(got_error || total < 1000)
  22379. << "Expected timeout but got all " << total << " bytes";
  22380. svr.stop();
  22381. t.join();
  22382. }
  22383. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22384. // Test connection closed detection via BodyReader
  22385. Server svr;
  22386. std::atomic<bool> close_now{false};
  22387. svr.Get("/will-close", [&](const Request &, Response &res) {
  22388. res.set_content_provider(
  22389. 10000, // Large content_length that we won't fully send
  22390. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22391. if (offset < 100) {
  22392. std::string data(100, 'X');
  22393. sink.write(data.c_str(), data.size());
  22394. return true;
  22395. }
  22396. // Wait for signal then abort
  22397. while (!close_now) {
  22398. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22399. }
  22400. return false; // Abort - server will close connection
  22401. });
  22402. });
  22403. auto port = 8092;
  22404. std::thread t([&]() { svr.listen("localhost", port); });
  22405. svr.wait_until_ready();
  22406. Client cli("localhost", port);
  22407. auto handle = cli.open_stream("GET", "/will-close");
  22408. ASSERT_TRUE(handle.is_valid());
  22409. char buf[256];
  22410. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22411. EXPECT_GT(n, 0) << "First read should succeed";
  22412. // Signal server to close
  22413. close_now = true;
  22414. // Keep reading until error or EOF
  22415. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22416. // Keep reading
  22417. }
  22418. // Should get an error since content_length wasn't satisfied
  22419. if (n < 0) {
  22420. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22421. handle.get_read_error() == Error::Read)
  22422. << "Actual error: " << to_string(handle.get_read_error());
  22423. }
  22424. svr.stop();
  22425. t.join();
  22426. }
  22427. #ifdef CPPHTTPLIB_SSL_ENABLED
  22428. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22429. // Test that read timeout during SSL streaming is detected
  22430. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22431. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22432. res.set_content_provider(
  22433. 1000, "text/plain",
  22434. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22435. if (offset < 100) {
  22436. std::string data(100, 'A');
  22437. sink.write(data.c_str(), data.size());
  22438. return true;
  22439. }
  22440. std::this_thread::sleep_for(std::chrono::seconds(3));
  22441. std::string data(900, 'B');
  22442. sink.write(data.c_str(), data.size());
  22443. return true;
  22444. });
  22445. });
  22446. auto port = 8093;
  22447. std::thread t([&]() { svr.listen("localhost", port); });
  22448. svr.wait_until_ready();
  22449. SSLClient cli("localhost", port);
  22450. cli.enable_server_certificate_verification(false);
  22451. cli.set_read_timeout(1, 0); // 1 second timeout
  22452. auto handle = cli.open_stream("GET", "/slow-stream");
  22453. ASSERT_TRUE(handle.is_valid());
  22454. char buf[256];
  22455. ssize_t total = 0;
  22456. ssize_t n;
  22457. bool got_error = false;
  22458. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22459. total += n;
  22460. }
  22461. if (n < 0) {
  22462. got_error = true;
  22463. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22464. handle.get_read_error() == Error::Read)
  22465. << "Actual error: " << to_string(handle.get_read_error());
  22466. }
  22467. EXPECT_TRUE(got_error || total < 1000)
  22468. << "Expected timeout but got all " << total << " bytes";
  22469. svr.stop();
  22470. t.join();
  22471. }
  22472. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22473. // Test SSL connection closed detection
  22474. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22475. std::atomic<bool> close_now{false};
  22476. svr.Get("/will-close", [&](const Request &, Response &res) {
  22477. res.set_content_provider(
  22478. 10000, "text/plain",
  22479. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22480. if (offset < 100) {
  22481. std::string data(100, 'X');
  22482. sink.write(data.c_str(), data.size());
  22483. return true;
  22484. }
  22485. while (!close_now) {
  22486. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22487. }
  22488. return false;
  22489. });
  22490. });
  22491. auto port = 8094;
  22492. std::thread t([&]() { svr.listen("localhost", port); });
  22493. svr.wait_until_ready();
  22494. SSLClient cli("localhost", port);
  22495. cli.enable_server_certificate_verification(false);
  22496. auto handle = cli.open_stream("GET", "/will-close");
  22497. ASSERT_TRUE(handle.is_valid());
  22498. char buf[256];
  22499. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22500. EXPECT_GT(n, 0);
  22501. // Signal server to close
  22502. close_now = true;
  22503. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22504. // Keep reading
  22505. }
  22506. if (n < 0) {
  22507. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22508. handle.get_read_error() == Error::Read)
  22509. << "Actual error: " << to_string(handle.get_read_error());
  22510. }
  22511. svr.stop();
  22512. t.join();
  22513. }
  22514. #endif
  22515. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22516. using namespace httplib;
  22517. // Create a test file
  22518. const char *fname = "etag_testfile.txt";
  22519. const char *content = "etag-content";
  22520. {
  22521. std::ofstream ofs(fname);
  22522. ofs << content;
  22523. ASSERT_TRUE(ofs.good());
  22524. }
  22525. Server svr;
  22526. svr.set_mount_point("/static", ".");
  22527. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22528. svr.wait_until_ready();
  22529. Client cli(HOST, PORT);
  22530. // First request: should get 200 with ETag header
  22531. auto res1 = cli.Get("/static/etag_testfile.txt");
  22532. ASSERT_TRUE(res1);
  22533. ASSERT_EQ(200, res1->status);
  22534. ASSERT_TRUE(res1->has_header("ETag"));
  22535. std::string etag = res1->get_header_value("ETag");
  22536. EXPECT_FALSE(etag.empty());
  22537. // Verify ETag format: W/"hex-hex"
  22538. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22539. EXPECT_EQ('W', etag[0]);
  22540. EXPECT_EQ('/', etag[1]);
  22541. EXPECT_EQ('"', etag[2]);
  22542. EXPECT_EQ('"', etag.back());
  22543. // Exact match: expect 304 Not Modified
  22544. Headers h2 = {{"If-None-Match", etag}};
  22545. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22546. ASSERT_TRUE(res2);
  22547. EXPECT_EQ(304, res2->status);
  22548. // Wildcard match: expect 304 Not Modified
  22549. Headers h3 = {{"If-None-Match", "*"}};
  22550. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22551. ASSERT_TRUE(res3);
  22552. EXPECT_EQ(304, res3->status);
  22553. // Non-matching ETag: expect 200
  22554. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22555. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22556. ASSERT_TRUE(res4);
  22557. EXPECT_EQ(200, res4->status);
  22558. // Multiple ETags with one matching: expect 304
  22559. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22560. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22561. ASSERT_TRUE(res5);
  22562. EXPECT_EQ(304, res5->status);
  22563. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22564. // that equivalent to the single comma-separated list above, so the match on
  22565. // the second line must still be found.
  22566. Headers h6;
  22567. h6.emplace("If-None-Match", "W/\"other\"");
  22568. h6.emplace("If-None-Match", etag);
  22569. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22570. ASSERT_TRUE(res6);
  22571. EXPECT_EQ(304, res6->status);
  22572. svr.stop();
  22573. t.join();
  22574. std::remove(fname);
  22575. }
  22576. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22577. using namespace httplib;
  22578. Server svr;
  22579. svr.set_mount_point("/static", ".");
  22580. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22581. svr.wait_until_ready();
  22582. Client cli(HOST, PORT);
  22583. // Send If-None-Match: * to a non-existent file
  22584. Headers h = {{"If-None-Match", "*"}};
  22585. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22587. EXPECT_EQ(404, res->status);
  22588. svr.stop();
  22589. t.join();
  22590. }
  22591. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22592. using namespace httplib;
  22593. // Create a test file
  22594. const char *fname = "etag_boundary_testfile.txt";
  22595. const char *content = "boundary-test";
  22596. {
  22597. std::ofstream ofs(fname);
  22598. ofs << content;
  22599. ASSERT_TRUE(ofs.good());
  22600. }
  22601. Server svr;
  22602. svr.set_mount_point("/static", ".");
  22603. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22604. svr.wait_until_ready();
  22605. Client cli(HOST, PORT);
  22606. // Get the actual ETag
  22607. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22608. ASSERT_TRUE(res1);
  22609. ASSERT_EQ(200, res1->status);
  22610. ASSERT_TRUE(res1->has_header("ETag"));
  22611. std::string etag = res1->get_header_value("ETag");
  22612. // Test 1: Very long ETag value (longer than actual ETag)
  22613. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22614. Headers h1 = {{"If-None-Match", "W/"
  22615. "\"very-long-etag-value-that-is-much-longer-"
  22616. "than-the-actual-etag-value\""}};
  22617. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22618. ASSERT_TRUE(res2);
  22619. EXPECT_EQ(200, res2->status); // Should not match
  22620. // Test 2: Long string followed by wildcard
  22621. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22622. // string)
  22623. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22624. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22625. ASSERT_TRUE(res3);
  22626. EXPECT_EQ(304, res3->status); // Should match on "*"
  22627. // Test 3: Wildcard followed by long string
  22628. // Should match on "*" immediately and return 304
  22629. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22630. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22631. ASSERT_TRUE(res4);
  22632. EXPECT_EQ(304, res4->status); // Should match on "*"
  22633. // Test 4: Multiple long non-matching values
  22634. // Should NOT match and return 200 (test that all comparisons are safe)
  22635. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22636. "W/\"second-long-non-matching-value\", "
  22637. "W/\"third-long-non-matching-value\""}};
  22638. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22639. ASSERT_TRUE(res5);
  22640. EXPECT_EQ(200, res5->status); // Should not match
  22641. // Test 5: Single character that is not "*" (edge case)
  22642. Headers h5 = {{"If-None-Match", "X"}};
  22643. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22644. ASSERT_TRUE(res6);
  22645. EXPECT_EQ(200, res6->status); // Should not match
  22646. svr.stop();
  22647. t.join();
  22648. std::remove(fname);
  22649. }
  22650. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22651. using namespace httplib;
  22652. // Create a test file
  22653. const char *fname = "ims_testfile.txt";
  22654. const char *content = "if-modified-since-test";
  22655. {
  22656. std::ofstream ofs(fname);
  22657. ofs << content;
  22658. ASSERT_TRUE(ofs.good());
  22659. }
  22660. Server svr;
  22661. svr.set_mount_point("/static", ".");
  22662. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22663. svr.wait_until_ready();
  22664. Client cli(HOST, PORT);
  22665. // First request: should get 200 with Last-Modified header
  22666. auto res1 = cli.Get("/static/ims_testfile.txt");
  22667. ASSERT_TRUE(res1);
  22668. ASSERT_EQ(200, res1->status);
  22669. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22670. std::string last_modified = res1->get_header_value("Last-Modified");
  22671. EXPECT_FALSE(last_modified.empty());
  22672. // If-Modified-Since with same time: expect 304
  22673. Headers h2 = {{"If-Modified-Since", last_modified}};
  22674. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22675. ASSERT_TRUE(res2);
  22676. EXPECT_EQ(304, res2->status);
  22677. // If-Modified-Since with future time: expect 304
  22678. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22679. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22680. ASSERT_TRUE(res3);
  22681. EXPECT_EQ(304, res3->status);
  22682. // If-Modified-Since with past time: expect 200
  22683. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22684. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22685. ASSERT_TRUE(res4);
  22686. EXPECT_EQ(200, res4->status);
  22687. // If-None-Match takes precedence over If-Modified-Since
  22688. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22689. ASSERT_TRUE(res1->has_header("ETag"));
  22690. std::string etag = res1->get_header_value("ETag");
  22691. Headers h5 = {{"If-None-Match", etag},
  22692. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22693. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22694. ASSERT_TRUE(res5);
  22695. EXPECT_EQ(304, res5->status);
  22696. svr.stop();
  22697. t.join();
  22698. std::remove(fname);
  22699. }
  22700. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22701. using namespace httplib;
  22702. Server svr;
  22703. // Endpoint that returns compressible content
  22704. svr.Get("/compressible", [](const Request &, Response &res) {
  22705. // Return a large enough body to trigger compression
  22706. std::string body(1000, 'a');
  22707. res.set_content(body, "text/plain");
  22708. });
  22709. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22710. svr.wait_until_ready();
  22711. Client cli(HOST, PORT);
  22712. // Request with gzip support: should get Vary header when compressed
  22713. cli.set_compress(true);
  22714. auto res1 = cli.Get("/compressible");
  22715. ASSERT_TRUE(res1);
  22716. EXPECT_EQ(200, res1->status);
  22717. // If Content-Encoding is set, Vary should also be set
  22718. if (res1->has_header("Content-Encoding")) {
  22719. EXPECT_TRUE(res1->has_header("Vary"));
  22720. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22721. }
  22722. // Request without Accept-Encoding header: should not have compression
  22723. Headers h_no_compress;
  22724. auto res2 = cli.Get("/compressible", h_no_compress);
  22725. ASSERT_TRUE(res2);
  22726. EXPECT_EQ(200, res2->status);
  22727. // Verify Vary header is present when compression is applied
  22728. // (the exact behavior depends on server configuration)
  22729. svr.stop();
  22730. t.join();
  22731. }
  22732. TEST(ETagTest, IfRangeWithETag) {
  22733. using namespace httplib;
  22734. // Create a test file with known content
  22735. const char *fname = "if_range_testfile.txt";
  22736. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22737. {
  22738. std::ofstream ofs(fname);
  22739. ofs << content;
  22740. ASSERT_TRUE(ofs.good());
  22741. }
  22742. Server svr;
  22743. svr.set_mount_point("/static", ".");
  22744. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22745. svr.wait_until_ready();
  22746. Client cli(HOST, PORT);
  22747. // First request: get ETag
  22748. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22749. ASSERT_TRUE(res1);
  22750. ASSERT_EQ(200, res1->status);
  22751. ASSERT_TRUE(res1->has_header("ETag"));
  22752. std::string etag = res1->get_header_value("ETag");
  22753. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22754. // Since our server generates weak ETags (W/"..."), If-Range with our
  22755. // ETag should NOT result in partial content - it should return full content.
  22756. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22757. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22758. ASSERT_TRUE(res2);
  22759. // Weak ETag in If-Range -> full content (200), not partial (206)
  22760. EXPECT_EQ(200, res2->status);
  22761. EXPECT_EQ(content, res2->body);
  22762. EXPECT_FALSE(res2->has_header("Content-Range"));
  22763. // Range request with non-matching If-Range (ETag): should get 200 (full
  22764. // content)
  22765. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22766. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22767. ASSERT_TRUE(res3);
  22768. EXPECT_EQ(200, res3->status);
  22769. EXPECT_EQ(content, res3->body);
  22770. EXPECT_FALSE(res3->has_header("Content-Range"));
  22771. // Range request with strong ETag (hypothetical - our server doesn't generate
  22772. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22773. // should return full content)
  22774. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22775. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22776. ASSERT_TRUE(res4);
  22777. EXPECT_EQ(200, res4->status);
  22778. EXPECT_EQ(content, res4->body);
  22779. EXPECT_FALSE(res4->has_header("Content-Range"));
  22780. svr.stop();
  22781. t.join();
  22782. std::remove(fname);
  22783. }
  22784. TEST(ETagTest, IfRangeWithDate) {
  22785. using namespace httplib;
  22786. // Create a test file
  22787. const char *fname = "if_range_date_testfile.txt";
  22788. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22789. {
  22790. std::ofstream ofs(fname);
  22791. ofs << content;
  22792. ASSERT_TRUE(ofs.good());
  22793. }
  22794. Server svr;
  22795. svr.set_mount_point("/static", ".");
  22796. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22797. svr.wait_until_ready();
  22798. Client cli(HOST, PORT);
  22799. // First request: get Last-Modified
  22800. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22801. ASSERT_TRUE(res1);
  22802. ASSERT_EQ(200, res1->status);
  22803. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22804. std::string last_modified = res1->get_header_value("Last-Modified");
  22805. // Range request with matching If-Range (date): should get 206
  22806. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22807. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22808. ASSERT_TRUE(res2);
  22809. EXPECT_EQ(206, res2->status);
  22810. EXPECT_EQ("FGHIJ", res2->body);
  22811. // Range request with old If-Range date: should get 200 (full content)
  22812. Headers h3 = {{"Range", "bytes=5-9"},
  22813. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22814. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22815. ASSERT_TRUE(res3);
  22816. EXPECT_EQ(200, res3->status);
  22817. EXPECT_EQ(content, res3->body);
  22818. // Range request with future If-Range date: should get 206
  22819. Headers h4 = {{"Range", "bytes=0-4"},
  22820. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22821. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22822. ASSERT_TRUE(res4);
  22823. EXPECT_EQ(206, res4->status);
  22824. EXPECT_EQ("ABCDE", res4->body);
  22825. svr.stop();
  22826. t.join();
  22827. std::remove(fname);
  22828. }
  22829. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22830. using namespace httplib;
  22831. const char *fname = "etag_malformed.txt";
  22832. const char *content = "malformed-etag";
  22833. {
  22834. std::ofstream ofs(fname);
  22835. ofs << content;
  22836. ASSERT_TRUE(ofs.good());
  22837. }
  22838. Server svr;
  22839. svr.set_mount_point("/static", ".");
  22840. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22841. svr.wait_until_ready();
  22842. Client cli(HOST, PORT);
  22843. // baseline: should get 200 and an ETag
  22844. auto res1 = cli.Get("/static/etag_malformed.txt");
  22845. ASSERT_TRUE(res1);
  22846. ASSERT_EQ(200, res1->status);
  22847. ASSERT_TRUE(res1->has_header("ETag"));
  22848. // Malformed ETag value (missing quotes) should be treated as non-matching
  22849. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22850. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22851. ASSERT_TRUE(res_bad);
  22852. EXPECT_EQ(200, res_bad->status);
  22853. // Whitespace-only header value should be considered invalid / non-matching
  22854. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22855. "Host: localhost\r\n"
  22856. "If-None-Match: \r\n"
  22857. "Connection: close\r\n"
  22858. "\r\n";
  22859. std::string out;
  22860. ASSERT_TRUE(send_request(5, raw_req, &out));
  22861. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22862. svr.stop();
  22863. t.join();
  22864. std::remove(fname);
  22865. }
  22866. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22867. using namespace httplib;
  22868. const char *fname = "ims_invalid_format.txt";
  22869. const char *content = "ims-bad-format";
  22870. {
  22871. std::ofstream ofs(fname);
  22872. ofs << content;
  22873. ASSERT_TRUE(ofs.good());
  22874. }
  22875. Server svr;
  22876. svr.set_mount_point("/static", ".");
  22877. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22878. svr.wait_until_ready();
  22879. Client cli(HOST, PORT);
  22880. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22881. ASSERT_TRUE(res1);
  22882. ASSERT_EQ(200, res1->status);
  22883. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22884. // If-Modified-Since with invalid format should not result in 304
  22885. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22886. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22887. ASSERT_TRUE(res_bad);
  22888. EXPECT_EQ(200, res_bad->status);
  22889. // If-Range with invalid date format should be treated as mismatch -> full
  22890. // content (200)
  22891. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22892. {"If-Range", "invalid-date"}};
  22893. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22894. ASSERT_TRUE(res_ifrange);
  22895. EXPECT_EQ(200, res_ifrange->status);
  22896. svr.stop();
  22897. t.join();
  22898. std::remove(fname);
  22899. }
  22900. TEST(ETagTest, IfRangeWithMalformedETag) {
  22901. using namespace httplib;
  22902. const char *fname = "ifrange_malformed.txt";
  22903. const std::string content = "0123456789";
  22904. {
  22905. std::ofstream ofs(fname);
  22906. ofs << content;
  22907. ASSERT_TRUE(ofs.good());
  22908. }
  22909. Server svr;
  22910. svr.set_mount_point("/static", ".");
  22911. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22912. svr.wait_until_ready();
  22913. Client cli(HOST, PORT);
  22914. // First request: get ETag
  22915. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22916. ASSERT_TRUE(res1);
  22917. ASSERT_EQ(200, res1->status);
  22918. ASSERT_TRUE(res1->has_header("ETag"));
  22919. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22920. // full content (200)
  22921. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22922. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22923. ASSERT_TRUE(res2);
  22924. EXPECT_EQ(200, res2->status);
  22925. EXPECT_EQ(content, res2->body);
  22926. svr.stop();
  22927. t.join();
  22928. std::remove(fname);
  22929. }
  22930. TEST(ETagTest, ExtremeLargeDateValues) {
  22931. using namespace httplib;
  22932. const char *fname = "ims_extreme_date.txt";
  22933. const char *content = "ims-extreme-date";
  22934. {
  22935. std::ofstream ofs(fname);
  22936. ofs << content;
  22937. ASSERT_TRUE(ofs.good());
  22938. }
  22939. Server svr;
  22940. svr.set_mount_point("/static", ".");
  22941. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22942. svr.wait_until_ready();
  22943. Client cli(HOST, PORT);
  22944. auto res1 = cli.Get(std::string("/static/") + fname);
  22945. ASSERT_TRUE(res1);
  22946. ASSERT_EQ(200, res1->status);
  22947. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22948. // Extremely large year that may overflow date parsing routines.
  22949. Headers h_large_date = {
  22950. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22951. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22952. ASSERT_TRUE(res_bad);
  22953. // Expect server to treat this as invalid/mismatch and return full content
  22954. EXPECT_EQ(200, res_bad->status);
  22955. // If-Range with extremely large date should be treated as mismatch -> full
  22956. // content (200)
  22957. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22958. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22959. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22960. ASSERT_TRUE(res_ifrange);
  22961. EXPECT_EQ(200, res_ifrange->status);
  22962. svr.stop();
  22963. t.join();
  22964. std::remove(fname);
  22965. }
  22966. TEST(ETagTest, NegativeFileModificationTime) {
  22967. using namespace httplib;
  22968. const char *fname = "ims_negative_mtime.txt";
  22969. const std::string content = "negative-mtime";
  22970. {
  22971. std::ofstream ofs(fname);
  22972. ofs << content;
  22973. ASSERT_TRUE(ofs.good());
  22974. }
  22975. // Try to set file mtime to a negative value. This may fail on some
  22976. // platforms/filesystems; if it fails, the test will still verify server
  22977. // behaves safely by performing a regular conditional request.
  22978. #if defined(__APPLE__) || defined(__linux__)
  22979. bool set_negative = false;
  22980. do {
  22981. struct timeval times[2];
  22982. // access time: now
  22983. times[0].tv_sec = time(nullptr);
  22984. times[0].tv_usec = 0;
  22985. // modification time: negative (e.g., -1)
  22986. times[1].tv_sec = -1;
  22987. times[1].tv_usec = 0;
  22988. if (utimes(fname, times) == 0) { set_negative = true; }
  22989. } while (0);
  22990. #else
  22991. bool set_negative = false;
  22992. #endif
  22993. Server svr;
  22994. svr.set_mount_point("/static", ".");
  22995. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22996. svr.wait_until_ready();
  22997. Client cli(HOST, PORT);
  22998. auto res1 = cli.Get(std::string("/static/") + fname);
  22999. ASSERT_TRUE(res1);
  23000. ASSERT_EQ(200, res1->status);
  23001. bool has_last_modified = res1->has_header("Last-Modified");
  23002. std::string last_modified;
  23003. if (has_last_modified) {
  23004. last_modified = res1->get_header_value("Last-Modified");
  23005. }
  23006. if (set_negative) {
  23007. // If we successfully set a negative mtime, ensure server returns a
  23008. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  23009. // with an old date and ensure server handles it without crash.
  23010. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  23011. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  23012. ASSERT_TRUE(res2);
  23013. // Behavior may vary; at minimum ensure server responds (200 or 304).
  23014. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  23015. } else {
  23016. // Could not set negative mtime on this platform; fall back to verifying
  23017. // that normal invalid/malformed dates are treated safely (non-304).
  23018. Headers h_bad_date = {
  23019. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23020. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  23021. ASSERT_TRUE(res_bad);
  23022. EXPECT_EQ(200, res_bad->status);
  23023. }
  23024. svr.stop();
  23025. t.join();
  23026. std::remove(fname);
  23027. }
  23028. //==============================================================================
  23029. // Integration Tests with Server
  23030. //==============================================================================
  23031. class SSEIntegrationTest : public ::testing::Test {
  23032. protected:
  23033. void SetUp() override {
  23034. stop_server_.store(false);
  23035. events_.clear();
  23036. server_ = httplib::detail::make_unique<Server>();
  23037. setup_server();
  23038. start_server();
  23039. }
  23040. void TearDown() override {
  23041. stop_server_.store(true);
  23042. event_cv_.notify_all();
  23043. server_->stop();
  23044. if (server_thread_.joinable()) { server_thread_.join(); }
  23045. }
  23046. void setup_server() {
  23047. // Simple SSE endpoint
  23048. server_->Get("/events", [this](const Request &req, Response &res) {
  23049. auto last_id = req.get_header_value("Last-Event-ID");
  23050. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  23051. res.set_chunked_content_provider(
  23052. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23053. std::unique_lock<std::mutex> lock(event_mutex_);
  23054. if (event_cv_.wait_for(
  23055. lock, std::chrono::milliseconds(200), [this] {
  23056. return !events_.empty() || stop_server_.load();
  23057. })) {
  23058. if (stop_server_.load()) { return false; }
  23059. if (!events_.empty()) {
  23060. std::string event = events_.front();
  23061. events_.erase(events_.begin());
  23062. sink.write(event.data(), event.size());
  23063. return true;
  23064. }
  23065. }
  23066. return !stop_server_.load();
  23067. });
  23068. });
  23069. // Endpoint that returns error
  23070. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23071. res.status = 500;
  23072. res.set_content("Internal Server Error", "text/plain");
  23073. });
  23074. // Endpoint for custom event types
  23075. server_->Get("/custom-events", [](const Request &, Response &res) {
  23076. res.set_chunked_content_provider(
  23077. "text/event-stream", [](size_t offset, DataSink &sink) {
  23078. if (offset == 0) {
  23079. std::string event = "event: update\ndata: updated\n\n"
  23080. "event: delete\ndata: deleted\n\n";
  23081. sink.write(event.data(), event.size());
  23082. }
  23083. return false; // End stream after sending
  23084. });
  23085. });
  23086. }
  23087. void start_server() {
  23088. port_ = server_->bind_to_any_port(HOST);
  23089. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23090. // Wait for server to start
  23091. while (!server_->is_running()) {
  23092. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23093. }
  23094. }
  23095. int get_port() const { return port_; }
  23096. void send_event(const std::string &event) {
  23097. std::lock_guard<std::mutex> lock(event_mutex_);
  23098. events_.push_back(event);
  23099. event_cv_.notify_all();
  23100. }
  23101. std::unique_ptr<Server> server_;
  23102. std::thread server_thread_;
  23103. std::mutex event_mutex_;
  23104. std::condition_variable event_cv_;
  23105. std::vector<std::string> events_;
  23106. std::atomic<bool> stop_server_{false};
  23107. std::string last_received_event_id_;
  23108. int port_ = 0;
  23109. };
  23110. //==============================================================================
  23111. // SSE Parser Tests
  23112. //==============================================================================
  23113. struct SSEParseResult {
  23114. std::vector<sse::SSEMessage> events;
  23115. std::vector<std::string> ids;
  23116. std::vector<int> retries;
  23117. bool ok = true;
  23118. std::string trace; // Every handler call in order
  23119. };
  23120. static SSEParseResult
  23121. sse_parse(const std::vector<std::string> &chunks,
  23122. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23123. SSEParseResult r;
  23124. detail::SSEParser parser(
  23125. [&](const sse::SSEMessage &msg) {
  23126. r.events.push_back(msg);
  23127. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23128. },
  23129. [&](const std::string &id) {
  23130. r.ids.push_back(id);
  23131. r.trace += "id[" + id + "]";
  23132. },
  23133. [&](int retry_ms) {
  23134. r.retries.push_back(retry_ms);
  23135. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23136. },
  23137. max_event_length);
  23138. for (const auto &chunk : chunks) {
  23139. if (!parser.parse(chunk.data(), chunk.size())) {
  23140. r.ok = false;
  23141. break;
  23142. }
  23143. }
  23144. return r;
  23145. }
  23146. static SSEParseResult sse_parse(const std::string &stream) {
  23147. return sse_parse(std::vector<std::string>{stream});
  23148. }
  23149. TEST(SSEParserTest, SingleLineData) {
  23150. auto r = sse_parse("data: hello\n\n");
  23151. ASSERT_EQ(r.events.size(), 1u);
  23152. EXPECT_EQ(r.events[0].data, "hello");
  23153. EXPECT_EQ(r.events[0].event, "message");
  23154. }
  23155. TEST(SSEParserTest, MultiLineData) {
  23156. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23157. ASSERT_EQ(r.events.size(), 1u);
  23158. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23159. }
  23160. TEST(SSEParserTest, CustomEventType) {
  23161. auto r = sse_parse("event: update\ndata: payload\n\n");
  23162. ASSERT_EQ(r.events.size(), 1u);
  23163. EXPECT_EQ(r.events[0].event, "update");
  23164. EXPECT_EQ(r.events[0].data, "payload");
  23165. }
  23166. TEST(SSEParserTest, EventIdHandling) {
  23167. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23168. ASSERT_EQ(r.events.size(), 1u);
  23169. EXPECT_EQ(r.events[0].id, "12345");
  23170. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23171. }
  23172. TEST(SSEParserTest, EmptyEventId) {
  23173. auto r = sse_parse("id:\ndata: test\n\n");
  23174. ASSERT_EQ(r.events.size(), 1u);
  23175. EXPECT_EQ(r.events[0].id, "");
  23176. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23177. }
  23178. TEST(SSEParserTest, CommentsIgnored) {
  23179. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23180. ASSERT_EQ(r.events.size(), 1u);
  23181. EXPECT_EQ(r.events[0].data, "hello");
  23182. EXPECT_EQ(r.events[0].event, "message");
  23183. }
  23184. TEST(SSEParserTest, ColonInValue) {
  23185. auto r = sse_parse("data: hello:world:test\n\n");
  23186. ASSERT_EQ(r.events.size(), 1u);
  23187. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23188. }
  23189. TEST(SSEParserTest, FieldNameOnly) {
  23190. // A line without a colon is a field name with an empty value
  23191. auto r = sse_parse("data\n\n");
  23192. ASSERT_EQ(r.events.size(), 1u);
  23193. EXPECT_EQ(r.events[0].data, "");
  23194. }
  23195. TEST(SSEParserTest, TrailingCarriageReturn) {
  23196. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23197. ASSERT_EQ(r.events.size(), 1u);
  23198. EXPECT_EQ(r.events[0].event, "update");
  23199. EXPECT_EQ(r.events[0].data, "hello");
  23200. }
  23201. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23202. auto r = sse_parse("data\r\n\r\n");
  23203. ASSERT_EQ(r.events.size(), 1u);
  23204. EXPECT_EQ(r.events[0].data, "");
  23205. }
  23206. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23207. auto r = sse_parse("event: update\rdata: hello\r\r");
  23208. ASSERT_EQ(r.events.size(), 1u);
  23209. EXPECT_EQ(r.events[0].event, "update");
  23210. EXPECT_EQ(r.events[0].data, "hello");
  23211. }
  23212. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23213. // Chunk boundaries fall inside every \r\n and right before the first one
  23214. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23215. "\ndata: hello\r", "\n\r", "\n"});
  23216. ASSERT_EQ(r.events.size(), 1u);
  23217. EXPECT_EQ(r.events[0].event, "update");
  23218. EXPECT_EQ(r.events[0].data, "hello");
  23219. }
  23220. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23221. // Only a BOM at the start of the stream is ignored
  23222. auto r = sse_parse("\xEF\xBB\xBF"
  23223. "data: first\n\n"
  23224. "\xEF\xBB\xBF"
  23225. "data: second\n\n");
  23226. ASSERT_EQ(r.events.size(), 1u);
  23227. EXPECT_EQ(r.events[0].data, "first");
  23228. }
  23229. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23230. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23231. ASSERT_EQ(r.events.size(), 1u);
  23232. EXPECT_EQ(r.events[0].data, "hello");
  23233. EXPECT_EQ(r.events[0].event, "message");
  23234. }
  23235. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23236. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23237. ASSERT_EQ(r.events.size(), 2u);
  23238. EXPECT_EQ(r.events[0].data, "hello");
  23239. EXPECT_EQ(r.events[1].data, "hello");
  23240. }
  23241. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23242. // An event without data is not dispatched, and its type must not leak
  23243. // into the next event
  23244. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23245. ASSERT_EQ(r.events.size(), 1u);
  23246. EXPECT_EQ(r.events[0].event, "message");
  23247. EXPECT_EQ(r.events[0].data, "hello");
  23248. }
  23249. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23250. // Also when the empty field replaces an earlier type
  23251. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23252. ASSERT_EQ(r.events.size(), 2u);
  23253. EXPECT_EQ(r.events[0].event, "message");
  23254. EXPECT_EQ(r.events[1].event, "message");
  23255. }
  23256. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23257. auto r = sse_parse("id: 42\n\n");
  23258. EXPECT_TRUE(r.events.empty());
  23259. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23260. }
  23261. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23262. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23263. ASSERT_EQ(r.events.size(), 2u);
  23264. EXPECT_EQ(r.events[0].id, "1");
  23265. EXPECT_EQ(r.events[1].id, "");
  23266. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23267. }
  23268. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23269. // Ids that cannot be carried in a Last-Event-ID header
  23270. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23271. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23272. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23273. }
  23274. TEST(SSEParserTest, RetryDigitsOnly) {
  23275. auto r = sse_parse("retry: 1000\n");
  23276. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23277. // A value that is not all ASCII digits, or does not fit, is ignored
  23278. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23279. EXPECT_TRUE(r.retries.empty());
  23280. }
  23281. TEST(SSEParserTest, CompleteEventParsing) {
  23282. auto r = sse_parse("event: notification\nid: evt-42\n"
  23283. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23284. ASSERT_EQ(r.events.size(), 1u);
  23285. EXPECT_EQ(r.events[0].event, "notification");
  23286. EXPECT_EQ(r.events[0].id, "evt-42");
  23287. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23288. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23289. }
  23290. TEST(SSEParserTest, IncompleteEventNotReported) {
  23291. // An event still waiting for its blank line when the stream ends is
  23292. // discarded per the SSE spec
  23293. auto r = sse_parse("id: 1\ndata: x\n");
  23294. EXPECT_TRUE(r.events.empty());
  23295. EXPECT_TRUE(r.ids.empty());
  23296. }
  23297. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23298. const std::vector<std::string> streams = {
  23299. "\xEF\xBB\xBF"
  23300. "data: bom\r\n\r\n",
  23301. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23302. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23303. };
  23304. for (const auto &stream : streams) {
  23305. auto expected = sse_parse(stream).trace;
  23306. ASSERT_FALSE(expected.empty());
  23307. for (size_t i = 0; i <= stream.size(); i++) {
  23308. auto r = sse_parse(
  23309. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23310. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23311. }
  23312. std::vector<std::string> bytes;
  23313. for (auto c : stream) {
  23314. bytes.emplace_back(1, c);
  23315. }
  23316. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23317. }
  23318. }
  23319. TEST(SSEParserTest, MaxEventLength) {
  23320. // A line still waiting for its end
  23321. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23322. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23323. // Data accumulated over the lines of one event
  23324. EXPECT_TRUE(
  23325. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23326. EXPECT_FALSE(
  23327. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23328. // 0 means no limit
  23329. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23330. // Events completed in the same chunk are still reported
  23331. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23332. EXPECT_FALSE(r.ok);
  23333. ASSERT_EQ(r.events.size(), 1u);
  23334. EXPECT_EQ(r.events[0].data, "a");
  23335. }
  23336. TEST(SSEMessageTest, Clear) {
  23337. sse::SSEMessage msg;
  23338. msg.event = "custom";
  23339. msg.data = "some data";
  23340. msg.id = "123";
  23341. msg.clear();
  23342. EXPECT_EQ(msg.event, "message");
  23343. EXPECT_EQ(msg.data, "");
  23344. EXPECT_EQ(msg.id, "");
  23345. }
  23346. //==============================================================================
  23347. // SSE Integration Tests
  23348. //==============================================================================
  23349. // Test: Successful connection and on_open callback
  23350. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23351. // Add a simple endpoint that sends one event and closes
  23352. server_->Get("/simple-event", [](const Request &, Response &res) {
  23353. res.set_chunked_content_provider(
  23354. "text/event-stream", [](size_t offset, DataSink &sink) {
  23355. if (offset == 0) {
  23356. std::string event = "data: hello\n\n";
  23357. sink.write(event.data(), event.size());
  23358. }
  23359. return false; // Close stream after sending
  23360. });
  23361. });
  23362. Client client("localhost", get_port());
  23363. sse::SSEClient sse(client, "/simple-event");
  23364. std::atomic<bool> open_called{false};
  23365. std::atomic<bool> message_received{false};
  23366. sse.on_open([&open_called]() { open_called.store(true); });
  23367. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23368. if (msg.data == "hello") { message_received.store(true); }
  23369. });
  23370. sse.set_reconnect_interval(100);
  23371. sse.set_max_reconnect_attempts(1);
  23372. // Start async
  23373. sse.start_async();
  23374. // Wait for message to be processed
  23375. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23376. sse.stop();
  23377. EXPECT_TRUE(open_called.load());
  23378. EXPECT_TRUE(message_received.load());
  23379. }
  23380. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23381. // A data line that never ends.
  23382. server_->Get("/endless-line", [](const Request &, Response &res) {
  23383. res.set_chunked_content_provider(
  23384. "text/event-stream", [](size_t offset, DataSink &sink) {
  23385. if (offset == 0) { sink.write("data: ", 6); }
  23386. std::string chunk(64 * 1024, 'A');
  23387. return sink.write(chunk.data(), chunk.size());
  23388. });
  23389. });
  23390. Client client("localhost", get_port());
  23391. sse::SSEClient sse(client, "/endless-line");
  23392. std::atomic<bool> too_long{false};
  23393. sse.on_error([&](Error err) {
  23394. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23395. });
  23396. sse.set_max_reconnect_attempts(1);
  23397. sse.start_async();
  23398. for (int i = 0; i < 500 && !too_long; i++) {
  23399. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23400. }
  23401. sse.stop();
  23402. EXPECT_TRUE(too_long);
  23403. }
  23404. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23405. // Far more in all than the client's payload limit below.
  23406. server_->Get("/many-events", [](const Request &, Response &res) {
  23407. res.set_chunked_content_provider(
  23408. "text/event-stream", [](size_t offset, DataSink &sink) {
  23409. if (offset == 0) {
  23410. std::string events;
  23411. for (int i = 0; i < 1000; i++) {
  23412. events += "data: message\n\n";
  23413. }
  23414. sink.write(events.data(), events.size());
  23415. }
  23416. return false;
  23417. });
  23418. });
  23419. Client client("localhost", get_port());
  23420. client.set_payload_max_length(1024);
  23421. sse::SSEClient sse(client, "/many-events");
  23422. std::atomic<int> messages{0};
  23423. std::atomic<bool> too_large{false};
  23424. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23425. sse.on_error([&](Error err) {
  23426. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23427. });
  23428. sse.set_max_reconnect_attempts(1);
  23429. sse.start_async();
  23430. for (int i = 0; i < 500 && messages < 1000; i++) {
  23431. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23432. }
  23433. sse.stop();
  23434. EXPECT_GE(messages.load(), 1000);
  23435. EXPECT_FALSE(too_large);
  23436. }
  23437. // Test: on_message callback
  23438. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23439. // Endpoint that sends multiple events then closes
  23440. server_->Get("/multi-event", [](const Request &, Response &res) {
  23441. res.set_chunked_content_provider(
  23442. "text/event-stream", [](size_t offset, DataSink &sink) {
  23443. if (offset == 0) {
  23444. std::string events = "data: message1\n\ndata: message2\n\n";
  23445. sink.write(events.data(), events.size());
  23446. }
  23447. return false;
  23448. });
  23449. });
  23450. Client client("localhost", get_port());
  23451. sse::SSEClient sse(client, "/multi-event");
  23452. std::vector<std::string> received_messages;
  23453. std::mutex messages_mutex;
  23454. sse.on_message([&](const sse::SSEMessage &msg) {
  23455. std::lock_guard<std::mutex> lock(messages_mutex);
  23456. received_messages.push_back(msg.data);
  23457. });
  23458. sse.set_reconnect_interval(100);
  23459. sse.set_max_reconnect_attempts(1);
  23460. sse.start_async();
  23461. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23462. sse.stop();
  23463. std::lock_guard<std::mutex> lock(messages_mutex);
  23464. EXPECT_GE(received_messages.size(), 2u);
  23465. if (received_messages.size() >= 2) {
  23466. EXPECT_EQ(received_messages[0], "message1");
  23467. EXPECT_EQ(received_messages[1], "message2");
  23468. }
  23469. }
  23470. // Test: on_event for specific types
  23471. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23472. Client client("localhost", get_port());
  23473. sse::SSEClient sse(client, "/custom-events");
  23474. std::atomic<bool> update_received{false};
  23475. std::atomic<bool> delete_received{false};
  23476. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23477. if (msg.data == "updated") { update_received.store(true); }
  23478. });
  23479. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23480. if (msg.data == "deleted") { delete_received.store(true); }
  23481. });
  23482. sse.set_max_reconnect_attempts(1);
  23483. sse.start_async();
  23484. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23485. sse.stop();
  23486. EXPECT_TRUE(update_received.load());
  23487. EXPECT_TRUE(delete_received.load());
  23488. }
  23489. // Test: on_error callback on connection failure
  23490. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23491. // Connect to a non-existent port
  23492. Client client("localhost", 59999);
  23493. sse::SSEClient sse(client, "/events");
  23494. std::atomic<bool> error_called{false};
  23495. Error received_error = Error::Success;
  23496. sse.on_error([&](Error err) {
  23497. error_called.store(true);
  23498. received_error = err;
  23499. });
  23500. sse.set_reconnect_interval(50);
  23501. sse.set_max_reconnect_attempts(1);
  23502. sse.start_async();
  23503. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23504. sse.stop();
  23505. EXPECT_TRUE(error_called.load());
  23506. EXPECT_NE(received_error, Error::Success);
  23507. }
  23508. // Test: Last-Event-ID header sent on reconnect
  23509. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23510. // Endpoint that sends event with ID
  23511. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23512. res.set_chunked_content_provider(
  23513. "text/event-stream", [](size_t offset, DataSink &sink) {
  23514. if (offset == 0) {
  23515. std::string event = "id: evt-123\ndata: test\n\n";
  23516. sink.write(event.data(), event.size());
  23517. }
  23518. return false;
  23519. });
  23520. });
  23521. Client client("localhost", get_port());
  23522. sse::SSEClient sse(client, "/event-with-id");
  23523. std::atomic<bool> id_received{false};
  23524. sse.on_message([&](const sse::SSEMessage &msg) {
  23525. if (!msg.id.empty()) { id_received.store(true); }
  23526. });
  23527. sse.set_reconnect_interval(100);
  23528. sse.set_max_reconnect_attempts(1);
  23529. sse.start_async();
  23530. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23531. sse.stop();
  23532. EXPECT_TRUE(id_received.load());
  23533. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23534. }
  23535. // Test: last_event_id() read from another thread while start_async() runs
  23536. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23537. // Ids of every length up to 200, so the stored id keeps changing size
  23538. server_->Get("/many-ids", [](const Request &, Response &res) {
  23539. res.set_chunked_content_provider(
  23540. "text/event-stream", [](size_t offset, DataSink &sink) {
  23541. if (offset == 0) {
  23542. std::string events;
  23543. for (size_t i = 0; i < 2000; i++) {
  23544. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23545. events += "data: x\n\n";
  23546. }
  23547. events += "id: end\ndata: x\n\n";
  23548. sink.write(events.data(), events.size());
  23549. }
  23550. return false;
  23551. });
  23552. });
  23553. Client client("localhost", get_port());
  23554. sse::SSEClient sse(client, "/many-ids");
  23555. // Wait out the rest of the test rather than replay the stream
  23556. sse.set_reconnect_interval(10000);
  23557. sse.set_max_reconnect_attempts(1);
  23558. sse.start_async();
  23559. auto well_formed = true;
  23560. std::string id;
  23561. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23562. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23563. id = sse.last_event_id();
  23564. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23565. well_formed = false;
  23566. }
  23567. }
  23568. sse.stop();
  23569. EXPECT_TRUE(well_formed);
  23570. EXPECT_EQ(sse.last_event_id(), "end");
  23571. }
  23572. // Test: Manual stop
  23573. TEST_F(SSEIntegrationTest, ManualStop) {
  23574. // Endpoint that sends one event and stays open briefly. The server outlives
  23575. // this test body, so the provider uses the fixture's flag, not a local.
  23576. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23577. res.set_chunked_content_provider(
  23578. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23579. if (offset == 0) {
  23580. std::string event = "data: connected\n\n";
  23581. sink.write(event.data(), event.size());
  23582. }
  23583. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23584. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23585. }
  23586. return false;
  23587. });
  23588. });
  23589. Client client("localhost", get_port());
  23590. sse::SSEClient sse(client, "/stay-open");
  23591. std::atomic<bool> connected{false};
  23592. sse.on_open([&connected]() { connected.store(true); });
  23593. sse.set_reconnect_interval(100);
  23594. sse.set_max_reconnect_attempts(1);
  23595. sse.start_async();
  23596. // Wait for connection to establish
  23597. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23598. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23599. }
  23600. EXPECT_TRUE(connected.load());
  23601. EXPECT_TRUE(sse.is_connected());
  23602. // Signal handler to stop
  23603. stop_server_.store(true);
  23604. // Stop SSE client
  23605. sse.stop();
  23606. EXPECT_FALSE(sse.is_connected());
  23607. }
  23608. // Sends one event, then nothing until stop is set
  23609. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23610. return [&stop](const Request &, Response &res) {
  23611. res.set_chunked_content_provider(
  23612. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23613. if (offset == 0) {
  23614. std::string event = "data: hello\n\n";
  23615. sink.write(event.data(), event.size());
  23616. }
  23617. while (!stop.load()) {
  23618. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23619. }
  23620. return false;
  23621. });
  23622. };
  23623. }
  23624. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23625. static void check_stop_interrupts_blocked_read(Client &client) {
  23626. client.set_read_timeout(30, 0);
  23627. for (auto by_destructor : {false, true}) {
  23628. std::atomic<bool> received{false};
  23629. std::chrono::steady_clock::time_point start;
  23630. {
  23631. sse::SSEClient sse(client, "/idle-stream");
  23632. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23633. sse.start_async();
  23634. for (int i = 0; i < 500 && !received.load(); ++i) {
  23635. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23636. }
  23637. ASSERT_TRUE(received.load());
  23638. // Let the client block in the next read
  23639. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23640. start = std::chrono::steady_clock::now();
  23641. if (!by_destructor) { sse.stop(); }
  23642. }
  23643. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23644. std::chrono::seconds(2));
  23645. }
  23646. }
  23647. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23648. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23649. Client client("localhost", get_port());
  23650. check_stop_interrupts_blocked_read(client);
  23651. }
  23652. #ifdef CPPHTTPLIB_SSL_ENABLED
  23653. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23654. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23655. std::atomic<bool> done{false};
  23656. svr.Get("/idle-stream", idle_event_stream(done));
  23657. auto port = svr.bind_to_any_port(HOST);
  23658. std::thread t([&] { svr.listen_after_bind(); });
  23659. auto se = detail::scope_exit([&] {
  23660. done.store(true);
  23661. svr.stop();
  23662. t.join();
  23663. });
  23664. svr.wait_until_ready();
  23665. Client client("https://localhost:" + std::to_string(port));
  23666. client.enable_server_certificate_verification(false);
  23667. check_stop_interrupts_blocked_read(client);
  23668. }
  23669. #endif
  23670. // Test: SSEClient with custom headers
  23671. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23672. // Setup a server endpoint that checks for custom header
  23673. std::atomic<bool> header_received{false};
  23674. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23675. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23676. header_received.store(true);
  23677. }
  23678. res.set_chunked_content_provider("text/event-stream",
  23679. [](size_t, DataSink &) { return false; });
  23680. });
  23681. Client client("localhost", get_port());
  23682. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23683. sse::SSEClient sse(client, "/header-check", headers);
  23684. sse.set_max_reconnect_attempts(1);
  23685. sse.start_async();
  23686. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23687. sse.stop();
  23688. EXPECT_TRUE(header_received.load());
  23689. }
  23690. // Test: Reconnect interval configuration
  23691. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23692. Client client("localhost", get_port());
  23693. sse::SSEClient sse(client, "/events");
  23694. auto &result = sse.set_reconnect_interval(500);
  23695. // Builder pattern should return reference to self
  23696. EXPECT_EQ(&result, &sse);
  23697. }
  23698. // Test: Max reconnect attempts
  23699. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23700. // Connect to non-existent port to force reconnects
  23701. Client client("localhost", 59998);
  23702. sse::SSEClient sse(client, "/events");
  23703. std::atomic<int> error_count{0};
  23704. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23705. sse.set_reconnect_interval(50);
  23706. sse.set_max_reconnect_attempts(2);
  23707. auto start = std::chrono::steady_clock::now();
  23708. sse.start(); // Blocking call
  23709. auto end = std::chrono::steady_clock::now();
  23710. // Should have stopped after 2 failed attempts
  23711. EXPECT_GE(error_count.load(), 2);
  23712. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23713. auto duration =
  23714. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23715. #ifdef _WIN32
  23716. // Windows is much slower for socket connection failures
  23717. EXPECT_LT(duration.count(), 7000);
  23718. #else
  23719. EXPECT_LT(duration.count(), 1000);
  23720. #endif
  23721. }
  23722. // Test: Multi-line data in integration
  23723. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23724. // Endpoint with multi-line data
  23725. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23726. res.set_chunked_content_provider(
  23727. "text/event-stream", [](size_t offset, DataSink &sink) {
  23728. if (offset == 0) {
  23729. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23730. sink.write(event.data(), event.size());
  23731. }
  23732. return false;
  23733. });
  23734. });
  23735. Client client("localhost", get_port());
  23736. sse::SSEClient sse(client, "/multiline-data");
  23737. std::string received_data;
  23738. std::mutex data_mutex;
  23739. sse.on_message([&](const sse::SSEMessage &msg) {
  23740. std::lock_guard<std::mutex> lock(data_mutex);
  23741. received_data = msg.data;
  23742. });
  23743. sse.set_reconnect_interval(100);
  23744. sse.set_max_reconnect_attempts(1);
  23745. sse.start_async();
  23746. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23747. sse.stop();
  23748. std::lock_guard<std::mutex> lock(data_mutex);
  23749. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23750. }
  23751. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23752. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23753. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23754. DataSink &sink) {
  23755. if (offset == 0) {
  23756. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23757. sink.write(events.data(), events.size());
  23758. }
  23759. return false;
  23760. });
  23761. });
  23762. Client client("localhost", get_port());
  23763. sse::SSEClient sse(client, "/empty-data-lines");
  23764. std::mutex mutex;
  23765. std::condition_variable cv;
  23766. std::vector<std::string> received;
  23767. sse.on_message([&](const sse::SSEMessage &msg) {
  23768. std::lock_guard<std::mutex> lock(mutex);
  23769. received.push_back(msg.data);
  23770. cv.notify_all();
  23771. });
  23772. sse.set_max_reconnect_attempts(1);
  23773. sse.start_async();
  23774. {
  23775. std::unique_lock<std::mutex> lock(mutex);
  23776. cv.wait_for(lock, std::chrono::seconds(2),
  23777. [&] { return received.size() >= 3; });
  23778. }
  23779. sse.stop();
  23780. ASSERT_GE(received.size(), 3u);
  23781. EXPECT_EQ(received[0], "");
  23782. EXPECT_EQ(received[1], "\nhello");
  23783. EXPECT_EQ(received[2], "");
  23784. }
  23785. // Test: Auto-reconnect after server disconnection
  23786. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23787. std::atomic<int> connection_count{0};
  23788. std::atomic<int> message_count{0};
  23789. // Endpoint that sends one event and closes, forcing reconnect
  23790. server_->Get("/reconnect-test",
  23791. [&connection_count](const Request &, Response &res) {
  23792. connection_count.fetch_add(1);
  23793. res.set_chunked_content_provider(
  23794. "text/event-stream", [](size_t offset, DataSink &sink) {
  23795. if (offset == 0) {
  23796. std::string event = "data: hello\n\n";
  23797. sink.write(event.data(), event.size());
  23798. }
  23799. return false; // Close connection after sending
  23800. });
  23801. });
  23802. Client client("localhost", get_port());
  23803. sse::SSEClient sse(client, "/reconnect-test");
  23804. sse.on_message([&message_count](const sse::SSEMessage &) {
  23805. message_count.fetch_add(1);
  23806. });
  23807. sse.set_reconnect_interval(100);
  23808. sse.set_max_reconnect_attempts(3);
  23809. sse.start_async();
  23810. // Wait long enough for multiple reconnects
  23811. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23812. sse.stop();
  23813. // Should have connected multiple times (initial + reconnects)
  23814. EXPECT_GE(connection_count.load(), 2);
  23815. // Should have received messages from multiple connections
  23816. EXPECT_GE(message_count.load(), 2);
  23817. }
  23818. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23819. std::atomic<int> connection_count{0};
  23820. // Neither Content-Length nor chunked: the close ends the stream
  23821. server_->Get("/close-delimited",
  23822. [&connection_count](const Request &, Response &res) {
  23823. connection_count.fetch_add(1);
  23824. res.set_content_provider(
  23825. "text/event-stream", [](size_t offset, DataSink &sink) {
  23826. if (offset == 0) {
  23827. std::string event = "data: hello\n\n";
  23828. sink.write(event.data(), event.size());
  23829. } else {
  23830. sink.done();
  23831. }
  23832. return true;
  23833. });
  23834. });
  23835. Client client("localhost", get_port());
  23836. sse::SSEClient sse(client, "/close-delimited");
  23837. std::atomic<int> error_count{0};
  23838. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23839. sse.set_reconnect_interval(100);
  23840. sse.start_async();
  23841. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23842. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23843. }
  23844. sse.stop();
  23845. // Reconnects as after any end of the stream, but reports no error
  23846. EXPECT_GE(connection_count.load(), 2);
  23847. EXPECT_EQ(0, error_count.load());
  23848. }
  23849. // Test: A retry field of all ASCII digits sets the reconnection time
  23850. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23851. std::mutex mutex;
  23852. std::condition_variable cv;
  23853. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23854. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23855. {
  23856. std::lock_guard<std::mutex> lock(mutex);
  23857. connected_at.push_back(std::chrono::steady_clock::now());
  23858. cv.notify_all();
  23859. }
  23860. res.set_chunked_content_provider(
  23861. "text/event-stream", [](size_t offset, DataSink &sink) {
  23862. if (offset == 0) {
  23863. std::string event = "retry: 0\ndata: hello\n\n";
  23864. sink.write(event.data(), event.size());
  23865. }
  23866. return false;
  23867. });
  23868. });
  23869. Client client("localhost", get_port());
  23870. sse::SSEClient sse(client, "/zero-retry");
  23871. sse.set_reconnect_interval(10000);
  23872. sse.start_async();
  23873. {
  23874. std::unique_lock<std::mutex> lock(mutex);
  23875. cv.wait_for(lock, std::chrono::seconds(5),
  23876. [&] { return connected_at.size() >= 2; });
  23877. }
  23878. sse.stop();
  23879. // The server-supplied interval is applied, but never below 100ms, so
  23880. // "retry: 0" does not cause a busy reconnect loop
  23881. std::lock_guard<std::mutex> lock(mutex);
  23882. ASSERT_GE(connected_at.size(), 2u);
  23883. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23884. connected_at[1] - connected_at[0])
  23885. .count();
  23886. EXPECT_GE(interval_ms, 100);
  23887. }
  23888. // Test: Last-Event-ID sent on reconnect
  23889. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23890. std::atomic<int> connection_count{0};
  23891. std::vector<std::string> received_last_event_ids;
  23892. std::mutex id_mutex;
  23893. // Endpoint that checks Last-Event-ID header and sends event with ID
  23894. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23895. int conn = connection_count.fetch_add(1);
  23896. // Capture the Last-Event-ID header from each connection
  23897. {
  23898. std::lock_guard<std::mutex> lock(id_mutex);
  23899. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23900. }
  23901. res.set_chunked_content_provider(
  23902. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23903. if (offset == 0) {
  23904. std::string event =
  23905. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23906. sink.write(event.data(), event.size());
  23907. }
  23908. return false;
  23909. });
  23910. });
  23911. Client client("localhost", get_port());
  23912. sse::SSEClient sse(client, "/reconnect-with-id");
  23913. sse.set_reconnect_interval(100);
  23914. sse.set_max_reconnect_attempts(3);
  23915. sse.start_async();
  23916. // Wait for at least 2 connections
  23917. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23918. sse.stop();
  23919. // Verify behavior
  23920. std::lock_guard<std::mutex> lock(id_mutex);
  23921. EXPECT_GE(received_last_event_ids.size(), 2u);
  23922. // First connection should have no Last-Event-ID
  23923. if (!received_last_event_ids.empty()) {
  23924. EXPECT_EQ(received_last_event_ids[0], "");
  23925. }
  23926. // Second connection should have Last-Event-ID from first connection
  23927. if (received_last_event_ids.size() >= 2) {
  23928. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23929. }
  23930. }
  23931. // Test: set_headers updates headers used on reconnect
  23932. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23933. std::vector<std::string> received_tokens;
  23934. std::mutex token_mutex;
  23935. // Endpoint that captures Authorization header
  23936. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23937. {
  23938. std::lock_guard<std::mutex> lock(token_mutex);
  23939. received_tokens.push_back(req.get_header_value("Authorization"));
  23940. }
  23941. res.set_chunked_content_provider(
  23942. "text/event-stream", [](size_t offset, DataSink &sink) {
  23943. if (offset == 0) {
  23944. std::string event = "data: hello\n\n";
  23945. sink.write(event.data(), event.size());
  23946. }
  23947. return false; // Close connection to trigger reconnect
  23948. });
  23949. });
  23950. Client client("localhost", get_port());
  23951. Headers headers = {{"Authorization", "Bearer old-token"}};
  23952. sse::SSEClient sse(client, "/auth-check", headers);
  23953. // Update headers on each successful connection
  23954. sse.on_open(
  23955. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23956. sse.set_reconnect_interval(100);
  23957. sse.set_max_reconnect_attempts(3);
  23958. sse.start_async();
  23959. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23960. sse.stop();
  23961. std::lock_guard<std::mutex> lock(token_mutex);
  23962. ASSERT_GE(received_tokens.size(), 2u);
  23963. // First connection uses original header
  23964. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23965. // Second connection uses updated header from set_headers
  23966. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23967. }
  23968. // Test: 401 allows reconnection (so on_error can refresh headers)
  23969. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23970. std::atomic<int> connection_count{0};
  23971. // Endpoint: returns 401 on first attempt, 200 on second
  23972. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23973. int conn = connection_count.fetch_add(1);
  23974. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23975. res.status = StatusCode::Unauthorized_401;
  23976. res.set_content("Unauthorized", "text/plain");
  23977. return;
  23978. }
  23979. res.set_chunked_content_provider(
  23980. "text/event-stream", [](size_t offset, DataSink &sink) {
  23981. if (offset == 0) {
  23982. std::string event = "data: authenticated\n\n";
  23983. sink.write(event.data(), event.size());
  23984. }
  23985. return false;
  23986. });
  23987. });
  23988. Client client("localhost", get_port());
  23989. Headers headers = {{"Authorization", "Bearer expired"}};
  23990. sse::SSEClient sse(client, "/auth-retry", headers);
  23991. std::atomic<bool> message_received{false};
  23992. // Refresh token on error
  23993. sse.on_error(
  23994. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23995. sse.on_message([&](const sse::SSEMessage &msg) {
  23996. if (msg.data == "authenticated") { message_received.store(true); }
  23997. });
  23998. sse.set_reconnect_interval(100);
  23999. sse.set_max_reconnect_attempts(3);
  24000. sse.start_async();
  24001. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  24002. sse.stop();
  24003. // Should have reconnected after 401 and succeeded with new token
  24004. EXPECT_GE(connection_count.load(), 2);
  24005. EXPECT_TRUE(message_received.load());
  24006. }
  24007. TEST(Issue2318Test, EmptyHostString) {
  24008. {
  24009. httplib::Client cli_empty("", PORT);
  24010. auto res = cli_empty.Get("/");
  24011. ASSERT_FALSE(res);
  24012. EXPECT_EQ(httplib::Error::Connection, res.error());
  24013. }
  24014. {
  24015. httplib::Client cli(" ", PORT);
  24016. auto res = cli.Get("/");
  24017. ASSERT_FALSE(res);
  24018. EXPECT_EQ(httplib::Error::Connection, res.error());
  24019. }
  24020. }
  24021. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  24022. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  24023. Server svr;
  24024. // Set a small payload limit (1KB)
  24025. svr.set_payload_max_length(1024);
  24026. svr.Post("/test", [&](const Request &req, Response &res) {
  24027. res.set_content("Body size: " + std::to_string(req.body.size()),
  24028. "text/plain");
  24029. });
  24030. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  24031. auto se = detail::scope_exit([&] {
  24032. svr.stop();
  24033. listen_thread.join();
  24034. });
  24035. svr.wait_until_ready();
  24036. // Create data that compresses well but exceeds limit when decompressed
  24037. // 8KB of repeated null bytes compresses to a very small size
  24038. std::string original_data(8 * 1024, '\0');
  24039. // Compress the data using gzip
  24040. std::string compressed_data;
  24041. detail::gzip_compressor compressor;
  24042. compressor.compress(original_data.data(), original_data.size(), true,
  24043. [&](const char *data, size_t size) {
  24044. compressed_data.append(data, size);
  24045. return true;
  24046. });
  24047. // Verify compression worked (compressed should be much smaller)
  24048. ASSERT_LT(compressed_data.size(), original_data.size());
  24049. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  24050. // Send compressed data with Content-Encoding: gzip
  24051. Client cli(HOST, PORT);
  24052. Headers headers = {{"Content-Encoding", "gzip"}};
  24053. auto res =
  24054. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24055. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24057. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24058. }
  24059. #endif
  24060. // ============================================================================
  24061. // OpenSSL-Specific Tests
  24062. // ============================================================================
  24063. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24064. X509 *readCertificate(const std::string &strFileName) {
  24065. std::ifstream inStream(strFileName);
  24066. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24067. std::istreambuf_iterator<char>());
  24068. if (strCertPEM.empty()) return (nullptr);
  24069. BIO *pbCert = BIO_new(BIO_s_mem());
  24070. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24071. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24072. BIO_free(pbCert);
  24073. return (pCert);
  24074. }
  24075. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24076. std::ifstream inStream(strFileName);
  24077. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24078. std::istreambuf_iterator<char>());
  24079. if (strPrivateKeyPEM.empty()) return (nullptr);
  24080. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24081. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24082. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24083. BIO_free(pbPrivKey);
  24084. return (pPrivateKey);
  24085. }
  24086. TEST(BindServerTest, UpdateCerts) {
  24087. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24088. int port = svr.bind_to_any_port("0.0.0.0");
  24089. ASSERT_TRUE(svr.is_valid());
  24090. ASSERT_TRUE(port > 0);
  24091. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24092. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24093. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24094. ASSERT_TRUE(cert != nullptr);
  24095. ASSERT_TRUE(ca_cert != nullptr);
  24096. ASSERT_TRUE(key != nullptr);
  24097. X509_STORE *cert_store = X509_STORE_new();
  24098. X509_STORE_add_cert(cert_store, ca_cert);
  24099. // svr.update_certs(cert, key, cert_store); // deprecated
  24100. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24101. CLIENT_CA_CERT_FILE);
  24102. ASSERT_TRUE(svr.is_valid());
  24103. svr.stop();
  24104. X509_STORE_free(cert_store);
  24105. X509_free(cert);
  24106. X509_free(ca_cert);
  24107. EVP_PKEY_free(key);
  24108. }
  24109. // Test that update_certs() updates client CA list correctly
  24110. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24111. // Start with file-based constructor
  24112. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24113. ASSERT_TRUE(svr.is_valid());
  24114. // Initially no client CA list should be set
  24115. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24116. ASSERT_TRUE(ssl_ctx != nullptr);
  24117. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24118. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24119. // Now update with client CA (PEM string)
  24120. std::string cert_pem, key_pem, ca_pem;
  24121. read_file(SERVER_CERT_FILE, cert_pem);
  24122. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24123. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24124. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24125. ASSERT_TRUE(svr.is_valid());
  24126. // Now client CA list should be set
  24127. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24128. ASSERT_TRUE(ca_list_after != nullptr);
  24129. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24130. }
  24131. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24132. // Test that the file-path SSLServer constructor properly sets the client CA
  24133. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24134. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24135. ASSERT_TRUE(svr.is_valid());
  24136. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24137. ASSERT_TRUE(ssl_ctx != nullptr);
  24138. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24139. ASSERT_TRUE(ca_list != nullptr);
  24140. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24141. }
  24142. #endif
  24143. // ============================================================================
  24144. // MbedTLS-Specific Tests
  24145. // ============================================================================
  24146. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24147. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24148. using namespace httplib::tls;
  24149. // Track if callback was invoked
  24150. bool callback_invoked = false;
  24151. // The callback receives void* ctx which is actually MbedTlsContext*
  24152. // We can access the mbedtls_ssl_config via the context
  24153. auto setup_callback = [&callback_invoked](void *ctx) {
  24154. callback_invoked = true;
  24155. // Cast to MbedTlsContext* to access the ssl config
  24156. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24157. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24158. // Use static variables to hold certificate data (simplified for test)
  24159. static mbedtls_x509_crt own_cert;
  24160. static mbedtls_pk_context own_key;
  24161. static mbedtls_x509_crt ca_chain;
  24162. static bool initialized = false;
  24163. if (!initialized) {
  24164. mbedtls_x509_crt_init(&own_cert);
  24165. mbedtls_pk_init(&own_key);
  24166. mbedtls_x509_crt_init(&ca_chain);
  24167. // Load server certificate
  24168. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24169. return false;
  24170. }
  24171. // Load server private key.
  24172. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24173. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24174. #if MBEDTLS_VERSION_MAJOR == 3
  24175. ,
  24176. mbedtls_ctr_drbg_random, nullptr
  24177. #endif
  24178. ) != 0) {
  24179. return false;
  24180. }
  24181. // Load CA chain for client verification
  24182. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24183. return false;
  24184. }
  24185. initialized = true;
  24186. }
  24187. // Configure the SSL config
  24188. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24189. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24190. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24191. // Set minimum TLS version using mbedTLS native API
  24192. #if MBEDTLS_VERSION_MAJOR >= 3
  24193. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24194. #else
  24195. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24196. MBEDTLS_SSL_MINOR_VERSION_3);
  24197. #endif
  24198. return true;
  24199. };
  24200. SSLServer svr(setup_callback);
  24201. ASSERT_TRUE(svr.is_valid());
  24202. ASSERT_TRUE(callback_invoked);
  24203. svr.Get("/test", [&](const Request &req, Response &res) {
  24204. res.set_content("test", "text/plain");
  24205. auto cert = req.peer_cert();
  24206. ASSERT_TRUE(static_cast<bool>(cert));
  24207. auto common_name = cert.subject_cn();
  24208. EXPECT_EQ("Common Name", common_name);
  24209. });
  24210. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24211. auto se = detail::scope_exit([&] {
  24212. svr.stop();
  24213. t.join();
  24214. ASSERT_FALSE(svr.is_running());
  24215. });
  24216. svr.wait_until_ready();
  24217. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24218. cli.enable_server_certificate_verification(false);
  24219. cli.set_connection_timeout(30);
  24220. auto res = cli.Get("/test");
  24221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24222. ASSERT_EQ(StatusCode::OK_200, res->status);
  24223. }
  24224. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24225. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24226. // keep-alive SSL session, which reads through that config in
  24227. // mbedtls_ssl_close_notify.
  24228. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24229. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24230. ASSERT_TRUE(svr.is_valid());
  24231. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24232. res.set_content("test", "text/plain");
  24233. });
  24234. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24235. auto se = detail::scope_exit([&] {
  24236. svr.stop();
  24237. t.join();
  24238. ASSERT_FALSE(svr.is_running());
  24239. });
  24240. svr.wait_until_ready();
  24241. {
  24242. SSLClient cli(HOST, PORT);
  24243. cli.enable_server_certificate_verification(false);
  24244. cli.set_keep_alive(true);
  24245. auto res = cli.Get("/test");
  24246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24247. ASSERT_EQ(StatusCode::OK_200, res->status);
  24248. // cli is destructed here with the keep-alive SSL session still open.
  24249. }
  24250. }
  24251. #endif
  24252. // WebSocket Tests
  24253. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24254. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24255. // defining the meaning of these bits has been negotiated.
  24256. auto make_frame = [](uint8_t first_byte) {
  24257. std::string frame;
  24258. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24259. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24260. frame += "Hello";
  24261. return frame;
  24262. };
  24263. // RSV1 set (0x40)
  24264. {
  24265. detail::BufferStream strm;
  24266. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24267. ws::Opcode opcode;
  24268. std::string payload;
  24269. bool fin;
  24270. EXPECT_EQ(
  24271. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24272. ws::impl::FrameRead::ProtocolError);
  24273. }
  24274. // RSV2 set (0x20)
  24275. {
  24276. detail::BufferStream strm;
  24277. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24278. ws::Opcode opcode;
  24279. std::string payload;
  24280. bool fin;
  24281. EXPECT_EQ(
  24282. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24283. ws::impl::FrameRead::ProtocolError);
  24284. }
  24285. // RSV3 set (0x10)
  24286. {
  24287. detail::BufferStream strm;
  24288. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24289. ws::Opcode opcode;
  24290. std::string payload;
  24291. bool fin;
  24292. EXPECT_EQ(
  24293. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24294. ws::impl::FrameRead::ProtocolError);
  24295. }
  24296. // No RSV bits set - should succeed
  24297. {
  24298. detail::BufferStream strm;
  24299. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24300. ws::Opcode opcode;
  24301. std::string payload;
  24302. bool fin;
  24303. EXPECT_EQ(
  24304. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24305. ws::impl::FrameRead::Ok);
  24306. EXPECT_EQ(ws::Opcode::Text, opcode);
  24307. EXPECT_EQ("Hello", payload);
  24308. EXPECT_TRUE(fin);
  24309. }
  24310. }
  24311. TEST(WebSocketTest, ControlFrameValidation) {
  24312. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24313. // payload length <= 125.
  24314. // Ping with FIN=0 - must be rejected
  24315. {
  24316. detail::BufferStream strm;
  24317. std::string frame;
  24318. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24319. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24320. strm.write(frame.data(), frame.size());
  24321. ws::Opcode opcode;
  24322. std::string payload;
  24323. bool fin;
  24324. EXPECT_EQ(
  24325. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24326. ws::impl::FrameRead::ProtocolError);
  24327. }
  24328. // Close with FIN=0 - must be rejected
  24329. {
  24330. detail::BufferStream strm;
  24331. std::string frame;
  24332. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24333. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24334. strm.write(frame.data(), frame.size());
  24335. ws::Opcode opcode;
  24336. std::string payload;
  24337. bool fin;
  24338. EXPECT_EQ(
  24339. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24340. ws::impl::FrameRead::ProtocolError);
  24341. }
  24342. // Ping with payload_len=126 (extended length) - must be rejected
  24343. {
  24344. detail::BufferStream strm;
  24345. std::string frame;
  24346. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24347. frame += static_cast<char>(126); // payload_len=126 (>125)
  24348. frame += static_cast<char>(0x00); // extended length high byte
  24349. frame += static_cast<char>(126); // extended length low byte
  24350. frame += std::string(126, 'x');
  24351. strm.write(frame.data(), frame.size());
  24352. ws::Opcode opcode;
  24353. std::string payload;
  24354. bool fin;
  24355. EXPECT_EQ(
  24356. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24357. ws::impl::FrameRead::ProtocolError);
  24358. }
  24359. // Ping with FIN=1 and payload_len=125 - should succeed
  24360. {
  24361. detail::BufferStream strm;
  24362. std::string frame;
  24363. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24364. frame += static_cast<char>(125); // payload_len=125
  24365. frame += std::string(125, 'x');
  24366. strm.write(frame.data(), frame.size());
  24367. ws::Opcode opcode;
  24368. std::string payload;
  24369. bool fin;
  24370. EXPECT_EQ(
  24371. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24372. ws::impl::FrameRead::Ok);
  24373. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24374. EXPECT_EQ(125u, payload.size());
  24375. EXPECT_TRUE(fin);
  24376. }
  24377. }
  24378. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24379. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24380. // length MUST be 0.
  24381. // MSB set - must be rejected
  24382. {
  24383. detail::BufferStream strm;
  24384. std::string frame;
  24385. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24386. frame += static_cast<char>(127); // 64-bit extended length
  24387. frame += static_cast<char>(0x80); // MSB set (invalid)
  24388. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24389. strm.write(frame.data(), frame.size());
  24390. ws::Opcode opcode;
  24391. std::string payload;
  24392. bool fin;
  24393. EXPECT_EQ(
  24394. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24395. ws::impl::FrameRead::ProtocolError);
  24396. }
  24397. // MSB clear - should pass length parsing (will be rejected by max_len,
  24398. // but that's a different check; use a small length to verify)
  24399. {
  24400. detail::BufferStream strm;
  24401. std::string frame;
  24402. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24403. frame += static_cast<char>(127); // 64-bit extended length
  24404. frame += std::string(7, '\0'); // high bytes = 0
  24405. frame += static_cast<char>(0x03); // length = 3
  24406. frame += "abc";
  24407. strm.write(frame.data(), frame.size());
  24408. ws::Opcode opcode;
  24409. std::string payload;
  24410. bool fin;
  24411. EXPECT_EQ(
  24412. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24413. ws::impl::FrameRead::Ok);
  24414. EXPECT_EQ(ws::Opcode::Text, opcode);
  24415. EXPECT_EQ("abc", payload);
  24416. }
  24417. }
  24418. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24419. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24420. // Valid UTF-8
  24421. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24422. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24423. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24424. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24425. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24426. // Invalid UTF-8
  24427. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24428. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24429. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24430. EXPECT_FALSE(
  24431. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24432. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24433. }
  24434. TEST(WebSocketTest, ConnectAndDisconnect) {
  24435. Server svr;
  24436. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24437. std::string msg;
  24438. while (ws.read(msg)) {}
  24439. });
  24440. auto port = svr.bind_to_any_port(HOST);
  24441. std::thread t([&]() { svr.listen_after_bind(); });
  24442. svr.wait_until_ready();
  24443. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24444. auto res = client.connect();
  24445. ASSERT_TRUE(res);
  24446. EXPECT_EQ(Error::Success, res.error());
  24447. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24448. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24449. EXPECT_TRUE(client.is_open());
  24450. client.close();
  24451. EXPECT_FALSE(client.is_open());
  24452. svr.stop();
  24453. t.join();
  24454. }
  24455. TEST(WebSocketTest, ValidURL) {
  24456. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24457. EXPECT_TRUE(ws1.is_valid());
  24458. ws::WebSocketClient ws2("ws://example.com/path");
  24459. EXPECT_TRUE(ws2.is_valid());
  24460. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24461. EXPECT_TRUE(ws3.is_valid());
  24462. #ifdef CPPHTTPLIB_SSL_ENABLED
  24463. ws::WebSocketClient wss1("wss://example.com/path");
  24464. EXPECT_TRUE(wss1.is_valid());
  24465. ws::WebSocketClient wss2("wss://example.com:443/path");
  24466. EXPECT_TRUE(wss2.is_valid());
  24467. #endif
  24468. }
  24469. TEST(WebSocketTest, InvalidURL) {
  24470. // No scheme
  24471. ws::WebSocketClient ws1("localhost:8080/path");
  24472. EXPECT_FALSE(ws1.is_valid());
  24473. // No path
  24474. ws::WebSocketClient ws2("ws://localhost:8080");
  24475. EXPECT_FALSE(ws2.is_valid());
  24476. // Empty string
  24477. ws::WebSocketClient ws3("");
  24478. EXPECT_FALSE(ws3.is_valid());
  24479. // Missing host
  24480. ws::WebSocketClient ws4("ws://:8080/path");
  24481. EXPECT_FALSE(ws4.is_valid());
  24482. // Port number overflow — should not crash
  24483. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24484. EXPECT_FALSE(ws5.is_valid());
  24485. // Port out of range
  24486. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24487. EXPECT_FALSE(ws6.is_valid());
  24488. }
  24489. TEST(WebSocketTest, UnsupportedScheme) {
  24490. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24491. ws::WebSocketClient ws1("http://localhost:8080/path");
  24492. EXPECT_FALSE(ws1.is_valid());
  24493. ws::WebSocketClient ws2("https://localhost:8080/path");
  24494. EXPECT_FALSE(ws2.is_valid());
  24495. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24496. EXPECT_FALSE(ws3.is_valid());
  24497. #else
  24498. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24499. std::invalid_argument);
  24500. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24501. std::invalid_argument);
  24502. #endif
  24503. }
  24504. TEST(WebSocketTest, ConnectWhenInvalid) {
  24505. ws::WebSocketClient ws("not a valid url");
  24506. EXPECT_FALSE(ws.is_valid());
  24507. auto res = ws.connect();
  24508. EXPECT_FALSE(res);
  24509. EXPECT_EQ(Error::Connection, res.error());
  24510. EXPECT_EQ(-1, res.status());
  24511. }
  24512. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24513. // Grab a port that is free, then close it again so nothing listens there
  24514. Server svr;
  24515. auto port = svr.bind_to_any_port(HOST);
  24516. svr.stop();
  24517. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24518. auto res = client.connect();
  24519. ASSERT_FALSE(res);
  24520. EXPECT_EQ(Error::Connection, res.error());
  24521. EXPECT_EQ(-1, res.status());
  24522. }
  24523. TEST(WebSocketTest, DefaultPort) {
  24524. ws::WebSocketClient ws1("ws://example.com/path");
  24525. EXPECT_TRUE(ws1.is_valid());
  24526. // ws:// defaults to port 80 (verified by successful parse)
  24527. #ifdef CPPHTTPLIB_SSL_ENABLED
  24528. ws::WebSocketClient ws2("wss://example.com/path");
  24529. EXPECT_TRUE(ws2.is_valid());
  24530. // wss:// defaults to port 443 (verified by successful parse)
  24531. #endif
  24532. }
  24533. TEST(WebSocketTest, IPv6LiteralAddress) {
  24534. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24535. EXPECT_TRUE(ws1.is_valid());
  24536. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24537. EXPECT_TRUE(ws2.is_valid());
  24538. }
  24539. TEST(WebSocketTest, ComplexPath) {
  24540. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24541. EXPECT_TRUE(ws1.is_valid());
  24542. ws::WebSocketClient ws2("ws://localhost:8080/");
  24543. EXPECT_TRUE(ws2.is_valid());
  24544. }
  24545. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24546. Server svr;
  24547. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24548. std::string msg;
  24549. while (ws.read(msg)) {}
  24550. });
  24551. auto port = svr.bind_to_any_port(HOST);
  24552. std::thread t([&]() { svr.listen_after_bind(); });
  24553. svr.wait_until_ready();
  24554. auto another_host = "example.com";
  24555. auto wrong_ip = "192.0.2.1";
  24556. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24557. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24558. ASSERT_TRUE(client.connect());
  24559. EXPECT_TRUE(client.is_open());
  24560. client.close();
  24561. svr.stop();
  24562. t.join();
  24563. }
  24564. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24565. Server svr;
  24566. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24567. std::string msg;
  24568. while (ws.read(msg)) {}
  24569. });
  24570. auto port = svr.bind_to_any_port(HOST);
  24571. std::thread t([&]() { svr.listen_after_bind(); });
  24572. svr.wait_until_ready();
  24573. auto wrong_ip = "192.0.2.1";
  24574. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24575. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24576. client.set_connection_timeout(1);
  24577. client.set_read_timeout(1);
  24578. client.set_write_timeout(1);
  24579. EXPECT_FALSE(client.connect());
  24580. EXPECT_FALSE(client.is_open());
  24581. svr.stop();
  24582. t.join();
  24583. }
  24584. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24585. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24586. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24587. // (RFC 6761) is only a map key and the Host header value.
  24588. auto host = "target.invalid";
  24589. Server svr;
  24590. std::string received_host;
  24591. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24592. received_host = req.get_header_value("Host");
  24593. std::string msg;
  24594. while (ws.read(msg)) {}
  24595. });
  24596. auto port = svr.bind_to_any_port(HOST);
  24597. std::thread t([&]() { svr.listen_after_bind(); });
  24598. // ASSERT_* below returns from the test body, which would leave t joinable
  24599. // and make ~thread call std::terminate.
  24600. auto se = detail::scope_exit([&] {
  24601. svr.stop();
  24602. if (t.joinable()) { t.join(); }
  24603. });
  24604. svr.wait_until_ready();
  24605. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24606. std::to_string(port) + "/ws");
  24607. client.set_direct_hostname_addr_map({{host, HOST}});
  24608. ASSERT_TRUE(client.connect());
  24609. EXPECT_TRUE(client.is_open());
  24610. client.close();
  24611. svr.stop();
  24612. t.join();
  24613. // The mapping only redirects the connection; the identity stays host_.
  24614. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24615. }
  24616. class WebSocketIntegrationTest : public ::testing::Test {
  24617. protected:
  24618. void SetUp() override {
  24619. server_ = httplib::detail::make_unique<Server>();
  24620. setup_server();
  24621. start_server();
  24622. }
  24623. void TearDown() override {
  24624. server_->stop();
  24625. if (server_thread_.joinable()) { server_thread_.join(); }
  24626. }
  24627. void setup_server() {
  24628. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24629. std::string msg;
  24630. ws::ReadResult ret;
  24631. while ((ret = ws.read(msg))) {
  24632. if (ret == ws::Binary) {
  24633. ws.send(msg.data(), msg.size());
  24634. } else {
  24635. ws.send(msg);
  24636. }
  24637. }
  24638. });
  24639. server_->WebSocket("/ws-echo-string",
  24640. [](const Request &, ws::WebSocket &ws) {
  24641. std::string msg;
  24642. while (ws.read(msg)) {
  24643. ws.send("echo: " + msg);
  24644. }
  24645. });
  24646. server_->WebSocket(
  24647. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24648. // Echo back request metadata
  24649. ws.send("path:" + req.path);
  24650. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24651. std::string msg;
  24652. while (ws.read(msg)) {}
  24653. });
  24654. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24655. std::string msg;
  24656. ws.read(msg); // wait for a message
  24657. ws.close();
  24658. });
  24659. server_->WebSocket("/ws-close-status",
  24660. [](const Request &, ws::WebSocket &ws) {
  24661. std::string msg;
  24662. ws.read(msg); // wait for a message
  24663. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24664. });
  24665. server_->WebSocket(
  24666. "/ws-subprotocol",
  24667. [](const Request &, ws::WebSocket &ws) {
  24668. std::string msg;
  24669. while (ws.read(msg)) {
  24670. ws.send(msg);
  24671. }
  24672. },
  24673. [](const std::vector<std::string> &protocols) -> std::string {
  24674. for (const auto &p : protocols) {
  24675. if (p == "graphql-ws") { return p; }
  24676. }
  24677. return "";
  24678. });
  24679. server_->WebSocket(
  24680. "/ws-subprotocol-unoffered",
  24681. [](const Request &, ws::WebSocket &ws) {
  24682. std::string msg;
  24683. while (ws.read(msg)) {
  24684. ws.send(msg);
  24685. }
  24686. },
  24687. [](const std::vector<std::string> &) -> std::string {
  24688. return "admin";
  24689. });
  24690. }
  24691. void start_server() {
  24692. port_ = server_->bind_to_any_port(HOST);
  24693. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24694. server_->wait_until_ready();
  24695. }
  24696. std::unique_ptr<Server> server_;
  24697. std::thread server_thread_;
  24698. int port_ = 0;
  24699. };
  24700. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24701. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24702. "/ws-echo");
  24703. ASSERT_TRUE(client.connect());
  24704. ASSERT_TRUE(client.is_open());
  24705. ASSERT_TRUE(client.send("Hello WebSocket"));
  24706. std::string msg;
  24707. EXPECT_EQ(ws::Text, client.read(msg));
  24708. EXPECT_EQ("Hello WebSocket", msg);
  24709. client.close();
  24710. }
  24711. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24712. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24713. "/ws-echo");
  24714. ASSERT_TRUE(client.connect());
  24715. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24716. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24717. std::string msg;
  24718. EXPECT_EQ(ws::Binary, client.read(msg));
  24719. EXPECT_EQ(binary_data, msg);
  24720. client.close();
  24721. }
  24722. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24723. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24724. "/ws-echo");
  24725. ASSERT_TRUE(client.connect());
  24726. for (int i = 0; i < 10; i++) {
  24727. auto text = "message " + std::to_string(i);
  24728. ASSERT_TRUE(client.send(text));
  24729. std::string msg;
  24730. ASSERT_TRUE(client.read(msg));
  24731. EXPECT_EQ(text, msg);
  24732. }
  24733. client.close();
  24734. }
  24735. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24736. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24737. "/ws-close");
  24738. ASSERT_TRUE(client.connect());
  24739. // Send a message to trigger the server to close
  24740. ASSERT_TRUE(client.send("trigger close"));
  24741. // The server will close, so read should return false
  24742. std::string msg;
  24743. EXPECT_FALSE(client.read(msg));
  24744. EXPECT_FALSE(client.is_open());
  24745. EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
  24746. EXPECT_EQ("", client.close_reason());
  24747. }
  24748. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24749. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24750. "/ws-echo");
  24751. ASSERT_TRUE(client.connect());
  24752. // 128KB message
  24753. std::string large_data(128 * 1024, 'X');
  24754. ASSERT_TRUE(client.send(large_data));
  24755. std::string msg;
  24756. ASSERT_TRUE(client.read(msg));
  24757. EXPECT_EQ(large_data, msg);
  24758. client.close();
  24759. }
  24760. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24761. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24762. "/ws-echo");
  24763. ASSERT_TRUE(client.connect());
  24764. const int num_threads = 4;
  24765. std::vector<std::thread> threads;
  24766. std::atomic<int> send_count{0};
  24767. for (int t = 0; t < num_threads; t++) {
  24768. threads.emplace_back([&client, &send_count, t]() {
  24769. for (int i = 0; i < 5; i++) {
  24770. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24771. if (client.send(text)) { send_count++; }
  24772. }
  24773. });
  24774. }
  24775. for (auto &th : threads) {
  24776. th.join();
  24777. }
  24778. int received = 0;
  24779. std::string msg;
  24780. while (received < send_count.load()) {
  24781. if (!client.read(msg)) { break; }
  24782. received++;
  24783. }
  24784. EXPECT_EQ(send_count.load(), received);
  24785. client.close();
  24786. }
  24787. TEST_F(WebSocketIntegrationTest, ReadString) {
  24788. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24789. "/ws-echo-string");
  24790. ASSERT_TRUE(client.connect());
  24791. ASSERT_TRUE(client.send("hello"));
  24792. std::string msg;
  24793. ASSERT_TRUE(client.read(msg));
  24794. EXPECT_EQ("echo: hello", msg);
  24795. ASSERT_TRUE(client.send("world"));
  24796. ASSERT_TRUE(client.read(msg));
  24797. EXPECT_EQ("echo: world", msg);
  24798. client.close();
  24799. }
  24800. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24801. Headers headers = {{"X-Test-Header", "test-value"}};
  24802. ws::WebSocketClient client(
  24803. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24804. ASSERT_TRUE(client.connect());
  24805. std::string msg;
  24806. ASSERT_TRUE(client.read(msg));
  24807. EXPECT_EQ("path:/ws-request-info", msg);
  24808. ASSERT_TRUE(client.read(msg));
  24809. EXPECT_EQ("header:test-value", msg);
  24810. client.close();
  24811. }
  24812. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24813. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24814. "/ws-echo");
  24815. client.set_read_timeout(1, 0); // 1 second
  24816. ASSERT_TRUE(client.connect());
  24817. // Don't send anything — server echo handler waits for a message, so read()
  24818. // should time out. The connection survives it: nothing was consumed.
  24819. std::string msg;
  24820. EXPECT_EQ(client.read(msg), ws::Timeout);
  24821. EXPECT_TRUE(client.is_open());
  24822. // And it is still usable afterwards.
  24823. EXPECT_TRUE(client.send("after timeout"));
  24824. EXPECT_EQ(client.read(msg), ws::Text);
  24825. EXPECT_EQ(msg, "after timeout");
  24826. }
  24827. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24828. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24829. "/ws-echo");
  24830. client.set_read_timeout(1, 0);
  24831. ASSERT_TRUE(client.connect());
  24832. ASSERT_TRUE(client.send("first"));
  24833. std::string msg;
  24834. ASSERT_EQ(client.read(msg), ws::Text);
  24835. ASSERT_EQ(msg, "first");
  24836. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24837. // not be used with a read timeout: it would reprocess the previous message.
  24838. EXPECT_EQ(client.read(msg), ws::Timeout);
  24839. EXPECT_EQ(msg, "first");
  24840. }
  24841. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24842. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24843. "/ws-echo");
  24844. ASSERT_TRUE(client.connect());
  24845. // Setting it once the connection is open reaches the live stream, not just
  24846. // the seed for the next connect().
  24847. client.set_read_timeout(1, 0);
  24848. std::string msg;
  24849. EXPECT_EQ(client.read(msg), ws::Timeout);
  24850. EXPECT_TRUE(client.is_open());
  24851. }
  24852. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24853. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24854. "/nonexistent");
  24855. auto res = client.connect();
  24856. EXPECT_FALSE(res);
  24857. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24858. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24859. EXPECT_FALSE(client.is_open());
  24860. }
  24861. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24862. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24863. "/ws-echo");
  24864. ASSERT_TRUE(client.connect());
  24865. ASSERT_TRUE(client.send(""));
  24866. std::string msg;
  24867. EXPECT_EQ(ws::Text, client.read(msg));
  24868. EXPECT_EQ("", msg);
  24869. client.close();
  24870. }
  24871. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24872. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24873. "/ws-echo");
  24874. // First connection
  24875. ASSERT_TRUE(client.connect());
  24876. ASSERT_TRUE(client.send("first"));
  24877. std::string msg;
  24878. ASSERT_TRUE(client.read(msg));
  24879. EXPECT_EQ("first", msg);
  24880. client.close();
  24881. EXPECT_FALSE(client.is_open());
  24882. // Reconnect using the same client object
  24883. ASSERT_TRUE(client.connect());
  24884. ASSERT_TRUE(client.is_open());
  24885. ASSERT_TRUE(client.send("second"));
  24886. ASSERT_TRUE(client.read(msg));
  24887. EXPECT_EQ("second", msg);
  24888. client.close();
  24889. }
  24890. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24891. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24892. "/ws-close-status");
  24893. ASSERT_TRUE(client.connect());
  24894. // Trigger the server to close with GoingAway status
  24895. ASSERT_TRUE(client.send("trigger"));
  24896. // read() should return false after receiving the close frame
  24897. std::string msg;
  24898. EXPECT_FALSE(client.read(msg));
  24899. EXPECT_FALSE(client.is_open());
  24900. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  24901. EXPECT_EQ("shutting down", client.close_reason());
  24902. // A copy, so it outlives a reconnect that replaces the connection
  24903. static_assert(
  24904. std::is_same<decltype(client.close_reason()), std::string>::value, "");
  24905. }
  24906. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24907. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24908. "/ws-echo");
  24909. EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
  24910. ASSERT_TRUE(client.connect());
  24911. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24912. EXPECT_FALSE(client.is_open());
  24913. // The server echoes the Close it receives
  24914. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  24915. EXPECT_EQ("client leaving", client.close_reason());
  24916. }
  24917. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24918. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24919. ws::WebSocketClient client(
  24920. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24921. ASSERT_TRUE(client.connect());
  24922. // Server should have selected graphql-ws
  24923. EXPECT_EQ("graphql-ws", client.subprotocol());
  24924. client.close();
  24925. }
  24926. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24927. Headers headers;
  24928. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24929. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24930. ws::WebSocketClient client(
  24931. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24932. ASSERT_TRUE(client.connect());
  24933. // The offer on the second field line counts too, so graphql-ws is selected
  24934. EXPECT_EQ("graphql-ws", client.subprotocol());
  24935. client.close();
  24936. }
  24937. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24938. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24939. ws::WebSocketClient client(
  24940. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24941. ASSERT_TRUE(client.connect());
  24942. // Server should not have selected any subprotocol
  24943. EXPECT_TRUE(client.subprotocol().empty());
  24944. client.close();
  24945. }
  24946. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24947. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24948. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24949. "/ws-subprotocol-unoffered",
  24950. headers);
  24951. ASSERT_TRUE(client.connect());
  24952. EXPECT_TRUE(client.subprotocol().empty());
  24953. client.close();
  24954. }
  24955. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24956. // Connect without requesting any subprotocol
  24957. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24958. "/ws-subprotocol");
  24959. ASSERT_TRUE(client.connect());
  24960. EXPECT_TRUE(client.subprotocol().empty());
  24961. client.close();
  24962. }
  24963. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24964. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24965. "/ws-echo");
  24966. client.set_tcp_nodelay(true);
  24967. client.set_connection_timeout(3, 0);
  24968. bool socket_options_called = false;
  24969. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24970. ASSERT_TRUE(client.connect());
  24971. ASSERT_TRUE(client.is_open());
  24972. EXPECT_TRUE(socket_options_called);
  24973. ASSERT_TRUE(client.send("hello"));
  24974. std::string msg;
  24975. auto result = client.read(msg);
  24976. EXPECT_EQ(result, ws::ReadResult::Text);
  24977. EXPECT_EQ(msg, "hello");
  24978. client.close();
  24979. }
  24980. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24982. "/ws-echo");
  24983. client.set_connection_timeout(std::chrono::seconds(3));
  24984. client.set_write_timeout(std::chrono::seconds(3));
  24985. // A sub-second remainder exercises the seconds/microseconds split.
  24986. client.set_read_timeout(std::chrono::milliseconds(1500));
  24987. ASSERT_TRUE(client.connect());
  24988. auto start = std::chrono::steady_clock::now();
  24989. std::string msg;
  24990. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24991. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24992. std::chrono::steady_clock::now() - start)
  24993. .count();
  24994. // Above 1s so that dropping the microseconds half of the split fails here.
  24995. // Ignoring the setter altogether would not reach this line at all: a client
  24996. // waits forever by default.
  24997. EXPECT_GE(elapsed, 1400);
  24998. EXPECT_LT(elapsed, 30000);
  24999. }
  25000. #ifndef _WIN32
  25001. // A send() that times out after part of the data went out returns the count
  25002. // written so far. Every byte of the frame must still be sent, or the peer reads
  25003. // the next frame's header and payload as the rest of this one.
  25004. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  25005. signal(SIGPIPE, SIG_IGN);
  25006. const std::string large(4 * 1024 * 1024, 'A');
  25007. std::atomic<bool> large_sent{false};
  25008. std::atomic<bool> small_sent{false};
  25009. Server svr;
  25010. svr.set_write_timeout(0, 500000);
  25011. svr.set_socket_options([](socket_t sock) {
  25012. int size = 8192;
  25013. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25014. reinterpret_cast<const char *>(&size), sizeof(size));
  25015. });
  25016. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25017. large_sent = ws.send(large.data(), large.size());
  25018. small_sent = ws.send("after");
  25019. std::string msg;
  25020. while (ws.read(msg)) {}
  25021. });
  25022. auto port = svr.bind_to_any_port(HOST);
  25023. std::thread t([&]() { svr.listen_after_bind(); });
  25024. auto se = detail::scope_exit([&] {
  25025. svr.stop();
  25026. t.join();
  25027. });
  25028. svr.wait_until_ready();
  25029. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25030. std::to_string(port) + "/ws");
  25031. client.set_read_timeout(5);
  25032. client.set_socket_options([](socket_t sock) {
  25033. int size = 8192;
  25034. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25035. reinterpret_cast<const char *>(&size), sizeof(size));
  25036. });
  25037. ASSERT_TRUE(client.connect());
  25038. // Outlast the server's write timeout, then drain.
  25039. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25040. std::string msg;
  25041. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25042. EXPECT_TRUE(msg == large);
  25043. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25044. EXPECT_EQ("after", msg);
  25045. EXPECT_TRUE(large_sent);
  25046. EXPECT_TRUE(small_sent);
  25047. client.close();
  25048. }
  25049. // A send() that fails partway leaves a frame on the wire whose header announces
  25050. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25051. // as the rest of it and a later payload's bytes as a frame of their own.
  25052. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25053. signal(SIGPIPE, SIG_IGN);
  25054. const std::string large(4 * 1024 * 1024, 'A');
  25055. std::atomic<bool> large_sent{true};
  25056. std::atomic<bool> open_after_failure{true};
  25057. std::atomic<bool> handler_done{false};
  25058. Server svr;
  25059. svr.set_write_timeout(0, 200000);
  25060. svr.set_socket_options([](socket_t sock) {
  25061. int size = 8192;
  25062. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25063. reinterpret_cast<const char *>(&size), sizeof(size));
  25064. });
  25065. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25066. large_sent = ws.send(large.data(), large.size());
  25067. open_after_failure = ws.is_open();
  25068. handler_done = true;
  25069. });
  25070. auto port = svr.bind_to_any_port(HOST);
  25071. std::thread t([&]() { svr.listen_after_bind(); });
  25072. auto se = detail::scope_exit([&] {
  25073. svr.stop();
  25074. t.join();
  25075. });
  25076. svr.wait_until_ready();
  25077. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25078. std::to_string(port) + "/ws");
  25079. client.set_socket_options([](socket_t sock) {
  25080. int size = 8192;
  25081. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25082. reinterpret_cast<const char *>(&size), sizeof(size));
  25083. });
  25084. ASSERT_TRUE(client.connect());
  25085. // Read nothing, so the server's write times out partway through the frame.
  25086. for (int i = 0; i < 100 && !handler_done; i++) {
  25087. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25088. }
  25089. ASSERT_TRUE(handler_done);
  25090. ASSERT_FALSE(large_sent);
  25091. EXPECT_FALSE(open_after_failure);
  25092. client.close();
  25093. }
  25094. #endif
  25095. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25096. Server svr;
  25097. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25098. if (!req.has_header("Authorization")) {
  25099. res.status = StatusCode::Unauthorized_401;
  25100. res.set_content("Unauthorized", "text/plain");
  25101. return Server::HandlerResponse::Handled;
  25102. }
  25103. return Server::HandlerResponse::Unhandled;
  25104. });
  25105. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25106. std::string msg;
  25107. while (ws.read(msg)) {
  25108. ws.send(msg);
  25109. }
  25110. });
  25111. auto port = svr.bind_to_any_port("localhost");
  25112. std::thread t([&]() { svr.listen_after_bind(); });
  25113. svr.wait_until_ready();
  25114. // Without Authorization header - should be rejected before upgrade
  25115. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25116. EXPECT_FALSE(client1.connect());
  25117. // The rejection is framed like any other HTTP response
  25118. {
  25119. Client cli("localhost", port);
  25120. Headers headers = {{"Upgrade", "websocket"},
  25121. {"Connection", "Upgrade"},
  25122. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25123. {"Sec-WebSocket-Version", "13"}};
  25124. auto res = cli.Get("/ws", headers);
  25125. ASSERT_TRUE(res);
  25126. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25127. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25128. EXPECT_EQ("Unauthorized", res->body);
  25129. }
  25130. // With Authorization header - should succeed
  25131. Headers headers = {{"Authorization", "Bearer token123"}};
  25132. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25133. headers);
  25134. ASSERT_TRUE(client2.connect());
  25135. ASSERT_TRUE(client2.send("hello"));
  25136. std::string msg;
  25137. ASSERT_TRUE(client2.read(msg));
  25138. EXPECT_EQ("hello", msg);
  25139. client2.close();
  25140. svr.stop();
  25141. t.join();
  25142. }
  25143. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25144. Server svr;
  25145. std::atomic<int> pre_routing_calls{0};
  25146. std::atomic<int> pre_request_calls{0};
  25147. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25148. pre_routing_calls++;
  25149. if (req.path == "/handled") {
  25150. res.set_content("handled", "text/plain");
  25151. return Server::HandlerResponse::Handled;
  25152. }
  25153. return Server::HandlerResponse::Unhandled;
  25154. });
  25155. svr.set_pre_request_handler([&](const Request &, Response &) {
  25156. pre_request_calls++;
  25157. return Server::HandlerResponse::Unhandled;
  25158. });
  25159. svr.Get("/http", [](const Request &, Response &res) {
  25160. res.set_content("http", "text/plain");
  25161. });
  25162. svr.WebSocket("/ws",
  25163. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25164. auto port = svr.bind_to_any_port("localhost");
  25165. std::thread t([&]() { svr.listen_after_bind(); });
  25166. auto se = detail::scope_exit([&] {
  25167. svr.stop();
  25168. t.join();
  25169. });
  25170. svr.wait_until_ready();
  25171. Headers upgrade = {{"Upgrade", "websocket"},
  25172. {"Connection", "Upgrade"},
  25173. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25174. {"Sec-WebSocket-Version", "13"}};
  25175. auto get = [&](const char *path) {
  25176. pre_routing_calls = 0;
  25177. return Client("localhost", port).Get(path, upgrade);
  25178. };
  25179. // No WebSocket route, but an HTTP one
  25180. auto res = get("/http");
  25181. ASSERT_TRUE(res);
  25182. EXPECT_EQ(StatusCode::OK_200, res->status);
  25183. EXPECT_EQ("http", res->body);
  25184. EXPECT_EQ(1, pre_routing_calls);
  25185. EXPECT_EQ(1, pre_request_calls);
  25186. // No route at all
  25187. res = get("/none");
  25188. ASSERT_TRUE(res);
  25189. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25190. EXPECT_EQ(1, pre_routing_calls);
  25191. // Answered by the pre-routing handler
  25192. res = get("/handled");
  25193. ASSERT_TRUE(res);
  25194. EXPECT_EQ(StatusCode::OK_200, res->status);
  25195. EXPECT_EQ("handled", res->body);
  25196. EXPECT_EQ(1, pre_routing_calls);
  25197. // A WebSocket route
  25198. pre_routing_calls = 0;
  25199. pre_request_calls = 0;
  25200. {
  25201. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25202. "/ws");
  25203. ASSERT_TRUE(client.connect());
  25204. std::string msg;
  25205. ASSERT_TRUE(client.read(msg));
  25206. EXPECT_EQ("ws", msg);
  25207. client.close();
  25208. }
  25209. EXPECT_EQ(1, pre_routing_calls);
  25210. EXPECT_EQ(1, pre_request_calls);
  25211. }
  25212. // An upgrade request answered by a hook leaves its body unread, so that body
  25213. // must not be served as the next request on the connection.
  25214. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25215. Server svr;
  25216. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25217. if (req.path == "/pre-routing") {
  25218. res.set_content("pre-routing", "text/plain");
  25219. return Server::HandlerResponse::Handled;
  25220. }
  25221. return Server::HandlerResponse::Unhandled;
  25222. });
  25223. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25224. if (req.matched_route == "/pre-request") {
  25225. res.set_content("pre-request", "text/plain");
  25226. return Server::HandlerResponse::Handled;
  25227. }
  25228. return Server::HandlerResponse::Unhandled;
  25229. });
  25230. svr.Get("/smuggled", [](const Request &, Response &res) {
  25231. res.set_content("smuggled", "text/plain");
  25232. });
  25233. svr.WebSocket("/pre-request",
  25234. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25235. auto port = svr.bind_to_any_port(HOST);
  25236. std::thread t([&]() { svr.listen_after_bind(); });
  25237. auto se = detail::scope_exit([&] {
  25238. svr.stop();
  25239. t.join();
  25240. });
  25241. svr.wait_until_ready();
  25242. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25243. for (auto path : {"/pre-routing", "/pre-request"}) {
  25244. std::string req = std::string("GET ") + path +
  25245. " HTTP/1.1\r\n"
  25246. "Host: localhost\r\n"
  25247. "Upgrade: websocket\r\n"
  25248. "Connection: Upgrade\r\n"
  25249. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25250. "Sec-WebSocket-Version: 13\r\n"
  25251. "Content-Length: " +
  25252. std::to_string(body.size()) + "\r\n\r\n" + body;
  25253. std::string res;
  25254. ASSERT_TRUE(send_request(5, req, &res, port));
  25255. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25256. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25257. // Only one response, and the body was not served as a request
  25258. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25259. }
  25260. }
  25261. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25262. Server svr;
  25263. std::atomic<int> pre_request_calls{0};
  25264. std::atomic<bool> route_matched{false};
  25265. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25266. pre_request_calls++;
  25267. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25268. if (req.get_header_value("Authorization") != "Bearer token123") {
  25269. res.status = StatusCode::Unauthorized_401;
  25270. res.set_content("Unauthorized", "text/plain");
  25271. return Server::HandlerResponse::Handled;
  25272. }
  25273. return Server::HandlerResponse::Unhandled;
  25274. });
  25275. std::atomic<bool> handler_called{false};
  25276. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25277. handler_called = true;
  25278. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25279. });
  25280. auto port = svr.bind_to_any_port("localhost");
  25281. std::thread t([&]() { svr.listen_after_bind(); });
  25282. svr.wait_until_ready();
  25283. // Without Authorization header - should be rejected before upgrade
  25284. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25285. "/ws/1");
  25286. EXPECT_FALSE(client1.connect());
  25287. EXPECT_FALSE(handler_called);
  25288. EXPECT_EQ(1, pre_request_calls);
  25289. EXPECT_TRUE(route_matched);
  25290. // The rejection is an ordinary HTTP response, not a protocol switch
  25291. {
  25292. Client cli("localhost", port);
  25293. Headers headers = {{"Upgrade", "websocket"},
  25294. {"Connection", "Upgrade"},
  25295. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25296. {"Sec-WebSocket-Version", "13"}};
  25297. auto res = cli.Get("/ws/1", headers);
  25298. ASSERT_TRUE(res);
  25299. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25300. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25301. EXPECT_EQ("Unauthorized", res->body);
  25302. }
  25303. EXPECT_FALSE(handler_called);
  25304. // With Authorization header - should succeed
  25305. Headers headers = {{"Authorization", "Bearer token123"}};
  25306. ws::WebSocketClient client2(
  25307. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25308. ASSERT_TRUE(client2.connect());
  25309. std::string msg;
  25310. ASSERT_TRUE(client2.read(msg));
  25311. EXPECT_EQ("/ws/:id 2", msg);
  25312. EXPECT_TRUE(handler_called);
  25313. client2.close();
  25314. svr.stop();
  25315. t.join();
  25316. }
  25317. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25318. static Headers websocket_upgrade_headers() {
  25319. return {{"Upgrade", "websocket"},
  25320. {"Connection", "Upgrade"},
  25321. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25322. {"Sec-WebSocket-Version", "13"},
  25323. {"Sec-WebSocket-Protocol", "chat"}};
  25324. }
  25325. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25326. Server svr;
  25327. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25328. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25329. return Server::HandlerResponse::Unhandled;
  25330. });
  25331. svr.set_pre_request_handler([](const Request &req, Response &) {
  25332. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25333. return Server::HandlerResponse::Unhandled;
  25334. });
  25335. svr.set_exception_handler(
  25336. [](const Request &, Response &res, std::exception_ptr ep) {
  25337. try {
  25338. std::rethrow_exception(ep);
  25339. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25340. });
  25341. auto handler = [](const Request &, ws::WebSocket &) {};
  25342. svr.WebSocket("/pre-routing", handler);
  25343. svr.WebSocket("/pre-request", handler);
  25344. svr.WebSocket("/sub-protocol", handler,
  25345. [](const std::vector<std::string> &) -> std::string {
  25346. throw std::runtime_error("/sub-protocol");
  25347. });
  25348. auto port = svr.bind_to_any_port(HOST);
  25349. ASSERT_GT(port, 0);
  25350. thread t = thread([&] { svr.listen_after_bind(); });
  25351. auto se = detail::scope_exit([&] {
  25352. svr.stop();
  25353. t.join();
  25354. ASSERT_FALSE(svr.is_running());
  25355. });
  25356. svr.wait_until_ready();
  25357. Client cli(HOST, port);
  25358. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25359. auto res = cli.Get(path, websocket_upgrade_headers());
  25360. if (!res) {
  25361. ADD_FAILURE() << path << ": " << to_string(res.error());
  25362. continue;
  25363. }
  25364. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25365. EXPECT_EQ(path, res->body);
  25366. }
  25367. }
  25368. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25369. Server svr;
  25370. svr.set_pre_routing_handler(
  25371. [](const Request &, Response &) -> Server::HandlerResponse {
  25372. throw std::runtime_error("pre-routing");
  25373. });
  25374. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25375. auto port = svr.bind_to_any_port(HOST);
  25376. ASSERT_GT(port, 0);
  25377. thread t = thread([&] { svr.listen_after_bind(); });
  25378. auto se = detail::scope_exit([&] {
  25379. svr.stop();
  25380. t.join();
  25381. ASSERT_FALSE(svr.is_running());
  25382. });
  25383. svr.wait_until_ready();
  25384. Client cli(HOST, port);
  25385. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25386. ASSERT_TRUE(res) << to_string(res.error());
  25387. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25388. }
  25389. #endif
  25390. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25391. Server svr;
  25392. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25393. // A read timeout is how a handler gets control back. Without it, a handler
  25394. // parked in read() can never write on the connection it is reading.
  25395. ws.set_read_timeout(std::chrono::milliseconds(100));
  25396. std::string msg;
  25397. while (ws.is_open()) {
  25398. auto r = ws.read(msg);
  25399. if (r == httplib::ws::Timeout) {
  25400. ws.send("tick");
  25401. continue;
  25402. }
  25403. if (r == httplib::ws::Fail) { break; }
  25404. ws.send(msg);
  25405. }
  25406. });
  25407. auto port = svr.bind_to_any_port("localhost");
  25408. std::thread t([&]() { svr.listen_after_bind(); });
  25409. svr.wait_until_ready();
  25410. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25411. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25412. ASSERT_TRUE(client.connect());
  25413. // The client sends nothing, so anything it receives came out of the
  25414. // handler's timeout path.
  25415. std::string msg;
  25416. ASSERT_EQ(client.read(msg), ws::Text);
  25417. EXPECT_EQ("tick", msg);
  25418. client.close();
  25419. svr.stop();
  25420. t.join();
  25421. }
  25422. // Stream::read may return fewer bytes than asked for. This is that contract at
  25423. // its worst -- one byte per call -- which is what a frame header straddling a
  25424. // read buffer's boundary looks like to the frame parser.
  25425. class WsByteAtATimeStream : public Stream {
  25426. public:
  25427. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25428. bool is_readable() const override { return true; }
  25429. bool wait_readable() const override { return true; }
  25430. bool wait_writable() const override { return true; }
  25431. ssize_t read(char *ptr, size_t size) override {
  25432. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25433. *ptr = data_[pos_++];
  25434. return 1;
  25435. }
  25436. ssize_t write(const char *, size_t size) override {
  25437. return static_cast<ssize_t>(size);
  25438. }
  25439. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25440. ip = "127.0.0.1";
  25441. port = 0;
  25442. }
  25443. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25444. ip = "127.0.0.1";
  25445. port = 0;
  25446. }
  25447. socket_t socket() const override { return INVALID_SOCKET; }
  25448. time_t duration() const override { return 0; }
  25449. private:
  25450. std::string data_;
  25451. size_t pos_ = 0;
  25452. };
  25453. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25454. // The payload uses the 16-bit extended length, so the header, the length
  25455. // and the mask key are all multi-byte fields here. Each used to be read
  25456. // with a single read() call, which fails as soon as one is split. The
  25457. // payload is also a little over one read chunk, so it is read in two.
  25458. std::string body;
  25459. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25460. body += static_cast<char>(i % 251);
  25461. }
  25462. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25463. std::string frame;
  25464. frame += static_cast<char>(0x81); // FIN + Text
  25465. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25466. frame += static_cast<char>(body.size() >> 8);
  25467. frame += static_cast<char>(body.size() & 0xff);
  25468. for (size_t i = 0; i < 4; i++) {
  25469. frame += static_cast<char>(mask[i]);
  25470. }
  25471. for (size_t i = 0; i < body.size(); i++) {
  25472. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25473. }
  25474. WsByteAtATimeStream strm(frame);
  25475. ws::Opcode opcode;
  25476. std::string payload;
  25477. bool fin = false;
  25478. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25479. /*expect_masked=*/true, body.size()),
  25480. ws::impl::FrameRead::Ok);
  25481. EXPECT_TRUE(fin);
  25482. EXPECT_EQ(opcode, ws::Opcode::Text);
  25483. EXPECT_EQ(payload, body);
  25484. }
  25485. // Keeps what is written, counting the writes, and reads it back.
  25486. class WsWriteCountingStream : public Stream {
  25487. public:
  25488. bool is_readable() const override { return true; }
  25489. bool wait_readable() const override { return true; }
  25490. bool wait_writable() const override { return true; }
  25491. ssize_t read(char *ptr, size_t size) override {
  25492. auto n = (std::min)(size, data_.size() - pos_);
  25493. if (n == 0) { return 0; }
  25494. memcpy(ptr, data_.data() + pos_, n);
  25495. pos_ += n;
  25496. return static_cast<ssize_t>(n);
  25497. }
  25498. ssize_t write(const char *ptr, size_t size) override {
  25499. writes++;
  25500. data_.append(ptr, size);
  25501. return static_cast<ssize_t>(size);
  25502. }
  25503. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25504. ip = "127.0.0.1";
  25505. port = 0;
  25506. }
  25507. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25508. ip = "127.0.0.1";
  25509. port = 0;
  25510. }
  25511. socket_t socket() const override { return INVALID_SOCKET; }
  25512. time_t duration() const override { return 0; }
  25513. int writes = 0;
  25514. private:
  25515. std::string data_;
  25516. size_t pos_ = 0;
  25517. };
  25518. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25519. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25520. // masked and not, reads back as written; a payload over one chunk follows
  25521. // its first in more writes.
  25522. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25523. for (auto mask : {false, true}) {
  25524. std::string body(len, '\0');
  25525. for (size_t i = 0; i < len; i++) {
  25526. body[i] = static_cast<char>(i % 251);
  25527. }
  25528. WsWriteCountingStream strm;
  25529. ASSERT_TRUE(detail::write_websocket_frame(
  25530. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25531. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25532. ws::Opcode opcode;
  25533. std::string payload;
  25534. bool fin = false;
  25535. ASSERT_EQ(
  25536. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25537. ws::impl::FrameRead::Ok)
  25538. << len << " " << mask;
  25539. EXPECT_TRUE(fin);
  25540. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25541. EXPECT_EQ(body, payload) << len << " " << mask;
  25542. }
  25543. }
  25544. }
  25545. // Hands out its pieces one read at a time, timing out between each two.
  25546. class WsTimeoutBetweenPiecesStream : public Stream {
  25547. public:
  25548. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25549. : pieces_(std::move(pieces)) {}
  25550. bool is_readable() const override { return true; }
  25551. bool wait_readable() const override { return true; }
  25552. bool wait_writable() const override { return true; }
  25553. ssize_t read(char *ptr, size_t size) override {
  25554. if (time_out_) {
  25555. time_out_ = false;
  25556. error_ = Error::Timeout;
  25557. return -1;
  25558. }
  25559. if (i_ >= pieces_.size()) {
  25560. error_ = Error::ConnectionClosed;
  25561. return 0;
  25562. }
  25563. auto &piece = pieces_[i_];
  25564. auto n = (std::min)(size, piece.size() - at_);
  25565. memcpy(ptr, piece.data() + at_, n);
  25566. at_ += n;
  25567. if (at_ == piece.size()) {
  25568. i_++;
  25569. at_ = 0;
  25570. time_out_ = true;
  25571. }
  25572. return static_cast<ssize_t>(n);
  25573. }
  25574. ssize_t write(const char *, size_t size) override {
  25575. return static_cast<ssize_t>(size);
  25576. }
  25577. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25578. ip = "127.0.0.1";
  25579. port = 0;
  25580. }
  25581. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25582. ip = "127.0.0.1";
  25583. port = 0;
  25584. }
  25585. socket_t socket() const override { return INVALID_SOCKET; }
  25586. time_t duration() const override { return 0; }
  25587. private:
  25588. std::vector<std::string> pieces_;
  25589. size_t i_ = 0;
  25590. size_t at_ = 0;
  25591. bool time_out_ = false;
  25592. };
  25593. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25594. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25595. std::string frame = "\x81\x85";
  25596. frame.append(4, '\0');
  25597. frame += "Hello";
  25598. // The header's first byte, then its second with half the mask key, then
  25599. // the rest
  25600. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25601. frame.substr(4)};
  25602. WsTimeoutBetweenPiecesStream strm(pieces);
  25603. ws::impl::FrameReader reader;
  25604. ws::Opcode opcode;
  25605. std::string payload;
  25606. bool fin = false;
  25607. for (int i = 0; i < 2; i++) {
  25608. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25609. reader.read(strm, opcode, payload, fin, true, 0));
  25610. EXPECT_TRUE(reader.begun());
  25611. }
  25612. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25613. reader.read(strm, opcode, payload, fin, true, 0));
  25614. EXPECT_FALSE(reader.begun());
  25615. EXPECT_TRUE(fin);
  25616. EXPECT_EQ(ws::Opcode::Text, opcode);
  25617. EXPECT_EQ("Hello", payload);
  25618. // Read in one go, the frame cannot be gone on with after a timeout
  25619. WsTimeoutBetweenPiecesStream again(pieces);
  25620. EXPECT_EQ(
  25621. ws::impl::FrameRead::Fail,
  25622. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25623. }
  25624. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25625. std::string body(2000, 'x');
  25626. std::string frame;
  25627. frame += static_cast<char>(0x82); // FIN + Binary
  25628. frame += static_cast<char>(126); // 16-bit length follows
  25629. frame += static_cast<char>(body.size() >> 8);
  25630. frame += static_cast<char>(body.size() & 0xff);
  25631. frame += body;
  25632. detail::BufferStream strm;
  25633. strm.write(frame.data(), frame.size());
  25634. ws::Opcode opcode;
  25635. std::string payload;
  25636. bool fin;
  25637. EXPECT_EQ(
  25638. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25639. ws::impl::FrameRead::Ok);
  25640. EXPECT_EQ(body, payload);
  25641. }
  25642. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25643. // The header announces the largest payload allowed, and only 3 bytes of it
  25644. // ever arrive.
  25645. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25646. std::string frame;
  25647. frame += static_cast<char>(0x82); // FIN + Binary
  25648. frame += static_cast<char>(127); // 64-bit length follows
  25649. for (int shift = 56; shift >= 0; shift -= 8) {
  25650. frame += static_cast<char>((len >> shift) & 0xff);
  25651. }
  25652. frame += "abc";
  25653. detail::BufferStream strm;
  25654. strm.write(frame.data(), frame.size());
  25655. ws::Opcode opcode;
  25656. std::string payload;
  25657. bool fin;
  25658. EXPECT_EQ(
  25659. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25660. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25661. ws::impl::FrameRead::Fail);
  25662. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25663. }
  25664. TEST(WebSocketTest, QueryStringInHandshake) {
  25665. Server svr;
  25666. std::mutex mtx;
  25667. std::string received_target;
  25668. std::string received_token;
  25669. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25670. {
  25671. std::lock_guard<std::mutex> lock(mtx);
  25672. received_target = req.target;
  25673. if (req.has_param("token")) {
  25674. received_token = req.get_param_value("token");
  25675. }
  25676. }
  25677. std::string msg;
  25678. while (ws.read(msg)) {
  25679. ws.send(msg);
  25680. }
  25681. });
  25682. auto port = svr.bind_to_any_port("localhost");
  25683. std::thread t([&]() { svr.listen_after_bind(); });
  25684. svr.wait_until_ready();
  25685. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25686. "/ws?token=ABC&session=123");
  25687. ASSERT_TRUE(client.connect());
  25688. // Round-trip ensures the handler has run and captured the request.
  25689. ASSERT_TRUE(client.send("hello"));
  25690. std::string msg;
  25691. ASSERT_TRUE(client.read(msg));
  25692. EXPECT_EQ("hello", msg);
  25693. client.close();
  25694. {
  25695. std::lock_guard<std::mutex> lock(mtx);
  25696. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25697. EXPECT_EQ("ABC", received_token);
  25698. }
  25699. svr.stop();
  25700. t.join();
  25701. }
  25702. // Run a handshake against a throwaway server and hand the request the server
  25703. // received back to the caller, so tests can assert on the headers the client
  25704. // actually put on the wire.
  25705. static void capture_websocket_handshake_request(
  25706. const Headers &client_headers,
  25707. std::function<void(const Request &, int port)> verify) {
  25708. Server svr;
  25709. std::mutex mtx;
  25710. Request received;
  25711. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25712. {
  25713. std::lock_guard<std::mutex> lock(mtx);
  25714. received = req;
  25715. }
  25716. std::string msg;
  25717. while (ws.read(msg)) {
  25718. ws.send(msg);
  25719. }
  25720. });
  25721. auto port = svr.bind_to_any_port("localhost");
  25722. std::thread t([&]() { svr.listen_after_bind(); });
  25723. auto se = detail::scope_exit([&] {
  25724. svr.stop();
  25725. t.join();
  25726. });
  25727. svr.wait_until_ready();
  25728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25729. client_headers);
  25730. ASSERT_TRUE(client.connect());
  25731. ASSERT_TRUE(client.send("hello"));
  25732. std::string msg;
  25733. ASSERT_TRUE(client.read(msg));
  25734. client.close();
  25735. {
  25736. std::lock_guard<std::mutex> lock(mtx);
  25737. verify(received, port);
  25738. }
  25739. }
  25740. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25741. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25742. // Non-default port must be present in the Host header. Default ports
  25743. // (80/443) are omitted; that logic is covered by
  25744. // MakeHostAndPortStringTest.
  25745. EXPECT_EQ("localhost:" + std::to_string(port),
  25746. req.get_header_value("Host"));
  25747. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25748. req.get_header_value("User-Agent"));
  25749. EXPECT_FALSE(req.has_header("Accept"));
  25750. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25751. EXPECT_FALSE(req.has_header("Content-Length"));
  25752. });
  25753. }
  25754. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25755. capture_websocket_handshake_request(
  25756. {{"Host", "example.com"},
  25757. {"User-Agent", "custom-agent"},
  25758. {"X-Custom", "value"}},
  25759. [](const Request &req, int) {
  25760. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25761. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25762. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25763. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25764. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25765. });
  25766. }
  25767. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25768. capture_websocket_handshake_request(
  25769. {{"Upgrade", "bogus"},
  25770. {"Connection", "close"},
  25771. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25772. {"Sec-WebSocket-Version", "8"}},
  25773. [](const Request &req, int) {
  25774. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25775. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25776. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25777. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25778. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25779. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25780. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25781. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25782. req.get_header_value("Sec-WebSocket-Key"));
  25783. });
  25784. }
  25785. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25786. // A header the client refuses to send must abort the handshake before any
  25787. // part of it reaches the wire; a lone request line would otherwise sit in
  25788. // the peer's buffer as a truncated request.
  25789. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25790. ASSERT_NE(INVALID_SOCKET, srv);
  25791. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25792. sockaddr_in addr{};
  25793. addr.sin_family = AF_INET;
  25794. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25795. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25796. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25797. ASSERT_EQ(0, ::listen(srv, 1));
  25798. sockaddr_in bound{};
  25799. socklen_t bound_len = sizeof(bound);
  25800. ASSERT_EQ(
  25801. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25802. auto port = ntohs(bound.sin_port);
  25803. ssize_t received = -1;
  25804. std::thread t([&] {
  25805. // Bound every blocking call so a regression fails the test with a bad
  25806. // value instead of hanging the suite.
  25807. fd_set rfds;
  25808. FD_ZERO(&rfds);
  25809. FD_SET(srv, &rfds);
  25810. timeval tv{5, 0};
  25811. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25812. 0) {
  25813. return;
  25814. }
  25815. sockaddr_in cli_addr{};
  25816. socklen_t cli_len = sizeof(cli_addr);
  25817. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25818. if (cli == INVALID_SOCKET) { return; }
  25819. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25820. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25821. char buf[4096];
  25822. received = ::recv(cli, buf, sizeof(buf), 0);
  25823. });
  25824. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25825. // connect() has already shut the socket down by the time it returns false,
  25826. // so the peer sees EOF without waiting for the client to be destroyed.
  25827. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25828. {{"X-Bad", "a\r\nInjected: 1"}});
  25829. EXPECT_FALSE(client.connect());
  25830. t.join();
  25831. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25832. EXPECT_EQ(0, received);
  25833. }
  25834. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25835. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25836. // contains "upgrade" as a substring is a different token and must not
  25837. // start a WebSocket handshake.
  25838. auto make_request = [](const std::vector<std::string> &connection_values) {
  25839. Request req;
  25840. req.method = "GET";
  25841. req.headers.emplace("Upgrade", "websocket");
  25842. for (const auto &value : connection_values) {
  25843. req.headers.emplace("Connection", value);
  25844. }
  25845. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25846. req.headers.emplace("Sec-WebSocket-Version", "13");
  25847. return req;
  25848. };
  25849. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25850. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25851. EXPECT_TRUE(
  25852. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25853. EXPECT_TRUE(
  25854. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25855. EXPECT_TRUE(
  25856. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25857. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25858. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25859. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25860. EXPECT_FALSE(
  25861. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25862. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25863. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25864. }
  25865. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25866. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25867. // asks recipients to match each protocol-name case-insensitively, and RFC
  25868. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25869. // client naming websocket alongside another protocol, or on a second field
  25870. // line, is offering websocket; a value that merely contains "websocket" as a
  25871. // substring is a different protocol name and is not.
  25872. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25873. Request req;
  25874. req.method = "GET";
  25875. for (const auto &value : upgrade_values) {
  25876. req.headers.emplace("Upgrade", value);
  25877. }
  25878. req.headers.emplace("Connection", "Upgrade");
  25879. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25880. req.headers.emplace("Sec-WebSocket-Version", "13");
  25881. return req;
  25882. };
  25883. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25884. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25885. EXPECT_TRUE(
  25886. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25887. EXPECT_TRUE(
  25888. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25889. EXPECT_TRUE(
  25890. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25891. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25892. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25893. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25894. EXPECT_FALSE(
  25895. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25896. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25897. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25898. }
  25899. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25900. Server svr;
  25901. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25902. auto port = svr.bind_to_any_port("localhost");
  25903. std::thread t([&]() { svr.listen_after_bind(); });
  25904. auto se = detail::scope_exit([&] {
  25905. svr.stop();
  25906. t.join();
  25907. });
  25908. svr.wait_until_ready();
  25909. Headers headers = {{"Upgrade", "websocket"},
  25910. {"Connection", "notupgrade"},
  25911. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25912. {"Sec-WebSocket-Version", "13"}};
  25913. Client cli("localhost", port);
  25914. auto res = cli.Get("/ws", headers);
  25915. // The route exists only as a WebSocket route, so a request that fails the
  25916. // handshake check falls through to ordinary routing.
  25917. ASSERT_TRUE(res);
  25918. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25919. }
  25920. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25921. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25922. // Connection value is the only thing left for the client to reject.
  25923. Server svr;
  25924. svr.Get("/ws", [](const Request &req, Response &res) {
  25925. res.status = StatusCode::SwitchingProtocol_101;
  25926. res.set_header("Upgrade", "websocket");
  25927. res.set_header("Connection", "notupgrade");
  25928. res.set_header("Sec-WebSocket-Accept",
  25929. detail::websocket_accept_key(
  25930. req.get_header_value("Sec-WebSocket-Key")));
  25931. });
  25932. auto port = svr.bind_to_any_port("localhost");
  25933. std::thread t([&]() { svr.listen_after_bind(); });
  25934. auto se = detail::scope_exit([&] {
  25935. svr.stop();
  25936. t.join();
  25937. });
  25938. svr.wait_until_ready();
  25939. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25940. auto res = client.connect();
  25941. EXPECT_FALSE(res);
  25942. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25943. EXPECT_FALSE(client.is_open());
  25944. }
  25945. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25946. Server svr;
  25947. svr.Get("/ws", [](const Request &req, Response &res) {
  25948. res.status = StatusCode::SwitchingProtocol_101;
  25949. res.set_header("Upgrade", "websocket");
  25950. res.set_header("Connection", "Upgrade");
  25951. res.set_header("Sec-WebSocket-Accept",
  25952. detail::websocket_accept_key(
  25953. req.get_header_value("Sec-WebSocket-Key")));
  25954. res.set_header("Sec-WebSocket-Protocol", "admin");
  25955. });
  25956. auto port = svr.bind_to_any_port("localhost");
  25957. std::thread t([&]() { svr.listen_after_bind(); });
  25958. auto se = detail::scope_exit([&] {
  25959. svr.stop();
  25960. t.join();
  25961. });
  25962. svr.wait_until_ready();
  25963. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25964. // Server selects a subprotocol the client never offered
  25965. {
  25966. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25967. ws::WebSocketClient client(url, headers);
  25968. auto res = client.connect();
  25969. EXPECT_FALSE(res);
  25970. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25971. EXPECT_FALSE(client.is_open());
  25972. EXPECT_TRUE(client.subprotocol().empty());
  25973. }
  25974. // Client offered none but the server named one anyway
  25975. {
  25976. ws::WebSocketClient client(url);
  25977. auto res = client.connect();
  25978. EXPECT_FALSE(res);
  25979. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25980. EXPECT_FALSE(client.is_open());
  25981. EXPECT_TRUE(client.subprotocol().empty());
  25982. }
  25983. }
  25984. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25985. // The socket path doubles as the URL host, so it must not contain '/'.
  25986. const char *shard = getenv("GTEST_SHARD_INDEX");
  25987. const std::string sock_path =
  25988. shard ? std::string("httplib-ws-") + shard + ".sock"
  25989. : std::string("httplib-ws.sock");
  25990. std::remove(sock_path.c_str());
  25991. Server svr;
  25992. std::mutex mtx;
  25993. std::string received_host;
  25994. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25995. {
  25996. std::lock_guard<std::mutex> lock(mtx);
  25997. received_host = req.get_header_value("Host");
  25998. }
  25999. std::string msg;
  26000. while (ws.read(msg)) {
  26001. ws.send(msg);
  26002. }
  26003. });
  26004. svr.set_address_family(AF_UNIX);
  26005. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  26006. auto se = detail::scope_exit([&] {
  26007. svr.stop();
  26008. t.join();
  26009. std::remove(sock_path.c_str());
  26010. });
  26011. svr.wait_until_ready();
  26012. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  26013. client.set_address_family(AF_UNIX);
  26014. ASSERT_TRUE(client.connect());
  26015. ASSERT_TRUE(client.send("hello"));
  26016. std::string msg;
  26017. ASSERT_TRUE(client.read(msg));
  26018. client.close();
  26019. {
  26020. std::lock_guard<std::mutex> lock(mtx);
  26021. // There is no host:port for a Unix socket, so the same "localhost"
  26022. // placeholder the HTTP client uses is expected.
  26023. EXPECT_EQ("localhost", received_host);
  26024. }
  26025. }
  26026. // Two threads must never parse WebSocket frames from the same stream.
  26027. // close() used to read the peer's Close reply with its own frame read, so it
  26028. // raced a reader thread that was in the middle of a payload: the payload loop
  26029. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  26030. // so bytes taken by close() were replaced with bytes from further along the
  26031. // stream. The message kept its length and silently changed content.
  26032. //
  26033. // The raw peer below sends a frame header plus part of the payload, waits for
  26034. // the handler to call close(), and only then sends the rest. Whichever thread
  26035. // would win the race for those bytes, the message must arrive intact, because
  26036. // close() must not touch the stream while read() owns it.
  26037. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  26038. #ifndef _WIN32
  26039. signal(SIGPIPE, SIG_IGN);
  26040. #endif
  26041. const size_t payload_len = 120; // fits the 7-bit length field
  26042. const size_t prefix_len = 8;
  26043. const int attempts = 8;
  26044. std::string expected(payload_len, '\0');
  26045. for (size_t i = 0; i < payload_len; i++) {
  26046. expected[i] = static_cast<char>('a' + i % 26);
  26047. }
  26048. std::atomic<bool> peer_stalled{false};
  26049. std::atomic<bool> handler_done{false};
  26050. std::mutex received_mutex;
  26051. std::vector<std::string> received;
  26052. // Bound every wait, so a regression fails the test instead of hanging the
  26053. // suite.
  26054. auto wait_for = [](const std::atomic<bool> &flag) {
  26055. for (int i = 0; i < 500 && !flag; i++) {
  26056. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26057. }
  26058. };
  26059. Server svr;
  26060. svr.set_websocket_ping_interval(0);
  26061. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26062. std::thread reader([&]() {
  26063. std::string msg;
  26064. while (ws.read(msg)) {
  26065. std::lock_guard<std::mutex> guard(received_mutex);
  26066. received.push_back(msg);
  26067. }
  26068. });
  26069. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26070. // inside a frame when close() runs.
  26071. wait_for(peer_stalled);
  26072. ws.close();
  26073. reader.join();
  26074. handler_done = true;
  26075. });
  26076. auto port = svr.bind_to_any_port("127.0.0.1");
  26077. std::thread t([&]() { svr.listen_after_bind(); });
  26078. auto se = detail::scope_exit([&] {
  26079. svr.stop();
  26080. t.join();
  26081. });
  26082. svr.wait_until_ready();
  26083. auto send_bytes = [](socket_t s, const std::string &data) {
  26084. #ifdef _WIN32
  26085. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26086. #else
  26087. auto n = ::send(s, data.data(), data.size(), 0);
  26088. #endif
  26089. return n == static_cast<decltype(n)>(data.size());
  26090. };
  26091. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26092. // Every length used here fits the 7-bit length field.
  26093. auto masked_header = [](uint8_t first_byte, size_t len) {
  26094. std::string h;
  26095. h += static_cast<char>(first_byte);
  26096. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26097. h.append(4, '\0'); // mask key
  26098. return h;
  26099. };
  26100. for (int attempt = 0; attempt < attempts; attempt++) {
  26101. peer_stalled = false;
  26102. handler_done = false;
  26103. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26104. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26105. auto se_sock = detail::scope_exit([&] {
  26106. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26107. });
  26108. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26109. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26110. sockaddr_in addr{};
  26111. addr.sin_family = AF_INET;
  26112. addr.sin_port = htons(static_cast<uint16_t>(port));
  26113. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26114. ASSERT_EQ(
  26115. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26116. << "attempt " << attempt;
  26117. ASSERT_TRUE(send_bytes(sock,
  26118. "GET /ws HTTP/1.1\r\n"
  26119. "Host: 127.0.0.1\r\n"
  26120. "Upgrade: websocket\r\n"
  26121. "Connection: Upgrade\r\n"
  26122. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26123. "Sec-WebSocket-Version: 13\r\n"
  26124. "\r\n"))
  26125. << "attempt " << attempt;
  26126. std::string response;
  26127. while (response.find("\r\n\r\n") == std::string::npos) {
  26128. char buf[512];
  26129. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26130. if (n <= 0) { break; }
  26131. response.append(buf, static_cast<size_t>(n));
  26132. }
  26133. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26134. << "attempt " << attempt;
  26135. // Send the header of a Binary message but only the first prefix_len bytes
  26136. // of its payload, leaving the reader thread stalled inside the payload.
  26137. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26138. expected.substr(0, prefix_len)))
  26139. << "attempt " << attempt;
  26140. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26141. peer_stalled = true;
  26142. // Let close() send its Close frame and park in its own read before the
  26143. // rest of the payload arrives, so both threads are waiting for it.
  26144. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26145. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26146. close_frame += static_cast<char>(0x03); // status 1000
  26147. close_frame += static_cast<char>(0xE8);
  26148. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26149. << "attempt " << attempt;
  26150. // Closing the peer releases the reader thread even on the buggy path,
  26151. // where it waits for bytes another thread already consumed.
  26152. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26153. detail::close_socket(sock);
  26154. sock = INVALID_SOCKET;
  26155. wait_for(handler_done);
  26156. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26157. }
  26158. std::lock_guard<std::mutex> guard(received_mutex);
  26159. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26160. << "a message in flight when close() ran was dropped";
  26161. for (size_t i = 0; i < received.size(); i++) {
  26162. EXPECT_EQ(expected, received[i]) << "message " << i;
  26163. }
  26164. }
  26165. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26166. // returning the socket, or INVALID_SOCKET.
  26167. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26168. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26169. if (sock == INVALID_SOCKET) { return sock; }
  26170. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26171. sockaddr_in addr{};
  26172. addr.sin_family = AF_INET;
  26173. addr.sin_port = htons(static_cast<uint16_t>(port));
  26174. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26175. std::string req = "GET " + path +
  26176. " HTTP/1.1\r\n"
  26177. "Host: 127.0.0.1\r\n"
  26178. "Upgrade: websocket\r\n"
  26179. "Connection: Upgrade\r\n"
  26180. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26181. "Sec-WebSocket-Version: 13\r\n"
  26182. "\r\n";
  26183. std::string res;
  26184. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26185. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26186. static_cast<ssize_t>(req.size())) {
  26187. char c;
  26188. while (res.find("\r\n\r\n") == std::string::npos &&
  26189. ::recv(sock, &c, 1, 0) == 1) {
  26190. res += c;
  26191. }
  26192. }
  26193. if (res.find(" 101 ") == std::string::npos) {
  26194. detail::close_socket(sock);
  26195. return INVALID_SOCKET;
  26196. }
  26197. return sock;
  26198. }
  26199. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26200. // The payload must fit the 7-bit length field.
  26201. static std::string masked_frame(uint8_t first_byte,
  26202. const std::string &payload) {
  26203. std::string f;
  26204. f += static_cast<char>(first_byte);
  26205. f += static_cast<char>(0x80 | payload.size());
  26206. f.append(4, '\0');
  26207. return f + payload;
  26208. }
  26209. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26210. // server sends back, or what came before it closed.
  26211. static std::string raw_websocket_reply(int port, const std::string &frames,
  26212. size_t n) {
  26213. auto sock = connect_raw_websocket(port, "/ws");
  26214. if (sock == INVALID_SOCKET) { return std::string(); }
  26215. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26216. std::string reply;
  26217. char buf[256];
  26218. while (reply.size() < n) {
  26219. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26220. if (got <= 0) { break; }
  26221. reply.append(buf, static_cast<size_t>(got));
  26222. }
  26223. detail::close_socket(sock);
  26224. return reply;
  26225. }
  26226. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26227. std::atomic<bool> done{false};
  26228. std::string received;
  26229. Server svr;
  26230. svr.set_websocket_ping_interval(0);
  26231. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26232. std::string msg;
  26233. if (ws.read(msg) == ws::Binary) { received = msg; }
  26234. done = true;
  26235. });
  26236. auto port = svr.bind_to_any_port("127.0.0.1");
  26237. std::thread t([&]() { svr.listen_after_bind(); });
  26238. auto se = detail::scope_exit([&] {
  26239. svr.stop();
  26240. t.join();
  26241. });
  26242. svr.wait_until_ready();
  26243. auto sock = connect_raw_websocket(port, "/ws");
  26244. ASSERT_NE(INVALID_SOCKET, sock);
  26245. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26246. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26247. masked_frame(0x89, "p") + // FIN + Ping
  26248. masked_frame(0x80, "lo"); // FIN + Continuation
  26249. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26250. for (int i = 0; i < 500 && !done; i++) {
  26251. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26252. }
  26253. ASSERT_TRUE(done);
  26254. EXPECT_EQ("Hello", received);
  26255. // The Ping between the fragments is answered with a Pong.
  26256. char pong[3];
  26257. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26258. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26259. }
  26260. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26261. #ifndef _WIN32
  26262. signal(SIGPIPE, SIG_IGN);
  26263. #endif
  26264. std::atomic<bool> read_ended{false};
  26265. std::atomic<bool> sending{true};
  26266. Server svr;
  26267. svr.set_websocket_ping_interval(0);
  26268. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26269. std::thread reader([&]() {
  26270. std::string msg;
  26271. while (ws.read(msg)) {}
  26272. read_ended = true;
  26273. });
  26274. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26275. ws.close();
  26276. reader.join();
  26277. });
  26278. auto port = svr.bind_to_any_port("127.0.0.1");
  26279. std::thread t([&]() { svr.listen_after_bind(); });
  26280. auto se = detail::scope_exit([&] {
  26281. svr.stop();
  26282. t.join();
  26283. });
  26284. svr.wait_until_ready();
  26285. auto sock = connect_raw_websocket(port, "/ws");
  26286. ASSERT_NE(INVALID_SOCKET, sock);
  26287. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26288. // A Text message whose empty continuation frames never end
  26289. std::thread sender([&]() {
  26290. auto data = masked_frame(0x01, "");
  26291. while (sending) {
  26292. data += masked_frame(0x00, "");
  26293. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26294. return;
  26295. }
  26296. data.clear();
  26297. }
  26298. });
  26299. for (int i = 0; i < 300 && !read_ended; i++) {
  26300. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26301. }
  26302. sending = false;
  26303. sender.join();
  26304. EXPECT_TRUE(read_ended);
  26305. }
  26306. TEST(WebSocketTest, ServerMaxMessageLength) {
  26307. Server svr;
  26308. svr.set_websocket_ping_interval(0);
  26309. svr.set_websocket_max_message_length(100);
  26310. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26311. std::string msg;
  26312. while (ws.read(msg)) {
  26313. ws.send(msg);
  26314. }
  26315. });
  26316. auto port = svr.bind_to_any_port("127.0.0.1");
  26317. std::thread t([&]() { svr.listen_after_bind(); });
  26318. auto se = detail::scope_exit([&] {
  26319. svr.stop();
  26320. t.join();
  26321. });
  26322. svr.wait_until_ready();
  26323. const std::string ping(110, 'p');
  26324. const std::string half(50, 'a');
  26325. const std::string over(60, 'b');
  26326. const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
  26327. // A Ping longer than the limit is answered, since the limit is for
  26328. // messages. A message at the limit is echoed, and one over it is refused
  26329. // although each of its frames is within it.
  26330. EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
  26331. raw_websocket_reply(
  26332. port,
  26333. masked_frame(0x89, ping) + masked_frame(0x01, half) +
  26334. masked_frame(0x80, half) + masked_frame(0x01, over) +
  26335. masked_frame(0x80, over),
  26336. 2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
  26337. // A header that announces more than the limit is refused before its payload
  26338. EXPECT_EQ(too_big, raw_websocket_reply(port,
  26339. std::string("\x82\xfe\x03\xe8", 4) +
  26340. std::string(4, '\0'),
  26341. too_big.size()));
  26342. }
  26343. TEST(WebSocketTest, ClientMaxMessageLength) {
  26344. Server svr;
  26345. svr.set_websocket_ping_interval(0);
  26346. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26347. ws.send(std::string(1024, 'a'));
  26348. ws.send(std::string(2048, 'b'));
  26349. std::string msg;
  26350. while (ws.read(msg)) {}
  26351. });
  26352. auto port = svr.bind_to_any_port(HOST);
  26353. std::thread t([&]() { svr.listen_after_bind(); });
  26354. auto se = detail::scope_exit([&] {
  26355. svr.stop();
  26356. t.join();
  26357. });
  26358. svr.wait_until_ready();
  26359. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26360. client.set_read_timeout(5, 0);
  26361. client.set_websocket_max_message_length(1024);
  26362. ASSERT_TRUE(client.connect());
  26363. std::string msg;
  26364. ASSERT_EQ(ws::Text, client.read(msg));
  26365. EXPECT_EQ(1024u, msg.size());
  26366. EXPECT_EQ(ws::Fail, client.read(msg));
  26367. EXPECT_FALSE(client.is_open());
  26368. // 0 lifts the limit
  26369. client.set_websocket_max_message_length(0);
  26370. ASSERT_TRUE(client.connect());
  26371. EXPECT_EQ(ws::Text, client.read(msg));
  26372. EXPECT_EQ(ws::Text, client.read(msg));
  26373. EXPECT_EQ(2048u, msg.size());
  26374. }
  26375. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26376. Server svr;
  26377. svr.set_websocket_ping_interval(-1);
  26378. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26379. std::string msg;
  26380. while (ws.read(msg)) {}
  26381. });
  26382. auto port = svr.bind_to_any_port("127.0.0.1");
  26383. std::thread t([&]() { svr.listen_after_bind(); });
  26384. auto se = detail::scope_exit([&] {
  26385. svr.stop();
  26386. t.join();
  26387. });
  26388. svr.wait_until_ready();
  26389. auto sock = connect_raw_websocket(port, "/ws");
  26390. ASSERT_NE(INVALID_SOCKET, sock);
  26391. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26392. // Nothing comes while the client stays quiet.
  26393. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26394. char c;
  26395. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26396. }
  26397. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26398. // and that has to end a read() already waiting on the peer, on every platform.
  26399. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26400. // The peer sends no pings, and its handler never calls read(), which is
  26401. // where pongs are written.
  26402. std::mutex mutex;
  26403. std::condition_variable cv;
  26404. auto release = false;
  26405. svr.set_websocket_ping_interval(0);
  26406. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26407. std::unique_lock<std::mutex> lock(mutex);
  26408. cv.wait(lock, [&] { return release; });
  26409. });
  26410. auto port = svr.bind_to_any_port(HOST);
  26411. std::thread t([&]() { svr.listen_after_bind(); });
  26412. auto se = detail::scope_exit([&] {
  26413. {
  26414. std::lock_guard<std::mutex> lock(mutex);
  26415. release = true;
  26416. }
  26417. cv.notify_all();
  26418. svr.stop();
  26419. t.join();
  26420. });
  26421. svr.wait_until_ready();
  26422. ws::WebSocketClient client(std::string(scheme) +
  26423. "://localhost:" + std::to_string(port) + "/ws");
  26424. #ifdef CPPHTTPLIB_SSL_ENABLED
  26425. client.enable_server_certificate_verification(false);
  26426. #endif
  26427. // A ping a second, given up on after two go unanswered: about 3s
  26428. client.set_websocket_ping_interval(1);
  26429. client.set_websocket_max_missed_pongs(2);
  26430. // Well past that, so that a read the timeout ends instead stands out
  26431. client.set_read_timeout(10);
  26432. ASSERT_TRUE(client.connect());
  26433. auto start = std::chrono::steady_clock::now();
  26434. std::string msg;
  26435. EXPECT_EQ(ws::Fail, client.read(msg));
  26436. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26437. std::chrono::steady_clock::now() - start)
  26438. .count(),
  26439. 6000);
  26440. EXPECT_FALSE(client.is_open());
  26441. }
  26442. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26443. Server svr;
  26444. check_pong_timeout_ends_read(svr, "ws");
  26445. }
  26446. #ifdef CPPHTTPLIB_SSL_ENABLED
  26447. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26448. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26449. ASSERT_TRUE(svr.is_valid());
  26450. check_pong_timeout_ends_read(svr, "wss");
  26451. }
  26452. #endif
  26453. // listen() returns only after every handler has, so Server::stop() has to end
  26454. // a WebSocket handler's read() waiting on a client that stays connected and
  26455. // quiet, whether or not the handler bounded its reads, and the client's
  26456. // connection ends with it.
  26457. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26458. bool bounded) {
  26459. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26460. if (bounded) { ws.set_read_timeout(0, 50000); }
  26461. std::string msg;
  26462. while (ws.read(msg) != ws::Fail) {}
  26463. });
  26464. auto port = svr.bind_to_any_port(HOST);
  26465. std::thread t([&]() { svr.listen_after_bind(); });
  26466. auto se = detail::scope_exit([&] {
  26467. if (t.joinable()) {
  26468. svr.stop();
  26469. t.join();
  26470. }
  26471. });
  26472. svr.wait_until_ready();
  26473. ws::WebSocketClient client(std::string(scheme) +
  26474. "://localhost:" + std::to_string(port) + "/ws");
  26475. #ifdef CPPHTTPLIB_SSL_ENABLED
  26476. client.enable_server_certificate_verification(false);
  26477. #endif
  26478. client.set_read_timeout(2);
  26479. ASSERT_TRUE(client.connect());
  26480. auto stopped = std::async(std::launch::async, [&] {
  26481. svr.stop();
  26482. t.join();
  26483. });
  26484. std::string msg;
  26485. EXPECT_EQ(ws::Fail, client.read(msg));
  26486. EXPECT_FALSE(client.is_open());
  26487. auto in_time =
  26488. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26489. // A handler the stop did not reach ends when the client leaves
  26490. if (!in_time) { client.close(); }
  26491. stopped.wait();
  26492. EXPECT_TRUE(in_time);
  26493. }
  26494. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26495. Server svr;
  26496. check_stop_ends_websocket_read(svr, "ws", false);
  26497. }
  26498. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26499. Server svr;
  26500. check_stop_ends_websocket_read(svr, "ws", true);
  26501. }
  26502. #ifdef CPPHTTPLIB_SSL_ENABLED
  26503. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26504. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26505. ASSERT_TRUE(svr.is_valid());
  26506. check_stop_ends_websocket_read(svr, "wss", false);
  26507. }
  26508. #endif
  26509. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26510. // dropped connection, whether the handler waits for a message or for the rest
  26511. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26512. // time out inside the message as well, and the stop ends them too.
  26513. static void check_stop_closes_with_going_away(const std::string &sent,
  26514. bool bounded = false) {
  26515. Server svr;
  26516. svr.set_websocket_ping_interval(0);
  26517. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26518. if (bounded) { ws.set_read_timeout(0, 10000); }
  26519. std::string msg;
  26520. while (ws.read(msg) != ws::Fail) {}
  26521. });
  26522. auto port = svr.bind_to_any_port("127.0.0.1");
  26523. std::thread t([&]() { svr.listen_after_bind(); });
  26524. auto se = detail::scope_exit([&] {
  26525. svr.stop();
  26526. t.join();
  26527. });
  26528. svr.wait_until_ready();
  26529. // Closed before the join above, which a handler the stop did not reach
  26530. // would otherwise hold up.
  26531. auto sock = connect_raw_websocket(port, "/ws");
  26532. ASSERT_NE(INVALID_SOCKET, sock);
  26533. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26534. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26535. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26536. // Let the handler take what was sent and wait for more
  26537. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26538. svr.stop();
  26539. // FIN + Close, its length, then the code: unmasked, from a server
  26540. std::string head;
  26541. char c;
  26542. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26543. head += c;
  26544. }
  26545. const std::string reason = "server stopping";
  26546. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26547. "\x03\xe9",
  26548. head);
  26549. }
  26550. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26551. check_stop_closes_with_going_away("");
  26552. }
  26553. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26554. // A Text frame without FIN: the first fragment of a message
  26555. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26556. }
  26557. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26558. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26559. /*bounded=*/true);
  26560. }
  26561. // A handler that bounds its reads gets control back within its timeout even
  26562. // while a message arrives in pieces, and the message whole once the last has
  26563. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26564. // sent once read() has timed out twice since the one before was sent, so the
  26565. // second timeout came from a read() that had that piece to take.
  26566. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26567. const std::string &expected) {
  26568. std::atomic<bool> done{false};
  26569. std::atomic<int> timeouts{0};
  26570. std::string received;
  26571. Server svr;
  26572. svr.set_websocket_ping_interval(0);
  26573. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26574. ws.set_read_timeout(0, 10000);
  26575. std::string msg;
  26576. ws::ReadResult r;
  26577. while ((r = ws.read(msg)) == ws::Timeout) {
  26578. timeouts++;
  26579. }
  26580. if (r == ws::Text) { received = msg; }
  26581. done = true;
  26582. });
  26583. auto port = svr.bind_to_any_port("127.0.0.1");
  26584. std::thread t([&]() { svr.listen_after_bind(); });
  26585. auto se = detail::scope_exit([&] {
  26586. svr.stop();
  26587. t.join();
  26588. });
  26589. svr.wait_until_ready();
  26590. auto sock = connect_raw_websocket(port, "/ws");
  26591. ASSERT_NE(INVALID_SOCKET, sock);
  26592. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26593. // Each piece goes out at once, not held back by Nagle's algorithm
  26594. ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  26595. for (size_t i = 0; i < pieces.size(); i++) {
  26596. ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
  26597. detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
  26598. if (i + 1 == pieces.size()) { break; }
  26599. auto before = timeouts.load();
  26600. for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
  26601. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26602. }
  26603. ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
  26604. }
  26605. for (int i = 0; i < 5000 && !done; i++) {
  26606. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26607. }
  26608. ASSERT_TRUE(done);
  26609. EXPECT_EQ(expected, received);
  26610. }
  26611. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26612. // The header's first byte, then its second with half the mask key, then
  26613. // the rest: what a frame written in several writes may look like when
  26614. // Nagle's algorithm holds the later ones back for an ACK.
  26615. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26616. check_bounded_read_resumes(
  26617. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26618. }
  26619. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26620. check_bounded_read_resumes(
  26621. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26622. }
  26623. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26624. Server svr;
  26625. svr.set_websocket_ping_interval(0);
  26626. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26627. std::string msg;
  26628. while (ws.read(msg)) {}
  26629. });
  26630. auto port = svr.bind_to_any_port("127.0.0.1");
  26631. std::thread t([&]() { svr.listen_after_bind(); });
  26632. auto se = detail::scope_exit([&] {
  26633. svr.stop();
  26634. t.join();
  26635. });
  26636. svr.wait_until_ready();
  26637. // Each Close payload and the reply it should get: an echo when valid, 1002
  26638. // otherwise.
  26639. std::vector<std::pair<std::string, std::string>> cases = {
  26640. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26641. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26642. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26643. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26644. };
  26645. // Also between the fragments of a message.
  26646. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26647. for (const auto &c : cases) {
  26648. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26649. c.second,
  26650. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26651. 2 + c.second.size()));
  26652. }
  26653. }
  26654. }
  26655. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26656. Server svr;
  26657. svr.set_websocket_ping_interval(0);
  26658. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26659. std::string msg;
  26660. while (ws.read(msg)) {}
  26661. });
  26662. auto port = svr.bind_to_any_port("127.0.0.1");
  26663. std::thread t([&]() { svr.listen_after_bind(); });
  26664. auto se = detail::scope_exit([&] {
  26665. svr.stop();
  26666. t.join();
  26667. });
  26668. svr.wait_until_ready();
  26669. // A header that announces one byte over the limit, and none of its payload
  26670. std::string too_big = "\x82\xff";
  26671. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26672. for (int shift = 56; shift >= 0; shift -= 8) {
  26673. too_big += static_cast<char>((len >> shift) & 0xff);
  26674. }
  26675. too_big.append(4, '\0');
  26676. const std::string protocol_error("\x03\xea"); // 1002
  26677. const std::string too_big_error("\x03\xf1"); // 1009
  26678. // What the client sends and the status the server closes with
  26679. std::vector<std::pair<std::string, std::string>> cases = {
  26680. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26681. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26682. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26683. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26684. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26685. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26686. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26687. protocol_error}, // a new message inside a fragmented one
  26688. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26689. protocol_error}, // 64-bit length with its top bit set
  26690. {too_big, too_big_error},
  26691. };
  26692. for (const auto &c : cases) {
  26693. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26694. raw_websocket_reply(port, c.first, 4));
  26695. }
  26696. }
  26697. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26698. SilentListener listener;
  26699. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26700. // A peer that completes the handshake, then sends a masked frame, which a
  26701. // server must never do, and keeps what the client sends back.
  26702. std::string reply;
  26703. std::thread peer([&]() {
  26704. auto sock = listener.accept();
  26705. if (sock == INVALID_SOCKET) { return; }
  26706. std::string req;
  26707. char c;
  26708. while (req.find("\r\n\r\n") == std::string::npos &&
  26709. ::recv(sock, &c, 1, 0) == 1) {
  26710. req += c;
  26711. }
  26712. const std::string field = "Sec-WebSocket-Key: ";
  26713. auto pos = req.find(field);
  26714. if (pos != std::string::npos) {
  26715. pos += field.size();
  26716. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26717. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26718. "Upgrade: websocket\r\n"
  26719. "Connection: Upgrade\r\n"
  26720. "Sec-WebSocket-Accept: " +
  26721. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26722. masked_frame(0x81, "a");
  26723. detail::send_socket(sock, res.data(), res.size(), 0);
  26724. // FIN + Close, masked with a length of 2, the mask key, the code
  26725. char buf[256];
  26726. while (reply.size() < 8) {
  26727. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26728. if (n <= 0) { break; }
  26729. reply.append(buf, static_cast<size_t>(n));
  26730. }
  26731. }
  26732. detail::close_socket(sock);
  26733. });
  26734. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26735. "/ws");
  26736. auto connected = static_cast<bool>(client.connect());
  26737. std::string msg;
  26738. auto r = connected ? client.read(msg) : ws::Fail;
  26739. peer.join();
  26740. ASSERT_TRUE(connected);
  26741. EXPECT_EQ(ws::Fail, r);
  26742. detail::BufferStream strm;
  26743. strm.write(reply.data(), reply.size());
  26744. ws::Opcode opcode;
  26745. std::string payload;
  26746. bool fin;
  26747. ASSERT_EQ(
  26748. ws::impl::FrameRead::Ok,
  26749. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26750. EXPECT_EQ(ws::Opcode::Close, opcode);
  26751. EXPECT_EQ(std::string("\x03\xea"), payload);
  26752. }
  26753. // What a handler sees of the peer's close once read() has failed
  26754. TEST(WebSocketTest, HandlerSeesThePeersClose) {
  26755. std::mutex m;
  26756. std::condition_variable cv;
  26757. size_t handled = 0;
  26758. uint16_t seen_status = 0;
  26759. std::string seen_reason;
  26760. Server svr;
  26761. svr.set_websocket_ping_interval(0);
  26762. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26763. std::string msg;
  26764. while (ws.read(msg)) {}
  26765. std::lock_guard<std::mutex> lock(m);
  26766. seen_status = static_cast<uint16_t>(ws.close_status());
  26767. seen_reason = ws.close_reason();
  26768. handled++;
  26769. cv.notify_one();
  26770. });
  26771. auto port = svr.bind_to_any_port("127.0.0.1");
  26772. std::thread t([&]() { svr.listen_after_bind(); });
  26773. auto se = detail::scope_exit([&] {
  26774. svr.stop();
  26775. t.join();
  26776. });
  26777. svr.wait_until_ready();
  26778. auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
  26779. const char *label) {
  26780. std::unique_lock<std::mutex> lock(m);
  26781. ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
  26782. return handled == n;
  26783. })) << label;
  26784. EXPECT_EQ(status, seen_status) << label;
  26785. EXPECT_EQ(reason, seen_reason) << label;
  26786. };
  26787. // What a raw client sends before it drops the connection
  26788. struct Case {
  26789. const char *label;
  26790. std::string sent;
  26791. uint16_t status;
  26792. std::string reason;
  26793. };
  26794. std::vector<Case> cases = {
  26795. {"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
  26796. "logout"},
  26797. {"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
  26798. {"no status", masked_frame(0x88, ""), 1005, ""},
  26799. {"malformed", masked_frame(0x88, "\x03"), 1002, ""},
  26800. {"no Close", masked_frame(0x81, "hi"), 1006, ""},
  26801. };
  26802. for (size_t i = 0; i < cases.size(); i++) {
  26803. auto sock = connect_raw_websocket(port, "/ws");
  26804. ASSERT_NE(INVALID_SOCKET, sock);
  26805. detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
  26806. detail::close_socket(sock);
  26807. expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
  26808. }
  26809. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
  26810. ASSERT_TRUE(client.connect());
  26811. client.close(static_cast<ws::CloseStatus>(4001), "logout");
  26812. expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
  26813. }
  26814. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26815. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26816. protected:
  26817. void SetUp() override {
  26818. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26819. SERVER_PRIVATE_KEY_FILE);
  26820. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26821. std::string msg;
  26822. ws::ReadResult ret;
  26823. while ((ret = ws.read(msg))) {
  26824. if (ret == ws::Binary) {
  26825. ws.send(msg.data(), msg.size());
  26826. } else {
  26827. ws.send(msg);
  26828. }
  26829. }
  26830. });
  26831. port_ = server_->bind_to_any_port(HOST);
  26832. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26833. server_->wait_until_ready();
  26834. }
  26835. void TearDown() override {
  26836. server_->stop();
  26837. if (server_thread_.joinable()) { server_thread_.join(); }
  26838. }
  26839. std::unique_ptr<SSLServer> server_;
  26840. std::thread server_thread_;
  26841. int port_ = 0;
  26842. };
  26843. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26844. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26845. {
  26846. ws::WebSocketClient client(url);
  26847. client.enable_server_certificate_verification(false);
  26848. auto calls = 0;
  26849. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26850. calls++;
  26851. return false;
  26852. });
  26853. EXPECT_FALSE(client.connect());
  26854. EXPECT_GT(calls, 0);
  26855. }
  26856. {
  26857. ws::WebSocketClient client(url);
  26858. client.enable_server_certificate_verification(false);
  26859. client.set_session_verifier([](tls::session_t) {
  26860. return SSLVerifierResponse::CertificateRejected;
  26861. });
  26862. EXPECT_FALSE(client.connect());
  26863. }
  26864. {
  26865. ws::WebSocketClient client(url);
  26866. client.enable_server_certificate_verification(false);
  26867. client.set_session_verifier([](tls::session_t) {
  26868. return SSLVerifierResponse::CertificateAccepted;
  26869. });
  26870. EXPECT_TRUE(client.connect());
  26871. }
  26872. }
  26873. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26874. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26875. "/ws-echo");
  26876. client.enable_server_certificate_verification(false);
  26877. ASSERT_TRUE(client.connect());
  26878. ASSERT_TRUE(client.is_open());
  26879. ASSERT_TRUE(client.send("Hello WSS"));
  26880. std::string msg;
  26881. EXPECT_EQ(ws::Text, client.read(msg));
  26882. EXPECT_EQ("Hello WSS", msg);
  26883. client.close();
  26884. }
  26885. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26886. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26887. "/ws-echo");
  26888. client.enable_server_certificate_verification(false);
  26889. EXPECT_TRUE(client.connect());
  26890. }
  26891. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26892. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26893. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26894. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26895. // client (without calling close() first) is the only path that runs
  26896. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26897. // bug exactly.
  26898. //
  26899. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26900. // when linked against an instrumented libssl; run under Valgrind to catch it
  26901. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26902. // suite (the freed session otherwise stalls on the close handshake) — this test
  26903. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26904. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26905. {
  26906. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26907. "/ws-echo");
  26908. client.enable_server_certificate_verification(false);
  26909. client.set_read_timeout(2, 0);
  26910. client.set_write_timeout(2, 0);
  26911. ASSERT_TRUE(client.connect());
  26912. ASSERT_TRUE(client.is_open());
  26913. ASSERT_TRUE(client.send("still open"));
  26914. // Intentionally do NOT call client.close(): leaving scope runs
  26915. // shutdown_and_close() with the WebSocket still open, which must send the
  26916. // close frame while the TLS session is still alive.
  26917. }
  26918. }
  26919. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26920. // shutdown_and_close() at the start of connect(), reproducing the same
  26921. // use-after-free within the test body rather than at scope exit. The second
  26922. // connect must succeed and echo, proving the close handshake ran over a live
  26923. // session. See the note above about memory-tool requirements.
  26924. TEST_F(WebSocketSSLIntegrationTest,
  26925. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26926. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26927. "/ws-echo");
  26928. client.enable_server_certificate_verification(false);
  26929. client.set_read_timeout(2, 0);
  26930. client.set_write_timeout(2, 0);
  26931. ASSERT_TRUE(client.connect());
  26932. ASSERT_TRUE(client.is_open());
  26933. ASSERT_TRUE(client.send("still open"));
  26934. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26935. // the still-open connection, which must not touch a freed TLS session.
  26936. ASSERT_TRUE(client.connect());
  26937. ASSERT_TRUE(client.is_open());
  26938. ASSERT_TRUE(client.send("after reconnect"));
  26939. std::string msg;
  26940. EXPECT_EQ(ws::Text, client.read(msg));
  26941. EXPECT_EQ("after reconnect", msg);
  26942. client.close();
  26943. }
  26944. #endif
  26945. #ifdef CPPHTTPLIB_SSL_ENABLED
  26946. class WebSocketSSLCATest : public ::testing::Test {
  26947. protected:
  26948. void SetUp() override {
  26949. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26950. SERVER_PRIVATE_KEY_FILE);
  26951. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26952. std::string msg;
  26953. while (ws.read(msg)) {
  26954. ws.send(msg);
  26955. }
  26956. });
  26957. port_ = server_->bind_to_any_port("127.0.0.1");
  26958. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26959. server_->wait_until_ready();
  26960. }
  26961. void TearDown() override {
  26962. server_->stop();
  26963. if (server_thread_.joinable()) { server_thread_.join(); }
  26964. }
  26965. std::string url() const {
  26966. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26967. }
  26968. std::unique_ptr<SSLServer> server_;
  26969. std::thread server_thread_;
  26970. int port_ = 0;
  26971. };
  26972. // A custom CA loaded as PEM verifies the server with full certificate
  26973. // verification enabled
  26974. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26975. ws::WebSocketClient client(url());
  26976. std::string cert;
  26977. read_file(SERVER_CERT2_FILE, cert);
  26978. client.load_ca_cert_store(cert.c_str(), cert.size());
  26979. ASSERT_TRUE(client.connect());
  26980. ASSERT_TRUE(client.send("hello"));
  26981. std::string msg;
  26982. EXPECT_EQ(ws::Text, client.read(msg));
  26983. EXPECT_EQ("hello", msg);
  26984. client.close();
  26985. }
  26986. // A custom CA that does not cover the server must fail verification (the
  26987. // custom CA is exclusive; system certs are not loaded alongside it)
  26988. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26989. ws::WebSocketClient client(url());
  26990. std::string cert;
  26991. read_file(CLIENT_CA_CERT_FILE, cert);
  26992. client.load_ca_cert_store(cert.c_str(), cert.size());
  26993. auto res = client.connect();
  26994. ASSERT_FALSE(res);
  26995. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26996. EXPECT_EQ(-1, res.status());
  26997. EXPECT_NE(0u, res.ssl_backend_error());
  26998. }
  26999. // The same CA as a file path rather than PEM in memory
  27000. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  27001. ws::WebSocketClient client(url());
  27002. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27003. ASSERT_TRUE(client.connect());
  27004. ASSERT_TRUE(client.send("hello"));
  27005. std::string msg;
  27006. EXPECT_EQ(ws::Text, client.read(msg));
  27007. EXPECT_EQ("hello", msg);
  27008. client.close();
  27009. }
  27010. // ...and a CA file that does not cover the server still fails, so it is the
  27011. // path above that decides the outcome
  27012. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  27013. ws::WebSocketClient client(url());
  27014. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27015. ASSERT_FALSE(client.connect());
  27016. }
  27017. // Regression test: reconnecting with a native custom CA store used to reuse
  27018. // a store handle the previous TLS context had already freed (use-after-free
  27019. // under the OpenSSL backend). The context now lives as long as the client.
  27020. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  27021. ws::WebSocketClient client(url());
  27022. std::string cert;
  27023. read_file(SERVER_CERT2_FILE, cert);
  27024. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  27025. ASSERT_TRUE(client.connect());
  27026. client.close();
  27027. ASSERT_TRUE(client.connect());
  27028. ASSERT_TRUE(client.send("again"));
  27029. std::string msg;
  27030. EXPECT_EQ(ws::Text, client.read(msg));
  27031. EXPECT_EQ("again", msg);
  27032. client.close();
  27033. }
  27034. // Regression test: a certificate with a trusted chain but no identity match
  27035. // for the server IP must be rejected. The Mbed TLS backend used to skip
  27036. // verification entirely for IP hosts, so this connection succeeded there.
  27037. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  27038. // chain verification while the identity check must still fail.
  27039. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  27040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  27041. ASSERT_TRUE(svr.is_valid());
  27042. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27043. std::string msg;
  27044. while (ws.read(msg)) {
  27045. ws.send(msg);
  27046. }
  27047. });
  27048. auto port = svr.bind_to_any_port("127.0.0.1");
  27049. auto t = std::thread([&]() { svr.listen_after_bind(); });
  27050. auto se = detail::scope_exit([&] {
  27051. svr.stop();
  27052. t.join();
  27053. });
  27054. svr.wait_until_ready();
  27055. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  27056. "/echo");
  27057. std::string cert;
  27058. read_file(SERVER_CERT_FILE, cert);
  27059. client.load_ca_cert_store(cert.c_str(), cert.size());
  27060. ASSERT_FALSE(client.connect());
  27061. }
  27062. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  27063. // SNI, so nothing binds the host name to the TLS session. These bind the
  27064. // server to "localhost" instead, the only shape that exercises the SNI and
  27065. // hostname-verification path with certificate verification left enabled.
  27066. class WebSocketSSLDnsHostTest : public ::testing::Test {
  27067. protected:
  27068. void Start(const char *cert_file) {
  27069. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  27070. SERVER_PRIVATE_KEY_FILE);
  27071. ASSERT_TRUE(server_->is_valid());
  27072. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27073. std::string msg;
  27074. while (ws.read(msg)) {
  27075. ws.send(msg);
  27076. }
  27077. });
  27078. port_ = server_->bind_to_any_port("localhost");
  27079. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27080. server_->wait_until_ready();
  27081. }
  27082. void TearDown() override {
  27083. if (server_) { server_->stop(); }
  27084. if (server_thread_.joinable()) { server_thread_.join(); }
  27085. }
  27086. std::string url() const {
  27087. return "wss://localhost:" + std::to_string(port_) + "/echo";
  27088. }
  27089. std::unique_ptr<SSLServer> server_;
  27090. std::thread server_thread_;
  27091. int port_ = 0;
  27092. };
  27093. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  27094. // out and the connection is usable
  27095. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  27096. Start(SERVER_CERT2_FILE);
  27097. ws::WebSocketClient client(url());
  27098. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27099. ASSERT_TRUE(client.connect());
  27100. ASSERT_TRUE(client.send("hello"));
  27101. std::string msg;
  27102. EXPECT_EQ(ws::Text, client.read(msg));
  27103. EXPECT_EQ("hello", msg);
  27104. client.close();
  27105. }
  27106. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  27107. // while the identity check must still reject "localhost"
  27108. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  27109. Start(SERVER_CERT_FILE);
  27110. ws::WebSocketClient client(url());
  27111. client.set_ca_cert_path(SERVER_CERT_FILE);
  27112. auto res = client.connect();
  27113. ASSERT_FALSE(res);
  27114. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  27115. EXPECT_EQ(-1, res.status());
  27116. }
  27117. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  27118. // disabled: the chain is still checked, only the identity check is skipped
  27119. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  27120. Start(SERVER_CERT_FILE);
  27121. ws::WebSocketClient client(url());
  27122. client.set_ca_cert_path(SERVER_CERT_FILE);
  27123. client.enable_server_hostname_verification(false);
  27124. ASSERT_TRUE(client.connect());
  27125. ASSERT_TRUE(client.send("hello"));
  27126. std::string msg;
  27127. EXPECT_EQ(ws::Text, client.read(msg));
  27128. EXPECT_EQ("hello", msg);
  27129. client.close();
  27130. }
  27131. // A CA that did not sign the server certificate fails the chain, even though
  27132. // the name would match
  27133. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  27134. Start(SERVER_CERT2_FILE);
  27135. ws::WebSocketClient client(url());
  27136. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27137. ASSERT_FALSE(client.connect());
  27138. }
  27139. // With verification disabled, neither the chain nor the name is checked
  27140. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  27141. Start(SERVER_CERT_FILE);
  27142. ws::WebSocketClient client(url());
  27143. client.enable_server_certificate_verification(false);
  27144. ASSERT_TRUE(client.connect());
  27145. ASSERT_TRUE(client.send("hello"));
  27146. std::string msg;
  27147. EXPECT_EQ(ws::Text, client.read(msg));
  27148. EXPECT_EQ("hello", msg);
  27149. client.close();
  27150. }
  27151. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  27152. protected:
  27153. void SetUp() override {
  27154. server_ = httplib::detail::make_unique<SSLServer>(
  27155. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  27156. ASSERT_TRUE(server_->is_valid());
  27157. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27158. std::string msg;
  27159. while (ws.read(msg)) {
  27160. ws.send(msg);
  27161. }
  27162. });
  27163. port_ = server_->bind_to_any_port("localhost");
  27164. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27165. server_->wait_until_ready();
  27166. }
  27167. void TearDown() override {
  27168. server_->stop();
  27169. if (server_thread_.joinable()) { server_thread_.join(); }
  27170. }
  27171. std::string url() const {
  27172. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27173. }
  27174. void ConnectWithClientCert(const std::string &client_cert_file,
  27175. const std::string &client_private_key_file,
  27176. const char *private_key_password) {
  27177. std::string cert_pem, key_pem;
  27178. read_file(client_cert_file, cert_pem);
  27179. read_file(client_private_key_file, key_pem);
  27180. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27181. key_pem.c_str(), key_pem.size(),
  27182. private_key_password};
  27183. ConnectWithPem(pem);
  27184. }
  27185. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27186. ws::WebSocketClient client(url(), pem);
  27187. ASSERT_TRUE(client.is_valid());
  27188. client.enable_server_certificate_verification(false);
  27189. ASSERT_TRUE(client.connect());
  27190. ASSERT_TRUE(client.send("hello"));
  27191. std::string msg;
  27192. EXPECT_EQ(ws::Text, client.read(msg));
  27193. EXPECT_EQ("hello", msg);
  27194. client.close();
  27195. }
  27196. std::unique_ptr<SSLServer> server_;
  27197. std::thread server_thread_;
  27198. int port_ = 0;
  27199. };
  27200. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27201. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27202. }
  27203. // Control for the tests above: the fixture's server really does require a
  27204. // client certificate, so it is the PEM the constructor installed that decides
  27205. // the outcome.
  27206. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27207. ws::WebSocketClient client(url());
  27208. ASSERT_TRUE(client.is_valid());
  27209. client.enable_server_certificate_verification(false);
  27210. EXPECT_FALSE(client.connect());
  27211. }
  27212. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27213. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27214. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27215. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27216. }
  27217. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27218. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27219. std::string cert_pem, key_pem;
  27220. read_file(CLIENT_CERT_FILE, cert_pem);
  27221. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27222. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27223. std::vector<char> key(key_pem.begin(), key_pem.end());
  27224. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27225. key.size(), nullptr};
  27226. ConnectWithPem(pem);
  27227. }
  27228. #endif
  27229. #if !defined(_WIN32)
  27230. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27231. auto secret_dir = std::string("./symlink_test_secret");
  27232. auto served_dir = std::string("./symlink_test_served");
  27233. auto secret_file = secret_dir + "/secret.txt";
  27234. auto symlink_path = served_dir + "/escape";
  27235. // Setup: create directories and files
  27236. mkdir(secret_dir.c_str(), 0755);
  27237. mkdir(served_dir.c_str(), 0755);
  27238. {
  27239. std::ofstream ofs(secret_file);
  27240. ofs << "SECRET_DATA";
  27241. }
  27242. // Create symlink using absolute path so it resolves correctly
  27243. #ifdef PATH_MAX
  27244. char abs_secret[PATH_MAX];
  27245. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27246. #else
  27247. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27248. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27249. ASSERT_NE(nullptr, abs_secret);
  27250. #endif
  27251. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27252. auto se = detail::scope_exit([&] {
  27253. unlink(symlink_path.c_str());
  27254. unlink(secret_file.c_str());
  27255. rmdir(served_dir.c_str());
  27256. rmdir(secret_dir.c_str());
  27257. });
  27258. Server svr;
  27259. svr.set_mount_point("/", served_dir);
  27260. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27261. auto se2 = detail::scope_exit([&] {
  27262. svr.stop();
  27263. listen_thread.join();
  27264. });
  27265. svr.wait_until_ready();
  27266. Client cli("localhost", PORT);
  27267. // Symlink pointing outside base dir should be blocked
  27268. auto res = cli.Get("/escape/secret.txt");
  27269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27270. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27271. }
  27272. #else
  27273. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27274. auto secret_dir = std::string("junction_test_secret");
  27275. auto served_dir = std::string("junction_test_served");
  27276. auto secret_file = secret_dir + "\\secret.txt";
  27277. auto junction_path = served_dir + "\\escape";
  27278. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27279. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27280. {
  27281. std::ofstream ofs(secret_file);
  27282. ofs << "SECRET_DATA";
  27283. }
  27284. // A junction needs no privilege to create, unlike a symlink
  27285. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27286. ASSERT_EQ(0, std::system(cmd.c_str()));
  27287. auto se = detail::scope_exit([&] {
  27288. ::RemoveDirectoryA(junction_path.c_str());
  27289. std::remove(secret_file.c_str());
  27290. ::RemoveDirectoryA(served_dir.c_str());
  27291. ::RemoveDirectoryA(secret_dir.c_str());
  27292. });
  27293. Server svr;
  27294. svr.set_mount_point("/", served_dir);
  27295. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27296. auto se2 = detail::scope_exit([&] {
  27297. svr.stop();
  27298. listen_thread.join();
  27299. });
  27300. svr.wait_until_ready();
  27301. Client cli("localhost", PORT);
  27302. // Junction pointing outside base dir should be blocked
  27303. auto res = cli.Get("/escape/secret.txt");
  27304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27305. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27306. }
  27307. #endif
  27308. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27309. // "GET /smuggled" request), reads the first response, and only then sends the
  27310. // embedded request as the body. Returns how many times /smuggled ran.
  27311. //
  27312. // The body is sent AFTER receiving the first response (as in the original
  27313. // PoC) so that the stream_line_reader cannot buffer it together with the
  27314. // headers of the first request.
  27315. static int count_smuggled_requests(const std::string &outer_head,
  27316. std::string &first_response) {
  27317. Server svr;
  27318. svr.set_mount_point("/", "./www");
  27319. std::atomic<int> smuggled_count(0);
  27320. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27321. smuggled_count++;
  27322. res.set_content("oops", "text/plain");
  27323. });
  27324. svr.Post("/post", [&](const Request &req, Response &res) {
  27325. res.set_content(req.body, "text/plain");
  27326. });
  27327. auto port = svr.bind_to_any_port("localhost");
  27328. thread t = thread([&] { svr.listen_after_bind(); });
  27329. auto se = detail::scope_exit([&] {
  27330. svr.stop();
  27331. t.join();
  27332. });
  27333. svr.wait_until_ready();
  27334. auto error = Error::Success;
  27335. auto sock = detail::create_client_socket(
  27336. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27337. /*connection_timeout_sec=*/2, 0,
  27338. /*read_timeout_sec=*/2, 0,
  27339. /*write_timeout_sec=*/2, 0, std::string(), error);
  27340. EXPECT_NE(INVALID_SOCKET, sock);
  27341. if (sock == INVALID_SOCKET) { return -1; }
  27342. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27343. // The "smuggled" request will be sent as the body of the outer request
  27344. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27345. "Host: localhost\r\n"
  27346. "Connection: close\r\n"
  27347. "\r\n";
  27348. auto head = outer_head;
  27349. auto len = std::to_string(smuggled.size());
  27350. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27351. pos = head.find("{len}", pos + len.size())) {
  27352. head.replace(pos, 5, len);
  27353. }
  27354. // Step 1: Send only the outer request headers (no body yet)
  27355. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27356. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27357. // Step 2: Read the first response
  27358. char buf[4096];
  27359. for (;;) {
  27360. auto n = recv(sock, buf, sizeof(buf), 0);
  27361. if (n <= 0) break;
  27362. first_response.append(buf, static_cast<size_t>(n));
  27363. // Stop once we have a complete response (headers + body)
  27364. auto hdr_end = first_response.find("\r\n\r\n");
  27365. if (hdr_end != std::string::npos) {
  27366. // Check for Content-Length to know when the body is complete
  27367. auto cl_pos = first_response.find("Content-Length:");
  27368. if (cl_pos != std::string::npos) {
  27369. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27370. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27371. auto cl = std::stoul(
  27372. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27373. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27374. } else {
  27375. break; // No Content-Length, assume headers-only response
  27376. }
  27377. }
  27378. }
  27379. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27380. // vulnerable server the keep-alive loop reads this as a second request. The
  27381. // server may already have closed the connection, so the result is ignored.
  27382. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27383. // Half-close so that a server which drained the body sees EOF and closes,
  27384. // instead of the read below waiting for the read timeout.
  27385. #ifdef _WIN32
  27386. ::shutdown(sock, SD_SEND);
  27387. #else
  27388. ::shutdown(sock, SHUT_WR);
  27389. #endif
  27390. // Step 4: Read until the server closes the connection
  27391. for (;;) {
  27392. auto n = recv(sock, buf, sizeof(buf), 0);
  27393. if (n <= 0) break;
  27394. }
  27395. return smuggled_count.load();
  27396. }
  27397. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27398. // A GET request with Content-Length to a static file handler must have its
  27399. // body drained before the keep-alive connection is reused. Otherwise the
  27400. // unread body bytes are interpreted as the next HTTP request.
  27401. std::string first_response;
  27402. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27403. "Host: localhost\r\n"
  27404. "Content-Length: {len}\r\n"
  27405. "\r\n",
  27406. first_response));
  27407. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27408. }
  27409. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27410. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27411. // be answered with 400 and the connection closed. Treating it as "no body"
  27412. // leaves the body to be parsed as the next request.
  27413. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27414. const char *targets[] = {
  27415. "GET /file", // handler that never reads the body
  27416. "GET /not-found", // no handler matches (404)
  27417. "POST /post", // handler that reads the body
  27418. };
  27419. for (auto target : targets) {
  27420. for (auto value : values) {
  27421. std::string first_response;
  27422. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27423. " HTTP/1.1\r\n"
  27424. "Host: localhost\r\n"
  27425. "Content-Length: " +
  27426. value + "\r\n\r\n",
  27427. first_response))
  27428. << target << " with Content-Length: " << value;
  27429. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27430. << target << " with Content-Length: " << value;
  27431. }
  27432. }
  27433. }
  27434. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27435. // A 400 for an unparseable request line leaves the rest of the message
  27436. // unread, so the connection must be closed rather than reused.
  27437. std::string first_response;
  27438. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27439. "Host: localhost\r\n"
  27440. "Content-Length: {len}\r\n"
  27441. "\r\n",
  27442. first_response));
  27443. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27444. }
  27445. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27446. // Same as above for a header block that fails to parse.
  27447. std::string first_response;
  27448. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27449. "Host: localhost\r\n"
  27450. "Bad Header\r\n"
  27451. "Content-Length: {len}\r\n"
  27452. "\r\n",
  27453. first_response));
  27454. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27455. }
  27456. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27457. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27458. // server must not read another request on that connection, even when the
  27459. // request had no body to drain.
  27460. std::string first_response;
  27461. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27462. "Host: localhost\r\n"
  27463. "\r\n",
  27464. first_response));
  27465. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27466. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27467. }
  27468. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27469. // A content reader that stops early leaves the stream inside the body.
  27470. // Draining the whole Content-Length from there, or reading the body again,
  27471. // reads into the next request, and whatever follows is parsed as a request
  27472. // of its own.
  27473. Server svr;
  27474. std::atomic<int> smuggled_count(0);
  27475. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27476. svr.Post("/upload", [](const Request &req, Response &res,
  27477. const ContentReader &content_reader) {
  27478. // Stop at the last chunk, so the whole body has been read however it
  27479. // arrives.
  27480. auto length = req.get_header_value_u64("Content-Length");
  27481. size_t total = 0;
  27482. auto consumed = content_reader([&](const char *, size_t n) {
  27483. total += n;
  27484. return total < length;
  27485. });
  27486. EXPECT_FALSE(consumed);
  27487. if (req.has_param("retry")) {
  27488. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27489. }
  27490. // Replace the 400 the aborted read set, which would close the connection.
  27491. res.set_redirect("/done");
  27492. });
  27493. auto port = svr.bind_to_any_port(HOST);
  27494. thread t = thread([&] { svr.listen_after_bind(); });
  27495. auto se = detail::scope_exit([&] {
  27496. svr.stop();
  27497. t.join();
  27498. });
  27499. svr.wait_until_ready();
  27500. // A front end sees the second request as a POST whose body is the GET. The
  27501. // first body is as long as the POST's headers, so draining it again reads
  27502. // exactly those and leaves the GET to be parsed next.
  27503. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27504. "Host: localhost\r\n"
  27505. "\r\n";
  27506. std::string second_head = "POST /post HTTP/1.1\r\n"
  27507. "Host: localhost\r\n"
  27508. "Content-Length: " +
  27509. std::to_string(inner.size()) +
  27510. "\r\n"
  27511. "\r\n";
  27512. for (auto target : {"/upload", "/upload?retry"}) {
  27513. smuggled_count = 0;
  27514. std::string request = "POST " + std::string(target) +
  27515. " HTTP/1.1\r\n"
  27516. "Host: localhost\r\n"
  27517. "Content-Length: " +
  27518. std::to_string(second_head.size()) +
  27519. "\r\n"
  27520. "\r\n" +
  27521. std::string(second_head.size(), 'A') + second_head +
  27522. inner;
  27523. std::string response;
  27524. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27525. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27526. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27527. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27528. EXPECT_EQ(0, smuggled_count.load()) << target;
  27529. }
  27530. }
  27531. // An error response closes the connection anyway, so the body is left unread
  27532. // with a redirect, such as one to a login page.
  27533. static void serve_redirects(Server &svr,
  27534. const std::function<void(int)> &client) {
  27535. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27536. res.set_redirect("/login");
  27537. return Server::HandlerResponse::Handled;
  27538. });
  27539. auto port = svr.bind_to_any_port(HOST);
  27540. ASSERT_GT(port, 0);
  27541. thread t = thread([&] { svr.listen_after_bind(); });
  27542. auto se = detail::scope_exit([&] {
  27543. svr.stop();
  27544. t.join();
  27545. ASSERT_FALSE(svr.is_running());
  27546. });
  27547. svr.wait_until_ready();
  27548. client(port);
  27549. }
  27550. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27551. Server svr;
  27552. serve_redirects(svr, [](int port) {
  27553. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27554. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27555. std::to_string(body.size()) + "\r\n\r\n" + body +
  27556. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27557. std::string resp;
  27558. ASSERT_TRUE(send_request(1, req, &resp, port));
  27559. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27560. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27561. });
  27562. }
  27563. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27564. Server svr;
  27565. svr.set_read_timeout(0, 200000);
  27566. serve_redirects(svr, [](int port) {
  27567. // A byte every 100 ms keeps each read within the read timeout, but not the
  27568. // body as a whole, so the server closes and the bytes sent after that fail.
  27569. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27570. "Content-Length: 10\r\n\r\n"};
  27571. parts.resize(11, "x");
  27572. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27573. });
  27574. }
  27575. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27576. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27577. // must be rejected with 400 Bad Request.
  27578. Server svr;
  27579. svr.Post("/test", [&](const Request &, Response &res) {
  27580. res.set_content("ok", "text/plain");
  27581. });
  27582. thread t = thread([&] { svr.listen(HOST, PORT); });
  27583. auto se = detail::scope_exit([&] {
  27584. svr.stop();
  27585. t.join();
  27586. ASSERT_FALSE(svr.is_running());
  27587. });
  27588. svr.wait_until_ready();
  27589. // Exact "chunked"
  27590. {
  27591. auto req = "POST /test HTTP/1.1\r\n"
  27592. "Host: localhost\r\n"
  27593. "Content-Length: 5\r\n"
  27594. "Transfer-Encoding: chunked\r\n"
  27595. "Connection: close\r\n"
  27596. "\r\n"
  27597. "hello";
  27598. std::string response;
  27599. ASSERT_TRUE(send_request(1, req, &response));
  27600. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27601. response.substr(0, response.find("\r\n")));
  27602. }
  27603. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27604. {
  27605. auto req = "POST /test HTTP/1.1\r\n"
  27606. "Host: localhost\r\n"
  27607. "Content-Length: 5\r\n"
  27608. "Transfer-Encoding: gzip, chunked\r\n"
  27609. "Connection: close\r\n"
  27610. "\r\n"
  27611. "hello";
  27612. std::string response;
  27613. ASSERT_TRUE(send_request(1, req, &response));
  27614. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27615. response.substr(0, response.find("\r\n")));
  27616. }
  27617. }
  27618. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27619. Server svr;
  27620. svr.Post("/test", [&](const Request &, Response &res) {
  27621. res.set_content("ok", "text/plain");
  27622. });
  27623. thread t = thread([&] { svr.listen(HOST, PORT); });
  27624. auto se = detail::scope_exit([&] {
  27625. svr.stop();
  27626. t.join();
  27627. ASSERT_FALSE(svr.is_running());
  27628. });
  27629. svr.wait_until_ready();
  27630. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27631. // length cannot be determined, so the server must answer 400 and close
  27632. // rather than treat the request as bodyless and leave the body in the
  27633. // socket for the next request to pick up.
  27634. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27635. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27636. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27637. std::string response;
  27638. ASSERT_TRUE(send_request(1, req, &response));
  27639. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27640. response.substr(0, response.find("\r\n")))
  27641. << transfer_encoding;
  27642. }
  27643. // RFC 9110 5.3: the codings may also be split across several
  27644. // Transfer-Encoding lines, which combine in the order they were received.
  27645. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27646. // just like the single-line "chunked, gzip" above.
  27647. {
  27648. auto req = "POST /test HTTP/1.1\r\n"
  27649. "Host: localhost\r\n"
  27650. "Transfer-Encoding: chunked\r\n"
  27651. "Transfer-Encoding: gzip\r\n"
  27652. "\r\n"
  27653. "0\r\n\r\n";
  27654. std::string response;
  27655. ASSERT_TRUE(send_request(1, req, &response));
  27656. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27657. response.substr(0, response.find("\r\n")));
  27658. }
  27659. }
  27660. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27661. Server svr;
  27662. svr.Post("/test", [&](const Request &, Response &res) {
  27663. res.set_content("ok", "text/plain");
  27664. });
  27665. auto port = svr.bind_to_any_port(HOST);
  27666. ASSERT_GT(port, 0);
  27667. thread t = thread([&] { svr.listen_after_bind(); });
  27668. auto se = detail::scope_exit([&] {
  27669. svr.stop();
  27670. t.join();
  27671. ASSERT_FALSE(svr.is_running());
  27672. });
  27673. svr.wait_until_ready();
  27674. for (auto transfer_encoding :
  27675. {"Transfer-Encoding: gzip, chunked\r\n",
  27676. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27677. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27678. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27679. transfer_encoding + "\r\n0\r\n\r\n";
  27680. std::string response;
  27681. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27682. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27683. response.substr(0, response.find("\r\n")))
  27684. << transfer_encoding;
  27685. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27686. << transfer_encoding;
  27687. }
  27688. }
  27689. // Regression for issue #2450: a DELETE without Content-Length on a
  27690. // keep-alive connection must not let the post-response drain consume the
  27691. // next request's bytes.
  27692. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27693. Server svr;
  27694. std::atomic<int> delete_count(0);
  27695. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27696. delete_count++;
  27697. res.status = StatusCode::NoContent_204;
  27698. });
  27699. auto port = svr.bind_to_any_port(HOST);
  27700. thread t = thread([&] { svr.listen_after_bind(); });
  27701. auto se = detail::scope_exit([&] {
  27702. svr.stop();
  27703. t.join();
  27704. });
  27705. svr.wait_until_ready();
  27706. auto error = Error::Success;
  27707. auto sock = detail::create_client_socket(
  27708. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27709. /*connection_timeout_sec=*/2, 0,
  27710. /*read_timeout_sec=*/2, 0,
  27711. /*write_timeout_sec=*/2, 0, std::string(), error);
  27712. ASSERT_NE(INVALID_SOCKET, sock);
  27713. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27714. auto send_request_and_read_response = [&](const std::string &req,
  27715. std::string &out) -> bool {
  27716. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27717. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27718. char buf[4096];
  27719. for (;;) {
  27720. auto n = recv(sock, buf, sizeof(buf), 0);
  27721. if (n <= 0) { return !out.empty(); }
  27722. out.append(buf, static_cast<size_t>(n));
  27723. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27724. }
  27725. };
  27726. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27727. "Host: localhost\r\n"
  27728. "\r\n";
  27729. std::string resp1;
  27730. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27731. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27732. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27733. "Host: localhost\r\n"
  27734. "Connection: close\r\n"
  27735. "\r\n";
  27736. std::string resp2;
  27737. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27738. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27739. EXPECT_EQ(2, delete_count.load());
  27740. }
  27741. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27742. Server svr;
  27743. svr.Post("/ingest", [&](const Request &, Response &res,
  27744. const ContentReader &content_reader) {
  27745. auto consumed = content_reader([](const char *, size_t) { return false; });
  27746. EXPECT_FALSE(consumed);
  27747. res.status = StatusCode::Conflict_409;
  27748. res.set_header("Connection", "close");
  27749. });
  27750. auto port = svr.bind_to_any_port(HOST);
  27751. thread t = thread([&] { svr.listen_after_bind(); });
  27752. auto se = detail::scope_exit([&] {
  27753. svr.stop();
  27754. t.join();
  27755. });
  27756. svr.wait_until_ready();
  27757. auto error = Error::Success;
  27758. auto sock = detail::create_client_socket(
  27759. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27760. /*connection_timeout_sec=*/2, 0,
  27761. /*read_timeout_sec=*/1, 0,
  27762. /*write_timeout_sec=*/2, 0, std::string(), error);
  27763. ASSERT_NE(INVALID_SOCKET, sock);
  27764. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27765. std::string request = "POST /ingest HTTP/1.1\r\n"
  27766. "Host: localhost\r\n"
  27767. "Transfer-Encoding: chunked\r\n"
  27768. "\r\n"
  27769. "4\r\n"
  27770. "data\r\n";
  27771. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27772. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27773. std::string response;
  27774. ssize_t received = 0;
  27775. do {
  27776. char buf[4096];
  27777. received = recv(sock, buf, sizeof(buf), 0);
  27778. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27779. } while (received > 0);
  27780. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27781. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27782. EXPECT_EQ(0, received);
  27783. }
  27784. namespace no_proxy_test {
  27785. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27786. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27787. // calling listen().
  27788. class ScopedServer {
  27789. public:
  27790. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27791. ~ScopedServer() {
  27792. svr_.stop();
  27793. if (th_.joinable()) { th_.join(); }
  27794. }
  27795. Server &svr() { return svr_; }
  27796. int port() const { return port_; }
  27797. void listen() {
  27798. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27799. svr_.wait_until_ready();
  27800. }
  27801. private:
  27802. Server svr_;
  27803. std::thread th_;
  27804. int port_ = 0;
  27805. };
  27806. class ProxyAndTargetServers {
  27807. public:
  27808. ProxyAndTargetServers() {
  27809. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27810. proxy_hits_++;
  27811. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27812. res.set_content("via-proxy", "text/plain");
  27813. });
  27814. target_.Get(".*", [this](const Request &req, Response &res) {
  27815. target_hits_++;
  27816. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27817. res.set_content("direct", "text/plain");
  27818. });
  27819. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27820. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27821. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27822. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27823. proxy_mock_.wait_until_ready();
  27824. target_.wait_until_ready();
  27825. }
  27826. ~ProxyAndTargetServers() {
  27827. proxy_mock_.stop();
  27828. target_.stop();
  27829. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27830. if (target_thread_.joinable()) { target_thread_.join(); }
  27831. }
  27832. Server &proxy_mock() { return proxy_mock_; }
  27833. Server &target() { return target_; }
  27834. int proxy_port() const { return proxy_port_; }
  27835. int target_port() const { return target_port_; }
  27836. int proxy_hits() const { return proxy_hits_.load(); }
  27837. int target_hits() const { return target_hits_.load(); }
  27838. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27839. void reset_counters() {
  27840. proxy_hits_ = 0;
  27841. target_hits_ = 0;
  27842. last_had_proxy_authz_ = false;
  27843. }
  27844. private:
  27845. Server proxy_mock_;
  27846. Server target_;
  27847. std::thread proxy_thread_;
  27848. std::thread target_thread_;
  27849. int proxy_port_ = 0;
  27850. int target_port_ = 0;
  27851. std::atomic<int> proxy_hits_{0};
  27852. std::atomic<int> target_hits_{0};
  27853. std::atomic<bool> last_had_proxy_authz_{false};
  27854. };
  27855. inline std::unique_ptr<Client> make_client(const std::string &host,
  27856. ProxyAndTargetServers &s) {
  27857. auto cli = detail::make_unique<Client>(host, s.target_port());
  27858. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27859. cli->set_proxy("127.0.0.1", s.proxy_port());
  27860. return cli;
  27861. }
  27862. } // namespace no_proxy_test
  27863. using no_proxy_test::make_client;
  27864. using no_proxy_test::ProxyAndTargetServers;
  27865. // A stream request carries the credentials a buffered request does
  27866. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27867. no_proxy_test::ScopedServer origin;
  27868. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27869. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27870. });
  27871. origin.listen();
  27872. Client cli("127.0.0.1", origin.port());
  27873. cli.set_basic_auth("user", "pass");
  27874. auto handle = cli.open_stream("GET", "/x");
  27875. ASSERT_TRUE(handle.is_valid());
  27876. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27877. Client bearer("127.0.0.1", origin.port());
  27878. bearer.set_bearer_token_auth("tok");
  27879. auto handle2 = bearer.open_stream("GET", "/x");
  27880. ASSERT_TRUE(handle2.is_valid());
  27881. EXPECT_EQ("Bearer tok", read_all(handle2));
  27882. }
  27883. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27884. // takes its own credentials, as for a buffered request
  27885. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27886. std::string target, authz, proxy_authz;
  27887. no_proxy_test::ScopedServer proxy;
  27888. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27889. target = req.target;
  27890. authz = req.get_header_value("Authorization");
  27891. proxy_authz = req.get_header_value("Proxy-Authorization");
  27892. res.set_content("ok", "text/plain");
  27893. });
  27894. proxy.listen();
  27895. Client cli("origin.example", 8080);
  27896. cli.set_proxy("127.0.0.1", proxy.port());
  27897. cli.set_proxy_basic_auth("puser", "ppass");
  27898. cli.set_basic_auth("user", "pass");
  27899. auto handle = cli.open_stream("GET", "/x");
  27900. ASSERT_TRUE(handle.is_valid());
  27901. EXPECT_EQ("ok", read_all(handle));
  27902. EXPECT_EQ("http://origin.example:8080/x", target);
  27903. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27904. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27905. }
  27906. // In absolute-form the path follows the authority, so a path that does not
  27907. // begin with '/' would make the proxy connect to another host
  27908. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27909. std::vector<std::string> targets;
  27910. no_proxy_test::ScopedServer proxy;
  27911. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27912. targets.push_back(req.target);
  27913. res.set_content("ok", "text/plain");
  27914. });
  27915. proxy.listen();
  27916. Client cli("origin.example", 8080);
  27917. cli.set_proxy("127.0.0.1", proxy.port());
  27918. cli.set_basic_auth("user", "pass");
  27919. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27920. auto res = cli.Get(path);
  27921. EXPECT_FALSE(res) << path;
  27922. auto handle = cli.open_stream("GET", path);
  27923. EXPECT_FALSE(handle.is_valid()) << path;
  27924. }
  27925. EXPECT_TRUE(targets.empty());
  27926. auto res = cli.Get("/x");
  27927. ASSERT_TRUE(res);
  27928. ASSERT_EQ(1u, targets.size());
  27929. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27930. }
  27931. TEST(NoProxyTest, ExactHostnameBypasses) {
  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, SubdomainBypasses) {
  27941. ProxyAndTargetServers s;
  27942. auto cli = make_client("foo.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, EvilExampleDoesNotMatchExample) {
  27950. // Regression guard: "evilexample.com" must not be considered a subdomain
  27951. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27952. // check would let traffic bypass the proxy and leak credentials direct
  27953. // to the attacker host.
  27954. ProxyAndTargetServers s;
  27955. auto cli = make_client("evilexample.com", s);
  27956. cli->set_no_proxy({"example.com"});
  27957. auto res = cli->Get("/");
  27958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27959. EXPECT_GE(s.proxy_hits(), 1);
  27960. EXPECT_EQ(0, s.target_hits());
  27961. }
  27962. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27963. ProxyAndTargetServers s;
  27964. auto cli = make_client("example.com.evil.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_GE(s.proxy_hits(), 1);
  27969. EXPECT_EQ(0, s.target_hits());
  27970. }
  27971. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27972. ProxyAndTargetServers s;
  27973. auto cli = make_client("example.com", s);
  27974. cli->set_no_proxy({".example.com"});
  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, CaseInsensitiveHostname) {
  27981. ProxyAndTargetServers s;
  27982. auto cli = make_client("Example.COM", s);
  27983. cli->set_no_proxy({"EXAMPLE.com"});
  27984. auto res = cli->Get("/");
  27985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27986. EXPECT_EQ(0, s.proxy_hits());
  27987. EXPECT_EQ(1, s.target_hits());
  27988. }
  27989. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27990. ProxyAndTargetServers s;
  27991. auto cli = make_client("example.com.", s);
  27992. cli->set_no_proxy({"example.com"});
  27993. auto res = cli->Get("/");
  27994. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27995. EXPECT_EQ(0, s.proxy_hits());
  27996. EXPECT_EQ(1, s.target_hits());
  27997. }
  27998. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27999. // Trailing dots must be normalized on BOTH sides — host and entry.
  28000. // An implementation that only strips the host-side trailing dot would
  28001. // fail to match host "example.com" against entry "example.com." because
  28002. // a literal substring search would compare 11 chars against 12.
  28003. ProxyAndTargetServers s;
  28004. auto cli = make_client("example.com", s);
  28005. cli->set_no_proxy({"example.com."});
  28006. auto res = cli->Get("/");
  28007. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28008. EXPECT_EQ(0, s.proxy_hits());
  28009. EXPECT_EQ(1, s.target_hits());
  28010. }
  28011. TEST(NoProxyTest, WildcardBypassesEverything) {
  28012. ProxyAndTargetServers s;
  28013. auto cli = make_client("anything.invalid.test", s);
  28014. cli->set_no_proxy({"*"});
  28015. auto res = cli->Get("/");
  28016. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28017. EXPECT_EQ(0, s.proxy_hits());
  28018. EXPECT_EQ(1, s.target_hits());
  28019. }
  28020. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  28021. ProxyAndTargetServers s;
  28022. Client cli("127.0.0.1", s.target_port());
  28023. cli.set_proxy("127.0.0.1", s.proxy_port());
  28024. cli.set_no_proxy({"127.0.0.1"});
  28025. auto res = cli.Get("/");
  28026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28027. EXPECT_EQ(0, s.proxy_hits());
  28028. EXPECT_EQ(1, s.target_hits());
  28029. }
  28030. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  28031. ProxyAndTargetServers s;
  28032. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  28033. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  28034. cli.set_proxy("127.0.0.1", s.proxy_port());
  28035. cli.set_no_proxy({"::1"});
  28036. auto res = cli.Get("/");
  28037. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28038. EXPECT_EQ(0, s.proxy_hits());
  28039. EXPECT_EQ(1, s.target_hits());
  28040. }
  28041. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  28042. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  28043. // must still be recognized as IPv6 for CIDR matching. Implementations
  28044. // that detect IPv6 only when the host begins with '[' would parse the
  28045. // host as a hostname and miss the match.
  28046. ProxyAndTargetServers s;
  28047. Client cli("fe80::1", s.target_port());
  28048. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28049. cli.set_proxy("127.0.0.1", s.proxy_port());
  28050. cli.set_no_proxy({"fe80::/10"});
  28051. auto res = cli.Get("/");
  28052. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28053. EXPECT_EQ(0, s.proxy_hits());
  28054. EXPECT_EQ(1, s.target_hits());
  28055. }
  28056. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  28057. ProxyAndTargetServers s;
  28058. Client cli("::1", s.target_port());
  28059. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  28060. cli.set_proxy("127.0.0.1", s.proxy_port());
  28061. cli.set_no_proxy({"[::1]"});
  28062. auto res = cli.Get("/");
  28063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28064. EXPECT_EQ(0, s.proxy_hits());
  28065. EXPECT_EQ(1, s.target_hits());
  28066. }
  28067. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  28068. ProxyAndTargetServers s;
  28069. Client cli("fe80::1", s.target_port());
  28070. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28071. cli.set_proxy("127.0.0.1", s.proxy_port());
  28072. cli.set_no_proxy({"[fe80::]/10"});
  28073. auto res = cli.Get("/");
  28074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28075. EXPECT_EQ(0, s.proxy_hits());
  28076. EXPECT_EQ(1, s.target_hits());
  28077. }
  28078. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  28079. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  28080. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  28081. // tricks via address-family conversion.
  28082. ProxyAndTargetServers s;
  28083. Client cli("::ffff:127.0.0.1", s.target_port());
  28084. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  28085. cli.set_proxy("127.0.0.1", s.proxy_port());
  28086. cli.set_no_proxy({"127.0.0.1"});
  28087. auto res = cli.Get("/");
  28088. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28089. EXPECT_GE(s.proxy_hits(), 1);
  28090. EXPECT_EQ(0, s.target_hits());
  28091. }
  28092. TEST(NoProxyTest, IPv4CidrMatch) {
  28093. ProxyAndTargetServers s;
  28094. Client cli("127.0.0.1", s.target_port());
  28095. cli.set_proxy("127.0.0.1", s.proxy_port());
  28096. cli.set_no_proxy({"127.0.0.0/8"});
  28097. auto res = cli.Get("/");
  28098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28099. EXPECT_EQ(0, s.proxy_hits());
  28100. EXPECT_EQ(1, s.target_hits());
  28101. }
  28102. TEST(NoProxyTest, IPv4CidrNonMatch) {
  28103. ProxyAndTargetServers s;
  28104. Client cli("127.0.0.1", s.target_port());
  28105. cli.set_proxy("127.0.0.1", s.proxy_port());
  28106. cli.set_no_proxy({"10.0.0.0/8"});
  28107. auto res = cli.Get("/");
  28108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28109. EXPECT_GE(s.proxy_hits(), 1);
  28110. EXPECT_EQ(0, s.target_hits());
  28111. }
  28112. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  28113. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  28114. // IPv4 target matches.
  28115. ProxyAndTargetServers s;
  28116. Client cli("127.0.0.1", s.target_port());
  28117. cli.set_proxy("127.0.0.1", s.proxy_port());
  28118. cli.set_no_proxy({"0.0.0.0/0"});
  28119. auto res = cli.Get("/");
  28120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28121. EXPECT_EQ(0, s.proxy_hits());
  28122. EXPECT_EQ(1, s.target_hits());
  28123. }
  28124. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  28125. ProxyAndTargetServers s;
  28126. Client cli("127.0.0.1", s.target_port());
  28127. cli.set_proxy("127.0.0.1", s.proxy_port());
  28128. cli.set_no_proxy({"127.0.0.1"});
  28129. auto res = cli.Get("/");
  28130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28131. EXPECT_EQ(0, s.proxy_hits());
  28132. EXPECT_EQ(1, s.target_hits());
  28133. }
  28134. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  28135. ProxyAndTargetServers s;
  28136. Client cli("127.0.0.1", s.target_port());
  28137. cli.set_proxy("127.0.0.1", s.proxy_port());
  28138. cli.set_no_proxy({"127.0.0.0/33"});
  28139. auto res = cli.Get("/");
  28140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28141. EXPECT_GE(s.proxy_hits(), 1);
  28142. EXPECT_EQ(0, s.target_hits());
  28143. }
  28144. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  28145. // Empty prefix after the slash must be rejected, not silently treated as /32.
  28146. ProxyAndTargetServers s;
  28147. Client cli("127.0.0.1", s.target_port());
  28148. cli.set_proxy("127.0.0.1", s.proxy_port());
  28149. cli.set_no_proxy({"127.0.0.1/"});
  28150. auto res = cli.Get("/");
  28151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28152. EXPECT_GE(s.proxy_hits(), 1);
  28153. EXPECT_EQ(0, s.target_hits());
  28154. }
  28155. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  28156. ProxyAndTargetServers s;
  28157. auto cli = make_client("internal.corp", s);
  28158. cli->set_proxy_basic_auth("u", "p");
  28159. cli->set_no_proxy({"internal.corp"});
  28160. auto res = cli->Get("/");
  28161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28162. EXPECT_EQ(1, s.target_hits());
  28163. EXPECT_EQ(0, s.proxy_hits());
  28164. EXPECT_FALSE(s.last_had_proxy_authz())
  28165. << "Proxy-Authorization must not be sent direct to the target";
  28166. }
  28167. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  28168. ProxyAndTargetServers s;
  28169. auto cli = make_client("public.example", s);
  28170. cli->set_proxy_basic_auth("u", "p");
  28171. cli->set_no_proxy({"internal.corp"}); // does not match
  28172. auto res = cli->Get("/");
  28173. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28174. EXPECT_GE(s.proxy_hits(), 1);
  28175. EXPECT_TRUE(s.last_had_proxy_authz());
  28176. }
  28177. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28178. std::atomic<int> hits{0};
  28179. std::atomic<int> hits_with_authz{0};
  28180. no_proxy_test::ScopedServer proxy_mock;
  28181. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28182. hits++;
  28183. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28184. if (req.target.find("/redir") != std::string::npos) {
  28185. res.set_redirect("http://other.example/landed");
  28186. } else {
  28187. res.set_content("via-proxy", "text/plain");
  28188. }
  28189. });
  28190. proxy_mock.listen();
  28191. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28192. hits = 0;
  28193. hits_with_authz = 0;
  28194. Client cli("public.example", 80);
  28195. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28196. cli.set_proxy_basic_auth(c.first, c.second);
  28197. cli.set_follow_location(true);
  28198. // The redirect to another host goes through the proxy as well
  28199. auto res = cli.Get("/redir");
  28200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28201. EXPECT_EQ(2, hits.load());
  28202. EXPECT_EQ(2, hits_with_authz.load());
  28203. }
  28204. }
  28205. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28206. ProxyAndTargetServers s;
  28207. auto cli = make_client("anything.test", s);
  28208. auto res = cli->Get("/");
  28209. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28210. EXPECT_GE(s.proxy_hits(), 1);
  28211. EXPECT_EQ(0, s.target_hits());
  28212. }
  28213. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28214. ProxyAndTargetServers s;
  28215. auto cli = make_client("example.com", s);
  28216. cli->set_no_proxy({"example.com:8080"});
  28217. auto res = cli->Get("/");
  28218. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28219. EXPECT_GE(s.proxy_hits(), 1);
  28220. EXPECT_EQ(0, s.target_hits());
  28221. }
  28222. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28223. ProxyAndTargetServers s;
  28224. auto cli = make_client("anything.test", s);
  28225. cli->set_no_proxy({"", " ", "\t"});
  28226. auto res = cli->Get("/");
  28227. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28228. EXPECT_GE(s.proxy_hits(), 1);
  28229. EXPECT_EQ(0, s.target_hits());
  28230. }
  28231. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28232. // An entry with leading/trailing whitespace must still match — env-style
  28233. // values are commonly pasted with stray spaces and an implementation
  28234. // that feeds the raw token directly to inet_pton would fail to match
  28235. // valid CIDRs because of the spaces.
  28236. ProxyAndTargetServers s;
  28237. Client cli("127.0.0.1", s.target_port());
  28238. cli.set_proxy("127.0.0.1", s.proxy_port());
  28239. cli.set_no_proxy({" 127.0.0.0/8 "});
  28240. auto res = cli.Get("/");
  28241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28242. EXPECT_EQ(0, s.proxy_hits());
  28243. EXPECT_EQ(1, s.target_hits());
  28244. }
  28245. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28246. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28247. // go direct and must NOT carry Proxy-Authorization.
  28248. std::atomic<int> proxy_hits{0};
  28249. std::atomic<int> target_hits{0};
  28250. std::atomic<bool> target_saw_authz{false};
  28251. no_proxy_test::ScopedServer proxy_mock, target;
  28252. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28253. proxy_hits++;
  28254. res.status = 302;
  28255. res.set_header("Location", "http://127.0.0.1:" +
  28256. std::to_string(target.port()) + "/landed");
  28257. });
  28258. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28259. target_hits++;
  28260. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28261. res.set_content("direct", "text/plain");
  28262. });
  28263. proxy_mock.listen();
  28264. target.listen();
  28265. Client cli("public.example", target.port());
  28266. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28267. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28268. cli.set_proxy_basic_auth("u", "p");
  28269. cli.set_no_proxy({"127.0.0.1"});
  28270. cli.set_follow_location(true);
  28271. auto res = cli.Get("/redir");
  28272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28273. EXPECT_GE(proxy_hits.load(), 1);
  28274. EXPECT_GE(target_hits.load(), 1);
  28275. EXPECT_FALSE(target_saw_authz.load());
  28276. }
  28277. #ifdef CPPHTTPLIB_SSL_ENABLED
  28278. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28279. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28280. // proxy creds would be sent to the (possibly hostile) origin.
  28281. std::atomic<int> target_hits{0};
  28282. std::atomic<bool> target_saw_proxy_authz{false};
  28283. no_proxy_test::ScopedServer target;
  28284. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28285. target_hits++;
  28286. if (req.has_header("Proxy-Authorization")) {
  28287. target_saw_proxy_authz = true;
  28288. }
  28289. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28290. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28291. "nonce=\"abc\", algorithm=MD5");
  28292. });
  28293. target.listen();
  28294. // The proxy address is set to the target's port: the bypass MUST kick in;
  28295. // if it doesn't, the test still routes "via proxy" to the same server and
  28296. // the Proxy-Authorization assertion below catches the leak.
  28297. Client cli("evil.example", target.port());
  28298. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28299. cli.set_proxy("127.0.0.1", target.port());
  28300. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28301. cli.set_no_proxy({"evil.example"});
  28302. auto res = cli.Get("/x");
  28303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28304. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28305. EXPECT_EQ(1, target_hits.load());
  28306. EXPECT_FALSE(target_saw_proxy_authz.load());
  28307. }
  28308. #endif
  28309. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28310. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28311. std::atomic<int> proxy_hits{0};
  28312. std::atomic<int> bypass_hits{0};
  28313. std::atomic<bool> proxy_saw_c_url{false};
  28314. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28315. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28316. proxy_hits++;
  28317. if (req.path.find("/start") != std::string::npos) {
  28318. res.status = 302;
  28319. res.set_header("Location", "http://127.0.0.1:" +
  28320. std::to_string(bypass_server.port()) +
  28321. "/middle");
  28322. return;
  28323. }
  28324. if (req.path.find("/end") != std::string::npos) {
  28325. proxy_saw_c_url = true;
  28326. res.set_content("c-via-proxy", "text/plain");
  28327. return;
  28328. }
  28329. res.set_content("unexpected", "text/plain");
  28330. });
  28331. // public.example's "advertised" port is arbitrary (the request never lands
  28332. // there — it goes through the proxy), but use a dynamic value to stay
  28333. // friendly with sharded parallel runs.
  28334. int public_port = bypass_server.port();
  28335. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28336. bypass_hits++;
  28337. res.status = 302;
  28338. res.set_header("Location", "http://public.example:" +
  28339. std::to_string(public_port) + "/end");
  28340. });
  28341. proxy_mock.listen();
  28342. bypass_server.listen();
  28343. Client cli("public.example", public_port);
  28344. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28345. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28346. cli.set_no_proxy({"127.0.0.1"});
  28347. cli.set_follow_location(true);
  28348. auto res = cli.Get("/start");
  28349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28350. EXPECT_EQ(StatusCode::OK_200, res->status);
  28351. EXPECT_EQ("c-via-proxy", res->body);
  28352. EXPECT_GE(proxy_hits.load(), 2);
  28353. EXPECT_GE(bypass_hits.load(), 1);
  28354. EXPECT_TRUE(proxy_saw_c_url.load());
  28355. }
  28356. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28357. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28358. // request reconnects to the correct endpoint.
  28359. std::atomic<int> proxy_hits{0};
  28360. std::atomic<int> target_hits{0};
  28361. no_proxy_test::ScopedServer proxy_mock, target;
  28362. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28363. proxy_hits++;
  28364. res.set_content("via-proxy", "text/plain");
  28365. });
  28366. target.svr().Get(".*", [&](const Request &, Response &res) {
  28367. target_hits++;
  28368. res.set_content("direct", "text/plain");
  28369. });
  28370. proxy_mock.listen();
  28371. target.listen();
  28372. Client cli("public.example", target.port());
  28373. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28374. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28375. cli.set_keep_alive(true);
  28376. auto res1 = cli.Get("/a");
  28377. ASSERT_TRUE(res1);
  28378. EXPECT_EQ("via-proxy", res1->body);
  28379. EXPECT_EQ(1, proxy_hits.load());
  28380. EXPECT_EQ(0, target_hits.load());
  28381. cli.set_no_proxy({"public.example"});
  28382. auto res2 = cli.Get("/b");
  28383. ASSERT_TRUE(res2);
  28384. EXPECT_EQ("direct", res2->body);
  28385. EXPECT_EQ(1, proxy_hits.load());
  28386. EXPECT_EQ(1, target_hits.load());
  28387. }
  28388. // Forward declarations (see the base64_encode note).
  28389. namespace httplib {
  28390. namespace detail {
  28391. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28392. int shutdown_socket(socket_t sock) noexcept;
  28393. } // namespace detail
  28394. } // namespace httplib
  28395. namespace proxy_tunnel_test {
  28396. const char *const kTunnelEstablished =
  28397. "HTTP/1.1 200 Connection established\r\n\r\n";
  28398. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28399. using ConnectReply = std::function<std::string(const std::string &head)>;
  28400. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28401. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28402. class ScopedConnectProxy {
  28403. public:
  28404. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28405. : forward_port_(forward_port), reply_(std::move(reply)) {
  28406. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28407. if (listen_sock_ == INVALID_SOCKET) { return; }
  28408. auto a = loopback(0);
  28409. auto addr = reinterpret_cast<sockaddr *>(&a);
  28410. socklen_t alen = sizeof(a);
  28411. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28412. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28413. ::listen(listen_sock_, 4) != 0) {
  28414. return;
  28415. }
  28416. port_ = ntohs(a.sin_port);
  28417. th_ = std::thread([this] { run(); });
  28418. }
  28419. ~ScopedConnectProxy() {
  28420. if (th_.joinable()) {
  28421. stop_ = true;
  28422. auto wake = connect_to(port_);
  28423. th_.join();
  28424. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28425. }
  28426. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28427. }
  28428. int port() const { return port_; }
  28429. int connect_hits() const { return connect_hits_.load(); }
  28430. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28431. std::string connect_request() const {
  28432. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28433. return connect_request_;
  28434. }
  28435. private:
  28436. static sockaddr_in loopback(int port) {
  28437. sockaddr_in a{};
  28438. a.sin_family = AF_INET;
  28439. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28440. a.sin_port = htons(static_cast<unsigned short>(port));
  28441. return a;
  28442. }
  28443. static socket_t connect_to(int port) {
  28444. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28445. if (sock == INVALID_SOCKET) { return sock; }
  28446. auto a = loopback(port);
  28447. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28448. detail::close_socket(sock);
  28449. return INVALID_SOCKET;
  28450. }
  28451. return sock;
  28452. }
  28453. static bool send_all(socket_t sock, const char *data, size_t size) {
  28454. while (size > 0) {
  28455. auto n = detail::send_socket(sock, data, size, 0);
  28456. if (n <= 0) { return false; }
  28457. data += n;
  28458. size -= static_cast<size_t>(n);
  28459. }
  28460. return true;
  28461. }
  28462. void run() {
  28463. for (;;) {
  28464. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28465. if (stop_) {
  28466. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28467. return;
  28468. }
  28469. if (client == INVALID_SOCKET) { continue; }
  28470. serve(client);
  28471. detail::close_socket(client);
  28472. }
  28473. }
  28474. void serve(socket_t client) {
  28475. std::string head;
  28476. char buf[2048];
  28477. while (head.find("\r\n\r\n") == std::string::npos) {
  28478. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28479. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28480. if (n <= 0) { return; }
  28481. head.append(buf, static_cast<size_t>(n));
  28482. }
  28483. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28484. connect_hits_++;
  28485. {
  28486. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28487. connect_request_ = head;
  28488. }
  28489. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28490. if (!send_all(client, res.data(), res.size()) ||
  28491. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28492. return;
  28493. }
  28494. auto origin = connect_to(forward_port_);
  28495. if (origin == INVALID_SOCKET) { return; }
  28496. // When either side stops, shut both down so the other pump returns too.
  28497. auto pump = [&](socket_t from, socket_t to) {
  28498. char b[8192];
  28499. for (;;) {
  28500. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28501. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28502. }
  28503. detail::shutdown_socket(client);
  28504. detail::shutdown_socket(origin);
  28505. };
  28506. std::thread up([&] { pump(client, origin); });
  28507. pump(origin, client);
  28508. up.join();
  28509. detail::close_socket(origin);
  28510. }
  28511. int forward_port_;
  28512. ConnectReply reply_;
  28513. socket_t listen_sock_ = INVALID_SOCKET;
  28514. int port_ = 0;
  28515. std::thread th_;
  28516. std::atomic<bool> stop_{false};
  28517. std::atomic<int> connect_hits_{0};
  28518. mutable std::mutex connect_request_mutex_;
  28519. std::string connect_request_;
  28520. };
  28521. } // namespace proxy_tunnel_test
  28522. #ifdef CPPHTTPLIB_SSL_ENABLED
  28523. namespace proxy_tunnel_test {
  28524. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28525. class ScopedSSLServer {
  28526. public:
  28527. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28528. port_ = svr_.bind_to_any_port("127.0.0.1");
  28529. }
  28530. ~ScopedSSLServer() {
  28531. svr_.stop();
  28532. if (th_.joinable()) { th_.join(); }
  28533. }
  28534. SSLServer &svr() { return svr_; }
  28535. int port() const { return port_; }
  28536. void listen() {
  28537. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28538. svr_.wait_until_ready();
  28539. }
  28540. private:
  28541. SSLServer svr_;
  28542. std::thread th_;
  28543. int port_ = 0;
  28544. };
  28545. // Sends one request through the CONNECT proxy to the TLS origin with a
  28546. // credential configured for each hop, and checks that each credential reaches
  28547. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28548. // origin's (every header in origin_headers) on the tunnelled request.
  28549. void CredentialsStayWithTheirHop(
  28550. const std::function<void(SSLClient &)> &set_credentials,
  28551. const std::string &scheme,
  28552. const std::vector<std::string> &origin_headers = {"Authorization"},
  28553. bool stream = false) {
  28554. std::atomic<int> origin_hits{0};
  28555. std::atomic<bool> origin_saw_proxy_authz{false};
  28556. std::atomic<bool> origin_saw_headers{false};
  28557. ScopedSSLServer origin;
  28558. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28559. origin_hits++;
  28560. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28561. origin_saw_headers =
  28562. std::all_of(origin_headers.begin(), origin_headers.end(),
  28563. [&](const std::string &h) { return req.has_header(h); });
  28564. res.set_content("ok", "text/plain");
  28565. });
  28566. origin.listen();
  28567. ScopedConnectProxy proxy(origin.port());
  28568. ASSERT_NE(0, proxy.port());
  28569. // Pinned to 127.0.0.1 for the same reason as the test below.
  28570. SSLClient cli("127.0.0.1", origin.port());
  28571. cli.enable_server_certificate_verification(false);
  28572. cli.set_proxy("127.0.0.1", proxy.port());
  28573. set_credentials(cli);
  28574. if (stream) {
  28575. auto handle = cli.open_stream("GET", "/x");
  28576. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28577. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28578. } else {
  28579. auto res = cli.Get("/x");
  28580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28581. EXPECT_EQ(StatusCode::OK_200, res->status);
  28582. }
  28583. EXPECT_EQ(1, origin_hits.load());
  28584. EXPECT_EQ(1, proxy.connect_hits());
  28585. EXPECT_TRUE(origin_saw_headers.load());
  28586. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28587. << "Proxy-Authorization must not be sent inside the tunnel";
  28588. auto connect_req = proxy.connect_request();
  28589. EXPECT_NE(std::string::npos,
  28590. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28591. for (const auto &h : origin_headers) {
  28592. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28593. << h << " must not be sent to the proxy on CONNECT";
  28594. }
  28595. }
  28596. } // namespace proxy_tunnel_test
  28597. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28598. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28599. [](SSLClient &cli) {
  28600. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28601. cli.set_basic_auth("origin-user", "origin-pass");
  28602. },
  28603. "Basic");
  28604. }
  28605. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28606. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28607. [](SSLClient &cli) {
  28608. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28609. cli.set_basic_auth("origin-user", "origin-pass");
  28610. },
  28611. "Basic", {"Authorization"}, true);
  28612. }
  28613. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28614. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28615. [](SSLClient &cli) {
  28616. cli.set_proxy_bearer_token_auth("proxy-token");
  28617. cli.set_bearer_token_auth("origin-token");
  28618. },
  28619. "Bearer");
  28620. }
  28621. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28622. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28623. [](SSLClient &cli) {
  28624. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28625. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28626. {"Cookie", "sid=origin-session"},
  28627. {"X-Api-Key", "origin-key"}});
  28628. },
  28629. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28630. }
  28631. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28632. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28633. // retry; otherwise proxy creds would be sent to the origin.
  28634. std::atomic<int> origin_hits{0};
  28635. std::atomic<bool> origin_saw_proxy_authz{false};
  28636. proxy_tunnel_test::ScopedSSLServer origin;
  28637. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28638. origin_hits++;
  28639. if (req.has_header("Proxy-Authorization")) {
  28640. origin_saw_proxy_authz = true;
  28641. }
  28642. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28643. res.set_header("Proxy-Authenticate",
  28644. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28645. "algorithm=MD5");
  28646. });
  28647. origin.listen();
  28648. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28649. ASSERT_NE(0, proxy.port());
  28650. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28651. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28652. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28653. // and answer with its own status, making this test flaky.
  28654. SSLClient cli("127.0.0.1", origin.port());
  28655. cli.enable_server_certificate_verification(false);
  28656. cli.set_proxy("127.0.0.1", proxy.port());
  28657. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28658. auto res = cli.Get("/x");
  28659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28660. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28661. EXPECT_EQ(1, origin_hits.load());
  28662. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28663. EXPECT_EQ(1, proxy.connect_hits());
  28664. }
  28665. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28666. std::string origin_sni;
  28667. std::string origin_host;
  28668. proxy_tunnel_test::ScopedSSLServer origin;
  28669. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28670. origin_sni = req.sni();
  28671. origin_host = req.get_header_value("Host");
  28672. res.set_content("ok", "text/plain");
  28673. });
  28674. origin.listen();
  28675. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28676. ASSERT_NE(0, proxy.port());
  28677. SSLClient cli("origin.example", origin.port());
  28678. cli.enable_server_certificate_verification(false);
  28679. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28680. cli.set_proxy("127.0.0.1", proxy.port());
  28681. auto res = cli.Get("/x");
  28682. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28683. EXPECT_EQ(StatusCode::OK_200, res->status);
  28684. auto port = std::to_string(origin.port());
  28685. auto target = "127.0.0.1:" + port;
  28686. auto connect_req = proxy.connect_request();
  28687. EXPECT_EQ(1, proxy.connect_hits());
  28688. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28689. EXPECT_NE(std::string::npos,
  28690. connect_req.find("\r\nHost: " + target + "\r\n"));
  28691. EXPECT_EQ("origin.example", origin_sni);
  28692. EXPECT_EQ("origin.example:" + port, origin_host);
  28693. }
  28694. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28695. proxy_tunnel_test::ScopedSSLServer origin;
  28696. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28697. res.set_content("ok", "text/plain");
  28698. });
  28699. origin.listen();
  28700. proxy_tunnel_test::ScopedConnectProxy proxy(
  28701. origin.port(), [](const std::string &head) -> std::string {
  28702. if (head.find(
  28703. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28704. std::string::npos) {
  28705. return proxy_tunnel_test::kTunnelEstablished;
  28706. }
  28707. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28708. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28709. "nonce=\"abc\", algorithm=MD5\r\n"
  28710. "Content-Length: 0\r\n\r\n";
  28711. });
  28712. ASSERT_NE(0, proxy.port());
  28713. SSLClient cli("origin.example", origin.port());
  28714. cli.enable_server_certificate_verification(false);
  28715. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28716. cli.set_proxy("127.0.0.1", proxy.port());
  28717. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28718. auto res = cli.Get("/x");
  28719. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28720. EXPECT_EQ(StatusCode::OK_200, res->status);
  28721. // The retried CONNECT is the one the proxy saw last.
  28722. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28723. auto connect_req = proxy.connect_request();
  28724. EXPECT_EQ(2, proxy.connect_hits());
  28725. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28726. EXPECT_NE(std::string::npos,
  28727. connect_req.find("\r\nHost: " + target + "\r\n"));
  28728. }
  28729. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28730. proxy_tunnel_test::ScopedSSLServer origin;
  28731. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28732. res.set_content("ok", "text/plain");
  28733. });
  28734. origin.listen();
  28735. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28736. ASSERT_NE(0, proxy.port());
  28737. SSLClient cli("origin.example", origin.port());
  28738. cli.enable_server_certificate_verification(false);
  28739. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28740. cli.set_proxy("127.0.0.1", proxy.port());
  28741. auto res = cli.Get("/x");
  28742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28743. EXPECT_EQ(StatusCode::OK_200, res->status);
  28744. auto target = "origin.example:" + std::to_string(origin.port());
  28745. auto connect_req = proxy.connect_request();
  28746. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28747. EXPECT_NE(std::string::npos,
  28748. connect_req.find("\r\nHost: " + target + "\r\n"));
  28749. }
  28750. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28751. proxy_tunnel_test::ScopedSSLServer origin;
  28752. auto port = std::to_string(origin.port());
  28753. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28754. res.set_redirect("https://next.example:" + port + "/y");
  28755. });
  28756. origin.svr().Get("/y", [](const Request &, Response &res) {
  28757. res.set_content("ok", "text/plain");
  28758. });
  28759. origin.listen();
  28760. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28761. ASSERT_NE(0, proxy.port());
  28762. SSLClient cli("origin.example", origin.port());
  28763. cli.enable_server_certificate_verification(false);
  28764. cli.set_tunnel_hostname_addr_map(
  28765. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28766. cli.set_proxy("127.0.0.1", proxy.port());
  28767. cli.set_follow_location(true);
  28768. auto res = cli.Get("/x");
  28769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28770. EXPECT_EQ("ok", res->body);
  28771. // The last CONNECT is the redirect client's.
  28772. ASSERT_EQ(2, proxy.connect_hits());
  28773. auto target = "127.0.0.1:" + port;
  28774. auto connect_req = proxy.connect_request();
  28775. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28776. EXPECT_NE(std::string::npos,
  28777. connect_req.find("\r\nHost: " + target + "\r\n"));
  28778. }
  28779. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28780. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28781. std::atomic<int> origin_hits{0};
  28782. proxy_tunnel_test::ScopedSSLServer origin;
  28783. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28784. origin_hits++;
  28785. res.set_content("ok", "text/plain");
  28786. });
  28787. origin.listen();
  28788. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28789. ASSERT_NE(0, proxy.port());
  28790. SSLClient cli("127.0.0.1", origin.port());
  28791. cli.enable_server_certificate_verification(false);
  28792. cli.set_proxy("127.0.0.1", proxy.port());
  28793. cli.set_keep_alive(true);
  28794. cli.set_session_verifier(
  28795. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28796. auto res = cli.Get("/x");
  28797. EXPECT_FALSE(res);
  28798. ASSERT_FALSE(cli.is_socket_open());
  28799. res = cli.Get("/x");
  28800. EXPECT_FALSE(res);
  28801. EXPECT_EQ(2, proxy.connect_hits());
  28802. auto handle = cli.open_stream("GET", "/x");
  28803. EXPECT_FALSE(handle.is_valid());
  28804. EXPECT_EQ(3, proxy.connect_hits());
  28805. EXPECT_EQ(0, origin_hits.load());
  28806. }
  28807. #endif
  28808. namespace proxy_tunnel_test {
  28809. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28810. // anything else gets a 407 with `challenge`.
  28811. ConnectReply require_proxy_auth(const std::string &expected,
  28812. const std::string &challenge) {
  28813. return [=](const std::string &head) -> std::string {
  28814. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28815. std::string::npos) {
  28816. return kTunnelEstablished;
  28817. }
  28818. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28819. "Proxy-Authenticate: " +
  28820. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28821. };
  28822. }
  28823. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28824. // request, then echoes.
  28825. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28826. ws.send(
  28827. "authorization:" + req.get_header_value("Authorization") +
  28828. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28829. std::string msg;
  28830. while (ws.read(msg)) {
  28831. ws.send(msg);
  28832. }
  28833. }
  28834. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28835. class ScopedWebSocketOrigin {
  28836. public:
  28837. ScopedWebSocketOrigin() {
  28838. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28839. server_.listen();
  28840. }
  28841. int port() const { return server_.port(); }
  28842. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28843. std::string url() const {
  28844. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28845. }
  28846. private:
  28847. no_proxy_test::ScopedServer server_;
  28848. };
  28849. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28850. // passed as a constructor header, and checks that each reaches only its hop.
  28851. void WebSocketCredentialsStayWithTheirHop(
  28852. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28853. const std::string &proxy_authz, const std::string &origin_authz) {
  28854. ScopedWebSocketOrigin origin;
  28855. ScopedConnectProxy proxy(
  28856. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28857. ASSERT_NE(0, proxy.port());
  28858. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28859. client.set_proxy("127.0.0.1", proxy.port());
  28860. set_proxy_credentials(client);
  28861. auto res = client.connect();
  28862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28863. std::string msg;
  28864. ASSERT_TRUE(client.read(msg));
  28865. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28866. client.close();
  28867. EXPECT_EQ(1, proxy.connect_hits());
  28868. EXPECT_EQ(std::string::npos,
  28869. proxy.connect_request().find("\r\nAuthorization: "))
  28870. << "origin credentials must not be sent to the proxy";
  28871. }
  28872. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28873. void WebSocketSetterCredentialsStayWithTheirHop(
  28874. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28875. const std::string &proxy_authz, const std::string &origin_authz) {
  28876. ScopedWebSocketOrigin origin;
  28877. ScopedConnectProxy proxy(
  28878. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28879. ASSERT_NE(0, proxy.port());
  28880. ws::WebSocketClient client(origin.url());
  28881. client.set_proxy("127.0.0.1", proxy.port());
  28882. set_credentials(client);
  28883. auto res = client.connect();
  28884. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28885. std::string msg;
  28886. ASSERT_TRUE(client.read(msg));
  28887. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28888. client.close();
  28889. EXPECT_EQ(1, proxy.connect_hits());
  28890. EXPECT_EQ(std::string::npos,
  28891. proxy.connect_request().find("\r\nAuthorization: "))
  28892. << "origin credentials must not be sent to the proxy";
  28893. }
  28894. } // namespace proxy_tunnel_test
  28895. namespace {
  28896. // Connects `client` and returns the Authorization header its upgrade
  28897. // request carried, or "<failed>" when the connection could not be opened.
  28898. std::string websocket_authorization(ws::WebSocketClient &client) {
  28899. if (!client.connect()) { return "<failed>"; }
  28900. std::string msg;
  28901. if (!client.read(msg)) { return "<failed>"; }
  28902. client.close();
  28903. auto prefix = std::string("authorization:");
  28904. auto end = msg.find("|proxy-authorization:");
  28905. return msg.substr(prefix.size(), end - prefix.size());
  28906. }
  28907. } // namespace
  28908. TEST(WebSocketClientAuthTest, BasicAuth) {
  28909. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28910. ws::WebSocketClient client(origin.url());
  28911. client.set_basic_auth("user", "pass");
  28912. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28913. websocket_authorization(client));
  28914. }
  28915. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28916. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28917. ws::WebSocketClient client(origin.url());
  28918. client.set_basic_auth("user", "");
  28919. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28920. websocket_authorization(client));
  28921. }
  28922. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28923. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28924. ws::WebSocketClient client(origin.url());
  28925. client.set_bearer_token_auth("token123");
  28926. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28927. }
  28928. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28929. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28930. ws::WebSocketClient client(origin.url());
  28931. client.set_bearer_token_auth("token123");
  28932. client.set_basic_auth("user", "pass");
  28933. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28934. websocket_authorization(client));
  28935. }
  28936. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28937. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28938. ws::WebSocketClient client(origin.url(),
  28939. {{"Authorization", "Bearer from-header"}});
  28940. client.set_bearer_token_auth("from-setter");
  28941. client.set_basic_auth("user", "pass");
  28942. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28943. }
  28944. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28945. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28946. ws::WebSocketClient client(origin.url());
  28947. EXPECT_EQ("", websocket_authorization(client));
  28948. client.set_bearer_token_auth("first");
  28949. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28950. client.set_bearer_token_auth("second");
  28951. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28952. client.set_bearer_token_auth("");
  28953. EXPECT_EQ("", websocket_authorization(client));
  28954. }
  28955. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28956. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28957. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28958. ASSERT_NE(0, proxy.port());
  28959. ws::WebSocketClient client(origin.url());
  28960. client.set_proxy("127.0.0.1", proxy.port());
  28961. auto res = client.connect();
  28962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28963. std::string msg;
  28964. ASSERT_TRUE(client.read(msg));
  28965. ASSERT_TRUE(client.send("hello"));
  28966. ASSERT_TRUE(client.read(msg));
  28967. EXPECT_EQ("hello", msg);
  28968. client.close();
  28969. EXPECT_EQ(1, proxy.connect_hits());
  28970. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28971. auto connect_req = proxy.connect_request();
  28972. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28973. EXPECT_NE(std::string::npos,
  28974. connect_req.find("\r\nHost: " + target + "\r\n"));
  28975. }
  28976. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28977. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28978. [](ws::WebSocketClient &cli) {
  28979. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28980. },
  28981. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28982. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28983. }
  28984. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28985. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28986. [](ws::WebSocketClient &cli) {
  28987. cli.set_proxy_bearer_token_auth("proxy-token");
  28988. },
  28989. "Bearer proxy-token", "Bearer origin-token");
  28990. }
  28991. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28992. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28993. [](ws::WebSocketClient &cli) {
  28994. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28995. cli.set_basic_auth("origin-user", "origin-pass");
  28996. },
  28997. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28998. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28999. }
  29000. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  29001. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  29002. [](ws::WebSocketClient &cli) {
  29003. cli.set_proxy_bearer_token_auth("proxy-token");
  29004. cli.set_bearer_token_auth("origin-token");
  29005. },
  29006. "Bearer proxy-token", "Bearer origin-token");
  29007. }
  29008. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  29009. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29010. proxy_tunnel_test::ScopedConnectProxy proxy(
  29011. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29012. "Basic " + detail::base64_encode("proxy-user:"),
  29013. "Basic realm=\"proxy\""));
  29014. ASSERT_NE(0, proxy.port());
  29015. ws::WebSocketClient client(origin.url());
  29016. client.set_proxy("127.0.0.1", proxy.port());
  29017. client.set_proxy_basic_auth("proxy-user", "");
  29018. auto res = client.connect();
  29019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29020. client.close();
  29021. EXPECT_EQ(1, proxy.connect_hits());
  29022. }
  29023. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  29024. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29025. proxy_tunnel_test::ScopedConnectProxy proxy(
  29026. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29027. "Bearer proxy-token", "Basic realm=\"proxy\""));
  29028. ASSERT_NE(0, proxy.port());
  29029. ws::WebSocketClient client(origin.url());
  29030. client.set_proxy("127.0.0.1", proxy.port());
  29031. auto res = client.connect();
  29032. EXPECT_FALSE(res);
  29033. EXPECT_EQ(Error::ProxyConnection, res.error());
  29034. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  29035. EXPECT_EQ("Basic realm=\"proxy\"",
  29036. res.get_header_value("Proxy-Authenticate"));
  29037. EXPECT_FALSE(client.is_open());
  29038. }
  29039. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  29040. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29041. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29042. ASSERT_NE(0, proxy.port());
  29043. ws::WebSocketClient client(origin.url());
  29044. client.set_proxy("127.0.0.1", proxy.port());
  29045. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29046. client.set_no_proxy({"127.0.0.1"});
  29047. auto res = client.connect();
  29048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29049. std::string msg;
  29050. ASSERT_TRUE(client.read(msg));
  29051. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29052. << "proxy credentials must not reach a bypassed origin";
  29053. client.close();
  29054. EXPECT_EQ(0, proxy.connect_hits());
  29055. }
  29056. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  29057. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29058. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29059. ASSERT_NE(0, proxy.port());
  29060. ws::WebSocketClient client(origin.url());
  29061. client.set_proxy("127.0.0.1", proxy.port());
  29062. ASSERT_TRUE(client.connect());
  29063. ASSERT_TRUE(client.connect());
  29064. client.close();
  29065. EXPECT_EQ(2, proxy.connect_hits());
  29066. }
  29067. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  29068. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29069. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29070. ASSERT_NE(0, proxy.port());
  29071. auto port = std::to_string(origin.port());
  29072. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29073. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29074. client.set_proxy("127.0.0.1", proxy.port());
  29075. auto res = client.connect();
  29076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29077. std::string msg;
  29078. ASSERT_TRUE(client.read(msg));
  29079. client.close();
  29080. EXPECT_EQ(1, proxy.connect_hits());
  29081. auto target = "127.0.0.1:" + port;
  29082. auto connect_req = proxy.connect_request();
  29083. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29084. EXPECT_NE(std::string::npos,
  29085. connect_req.find("\r\nHost: " + target + "\r\n"));
  29086. }
  29087. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  29088. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29089. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29090. ASSERT_NE(0, proxy.port());
  29091. auto port = std::to_string(origin.port());
  29092. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29093. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29094. client.set_proxy("127.0.0.1", proxy.port());
  29095. auto res = client.connect();
  29096. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29097. client.close();
  29098. auto target = "origin.example:" + port;
  29099. auto connect_req = proxy.connect_request();
  29100. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29101. EXPECT_NE(std::string::npos,
  29102. connect_req.find("\r\nHost: " + target + "\r\n"));
  29103. }
  29104. #ifdef CPPHTTPLIB_SSL_ENABLED
  29105. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  29106. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29107. proxy_tunnel_test::ScopedConnectProxy proxy(
  29108. origin.port(), [](const std::string &head) -> std::string {
  29109. if (head.find(
  29110. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  29111. std::string::npos) {
  29112. return proxy_tunnel_test::kTunnelEstablished;
  29113. }
  29114. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29115. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  29116. "nonce=\"abc\", algorithm=MD5\r\n"
  29117. "Content-Length: 0\r\n\r\n";
  29118. });
  29119. ASSERT_NE(0, proxy.port());
  29120. ws::WebSocketClient client(origin.url());
  29121. client.set_proxy("127.0.0.1", proxy.port());
  29122. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  29123. auto res = client.connect();
  29124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29125. std::string msg;
  29126. ASSERT_TRUE(client.read(msg));
  29127. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  29128. client.close();
  29129. EXPECT_EQ(2, proxy.connect_hits());
  29130. }
  29131. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  29132. proxy_tunnel_test::ScopedSSLServer origin;
  29133. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  29134. origin.listen();
  29135. proxy_tunnel_test::ScopedConnectProxy proxy(
  29136. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29137. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  29138. ASSERT_NE(0, proxy.port());
  29139. ws::WebSocketClient client(
  29140. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  29141. client.enable_server_certificate_verification(false);
  29142. client.set_proxy("127.0.0.1", proxy.port());
  29143. client.set_proxy_bearer_token_auth("proxy-token");
  29144. auto res = client.connect();
  29145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29146. std::string msg;
  29147. ASSERT_TRUE(client.read(msg));
  29148. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29149. << "Proxy-Authorization must not be sent inside the tunnel";
  29150. client.close();
  29151. EXPECT_EQ(1, proxy.connect_hits());
  29152. }
  29153. #endif
  29154. // ---------------------------------------------------------------------------
  29155. // Poller
  29156. // ---------------------------------------------------------------------------
  29157. namespace poller_test {
  29158. struct PollerBackend {
  29159. const char *name;
  29160. std::unique_ptr<detail::Poller> (*create)();
  29161. };
  29162. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  29163. *os << backend.name;
  29164. }
  29165. // Every backend runs the same contract tests. A new one is added here only.
  29166. std::vector<PollerBackend> poller_backends() {
  29167. return {
  29168. {"poll", &detail::PollPoller::create},
  29169. #ifdef __linux__
  29170. {"epoll", &detail::EpollPoller::create},
  29171. #endif
  29172. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29173. {"kqueue", &detail::KqueuePoller::create},
  29174. #endif
  29175. };
  29176. }
  29177. // A descriptor whose readability the test controls.
  29178. struct TestSocketPair {
  29179. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29180. TestSocketPair() { detail::create_socket_pair(fd); }
  29181. ~TestSocketPair() {
  29182. for (auto s : fd) {
  29183. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29184. }
  29185. }
  29186. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29187. socket_t reader() const { return fd[0]; }
  29188. void make_readable() {
  29189. const char c = 1;
  29190. detail::send_socket(fd[1], &c, 1, 0);
  29191. }
  29192. void close_writer() {
  29193. detail::close_socket(fd[1]);
  29194. fd[1] = INVALID_SOCKET;
  29195. }
  29196. };
  29197. using Tokens = std::vector<detail::Poller::Token>;
  29198. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29199. protected:
  29200. void SetUp() override {
  29201. poller_ = GetParam().create();
  29202. ASSERT_TRUE(poller_ != nullptr);
  29203. }
  29204. Tokens wait_for(int timeout_ms) {
  29205. Tokens ready;
  29206. poller_->wait(timeout_ms, ready);
  29207. std::sort(ready.begin(), ready.end());
  29208. return ready;
  29209. }
  29210. std::unique_ptr<detail::Poller> poller_;
  29211. };
  29212. } // namespace poller_test
  29213. using poller_test::PollerTest;
  29214. using poller_test::TestSocketPair;
  29215. using poller_test::Tokens;
  29216. INSTANTIATE_TEST_SUITE_P(
  29217. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29218. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29219. return std::string(p.param.name);
  29220. });
  29221. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29222. TestSocketPair sp;
  29223. ASSERT_TRUE(sp.ok());
  29224. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29225. EXPECT_EQ(Tokens{}, wait_for(0));
  29226. sp.make_readable();
  29227. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29228. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29229. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29230. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29231. }
  29232. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29233. TestSocketPair sp;
  29234. ASSERT_TRUE(sp.ok());
  29235. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29236. poller_->disarm(sp.reader());
  29237. poller_->disarm(sp.reader()); // disarming twice is harmless
  29238. sp.make_readable();
  29239. EXPECT_EQ(Tokens{}, wait_for(0));
  29240. }
  29241. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29242. TestSocketPair sp;
  29243. ASSERT_TRUE(sp.ok());
  29244. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29245. auto start = std::chrono::steady_clock::now();
  29246. EXPECT_EQ(Tokens{}, wait_for(30));
  29247. auto elapsed = std::chrono::steady_clock::now() - start;
  29248. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29249. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29250. }
  29251. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29252. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29253. for (detail::Poller::Token i = 0; i < 8; i++) {
  29254. sps.emplace_back(new TestSocketPair());
  29255. ASSERT_TRUE(sps.back()->ok());
  29256. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29257. }
  29258. sps[0]->make_readable();
  29259. sps[3]->make_readable();
  29260. sps[7]->make_readable();
  29261. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29262. // The others are still armed, the delivered ones are not.
  29263. sps[1]->make_readable();
  29264. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29265. EXPECT_EQ(Tokens{}, wait_for(0));
  29266. }
  29267. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29268. TestSocketPair s0, s1, s2;
  29269. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29270. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29271. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29272. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29273. // A delivery may move another entry inside the poller.
  29274. s0.make_readable();
  29275. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29276. // The entries left must still be found by descriptor.
  29277. poller_->disarm(s2.reader());
  29278. s1.make_readable();
  29279. s2.make_readable();
  29280. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29281. }
  29282. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29283. TestSocketPair sp;
  29284. ASSERT_TRUE(sp.ok());
  29285. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29286. sp.close_writer();
  29287. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29288. char c;
  29289. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29290. }
  29291. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29292. std::thread waker([&] {
  29293. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29294. poller_->wake();
  29295. });
  29296. Tokens ready;
  29297. auto start = std::chrono::steady_clock::now();
  29298. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29299. waker.join();
  29300. EXPECT_TRUE(ready.empty());
  29301. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29302. }
  29303. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29304. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29305. Tokens ready;
  29306. EXPECT_TRUE(poller_->wait(1000, ready));
  29307. }
  29308. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29309. for (int i = 0; i < 1000; i++) {
  29310. poller_->wake();
  29311. }
  29312. Tokens ready;
  29313. EXPECT_TRUE(poller_->wait(0, ready));
  29314. EXPECT_FALSE(poller_->wait(0, ready));
  29315. poller_->wake();
  29316. EXPECT_TRUE(poller_->wait(0, ready));
  29317. }
  29318. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29319. // Two threads publish changes and wake() after each, as a reactor's workers
  29320. // do. Every change must be seen without a wait() timing out. A lost wake()
  29321. // needs an unlucky interleaving, hence the rounds.
  29322. for (int round = 0; round < 5; round++) {
  29323. SCOPED_TRACE(round);
  29324. const int per_thread = 20000;
  29325. std::atomic<int> posted{0};
  29326. auto post = [&] {
  29327. for (int i = 0; i < per_thread; i++) {
  29328. posted++;
  29329. poller_->wake();
  29330. }
  29331. };
  29332. std::thread t1(post), t2(post);
  29333. auto lost = false;
  29334. Tokens ready;
  29335. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29336. if (!poller_->wait(1000, ready)) {
  29337. lost = true;
  29338. break;
  29339. }
  29340. }
  29341. t1.join();
  29342. t2.join();
  29343. ASSERT_FALSE(lost);
  29344. }
  29345. }
  29346. TEST(PollerFactoryTest, MakePollerWorks) {
  29347. auto poller = detail::make_poller();
  29348. ASSERT_TRUE(poller != nullptr);
  29349. poller->wake();
  29350. std::vector<detail::Poller::Token> ready;
  29351. EXPECT_TRUE(poller->wait(1000, ready));
  29352. }
  29353. // ---------------------------------------------------------------------------
  29354. // Keep-alive parking
  29355. // ---------------------------------------------------------------------------
  29356. namespace parking_test {
  29357. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29358. // runs once the port is bound and listening, before the server accepts.
  29359. struct RunningServer {
  29360. explicit RunningServer(
  29361. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29362. : svr_(svr) {
  29363. port = svr_.bind_to_any_port("127.0.0.1");
  29364. if (before_listen) { before_listen(port); }
  29365. thread = std::thread([this] { svr_.listen_after_bind(); });
  29366. svr_.wait_until_ready();
  29367. }
  29368. ~RunningServer() {
  29369. svr_.stop();
  29370. if (thread.joinable()) { thread.join(); }
  29371. }
  29372. Server &svr_;
  29373. int port = 0;
  29374. std::thread thread;
  29375. };
  29376. struct Sockets {
  29377. std::vector<socket_t> socks;
  29378. ~Sockets() {
  29379. for (auto s : socks) {
  29380. detail::close_socket(s);
  29381. }
  29382. }
  29383. socket_t connect(int port) {
  29384. auto error = Error::Success;
  29385. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29386. false, false, nullptr, 2, 0, 2, 0, 2,
  29387. 0, std::string(), error);
  29388. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29389. return s;
  29390. }
  29391. };
  29392. std::chrono::steady_clock::time_point in_ms(int ms) {
  29393. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29394. }
  29395. bool readable_by(socket_t sock,
  29396. std::chrono::steady_clock::time_point deadline) {
  29397. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29398. deadline - std::chrono::steady_clock::now())
  29399. .count();
  29400. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29401. }
  29402. bool send_get(socket_t sock, const std::string &path = "/") {
  29403. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29404. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29405. static_cast<ssize_t>(req.size());
  29406. }
  29407. // Reads one response whose body is "ok".
  29408. bool receives_ok(socket_t sock, int timeout_ms) {
  29409. auto deadline = in_ms(timeout_ms);
  29410. std::string buf;
  29411. while (readable_by(sock, deadline)) {
  29412. char tmp[1024];
  29413. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29414. if (n <= 0) { return false; }
  29415. buf.append(tmp, static_cast<size_t>(n));
  29416. auto end = buf.find("\r\n\r\n");
  29417. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29418. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29419. buf.compare(end + 4, 2, "ok") == 0;
  29420. }
  29421. }
  29422. return false;
  29423. }
  29424. bool get_ok(socket_t sock, int timeout_ms) {
  29425. return send_get(sock) && receives_ok(sock, timeout_ms);
  29426. }
  29427. // Whether the server closes `sock` by `deadline`.
  29428. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29429. char c;
  29430. return readable_by(sock, deadline) &&
  29431. detail::read_socket(sock, &c, 1, 0) <= 0;
  29432. }
  29433. // Whether the server closes `sock` without answering a request.
  29434. bool get_refused(socket_t sock, int timeout_ms) {
  29435. return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
  29436. }
  29437. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29438. auto deadline = in_ms(timeout_ms);
  29439. while (!cond()) {
  29440. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29441. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29442. }
  29443. return true;
  29444. }
  29445. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29446. svr.new_task_queue = std::move(new_task_queue);
  29447. svr.set_keep_alive_parking(true);
  29448. svr.Get("/", [](const Request &, Response &res) {
  29449. res.set_content("ok", "text/plain");
  29450. });
  29451. }
  29452. std::function<TaskQueue *(void)> threads(size_t n) {
  29453. return [n] { return new ThreadPool(n); };
  29454. }
  29455. // Counts what the event loop managed to queue, so that a test can wait for it.
  29456. class CountingTaskQueue final : public TaskQueue {
  29457. public:
  29458. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29459. std::atomic<int> &full)
  29460. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29461. bool enqueue(std::function<void()> fn) override {
  29462. auto queued = pool_.enqueue([this, fn]() {
  29463. fn();
  29464. // Holds the worker back from taking the next job.
  29465. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29466. });
  29467. (queued ? ok_ : full_)++;
  29468. return queued;
  29469. }
  29470. void shutdown() override { pool_.shutdown(); }
  29471. std::atomic<int> pause_after_ms{0};
  29472. private:
  29473. ThreadPool pool_;
  29474. std::atomic<int> &ok_;
  29475. std::atomic<int> &full_;
  29476. };
  29477. // Holds handlers until it opens, or for 3 seconds at most.
  29478. class Gate {
  29479. public:
  29480. void wait() {
  29481. std::unique_lock<std::mutex> lock(m_);
  29482. entered_++;
  29483. cv_.notify_all();
  29484. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29485. }
  29486. void open() {
  29487. std::lock_guard<std::mutex> guard(m_);
  29488. open_ = true;
  29489. cv_.notify_all();
  29490. }
  29491. int entered() {
  29492. std::lock_guard<std::mutex> guard(m_);
  29493. return entered_;
  29494. }
  29495. private:
  29496. std::mutex m_;
  29497. std::condition_variable cv_;
  29498. bool open_ = false;
  29499. int entered_ = 0;
  29500. };
  29501. } // namespace parking_test
  29502. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29503. using namespace parking_test;
  29504. Server svr;
  29505. serve_ok(svr, threads(1));
  29506. RunningServer running(svr);
  29507. Sockets socks;
  29508. // One kept-alive connection that has been served, and many that have not
  29509. // sent anything yet. None of them may keep the only worker.
  29510. auto served = socks.connect(running.port);
  29511. ASSERT_TRUE(get_ok(served, 2000));
  29512. for (int i = 0; i < 49; i++) {
  29513. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29514. }
  29515. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29516. EXPECT_TRUE(get_ok(served, 1000));
  29517. }
  29518. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29519. using namespace parking_test;
  29520. Server svr;
  29521. serve_ok(svr, threads(1));
  29522. svr.set_keep_alive_timeout(1);
  29523. RunningServer running(svr);
  29524. Sockets socks;
  29525. for (int i = 0; i < 3; i++) {
  29526. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29527. }
  29528. // One worker waiting on each in turn would take about 3 seconds.
  29529. auto deadline = in_ms(2000);
  29530. for (auto s : socks.socks) {
  29531. EXPECT_TRUE(sees_eof(s, deadline));
  29532. }
  29533. }
  29534. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29535. using namespace parking_test;
  29536. std::atomic<int> queued{0}, full{0};
  29537. Server svr;
  29538. // One worker and room for one queued task.
  29539. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29540. Gate gate;
  29541. svr.Get("/block", [&](const Request &, Response &res) {
  29542. gate.wait();
  29543. res.set_content("ok", "text/plain");
  29544. });
  29545. RunningServer running(svr);
  29546. // Before the server stops, so that a failed run does not wait for the
  29547. // handler's timeout.
  29548. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29549. Sockets socks;
  29550. auto a = socks.connect(running.port);
  29551. ASSERT_TRUE(get_ok(a, 2000));
  29552. // B keeps the only worker busy.
  29553. auto b = socks.connect(running.port);
  29554. ASSERT_TRUE(send_get(b, "/block"));
  29555. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29556. // A new connection C fills the queue.
  29557. auto c = socks.connect(running.port);
  29558. ASSERT_TRUE(send_get(c));
  29559. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29560. // A's next request finds the queue full, but A has been served before, so it
  29561. // waits instead of being cut off.
  29562. ASSERT_TRUE(send_get(a));
  29563. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29564. gate.open();
  29565. EXPECT_TRUE(receives_ok(b, 2000));
  29566. EXPECT_TRUE(receives_ok(c, 2000));
  29567. EXPECT_TRUE(receives_ok(a, 2000));
  29568. }
  29569. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29570. using namespace parking_test;
  29571. std::atomic<int> queued{0}, full{0};
  29572. CountingTaskQueue *queue = nullptr;
  29573. Server svr;
  29574. // Two workers and room for one queued task.
  29575. serve_ok(svr,
  29576. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29577. Gate first, second;
  29578. svr.Get("/first", [&](const Request &, Response &res) {
  29579. first.wait();
  29580. res.set_content("ok", "text/plain");
  29581. });
  29582. svr.Get("/second", [&](const Request &, Response &res) {
  29583. second.wait();
  29584. res.set_content("ok", "text/plain");
  29585. });
  29586. RunningServer running(svr);
  29587. auto open_gates = detail::scope_exit([&] {
  29588. first.open();
  29589. second.open();
  29590. });
  29591. Sockets socks;
  29592. auto a = socks.connect(running.port);
  29593. ASSERT_TRUE(get_ok(a, 2000));
  29594. // B and D take both workers, and C fills the queue. One at a time: the
  29595. // queue has room for one job only until a worker takes it.
  29596. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29597. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29598. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29599. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29600. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29601. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29602. // A's next request waits in the backlog.
  29603. ASSERT_TRUE(send_get(a));
  29604. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29605. // B's worker finishes, then takes C off the queue only later, which makes
  29606. // room for A.
  29607. queue->pause_after_ms = 200;
  29608. first.open();
  29609. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29610. queue->pause_after_ms = 0;
  29611. second.open();
  29612. EXPECT_TRUE(receives_ok(a, 2000));
  29613. }
  29614. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29615. using namespace parking_test;
  29616. Server svr;
  29617. serve_ok(svr, threads(1));
  29618. svr.set_keep_alive_timeout(0);
  29619. // The request is on the socket before the server accepts the connection,
  29620. // so it does not race the 10 ms floor. Without the floor the connection is
  29621. // closed unread.
  29622. Sockets socks;
  29623. auto sock = INVALID_SOCKET;
  29624. RunningServer running(svr, [&](int port) {
  29625. sock = socks.connect(port);
  29626. send_get(sock);
  29627. });
  29628. EXPECT_TRUE(receives_ok(sock, 1000));
  29629. }
  29630. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29631. using namespace parking_test;
  29632. for (int round = 0; round < 5; round++) {
  29633. SCOPED_TRACE(round);
  29634. Server svr;
  29635. serve_ok(svr, threads(2));
  29636. RunningServer running(svr);
  29637. Sockets socks;
  29638. for (int i = 0; i < 20; i++) {
  29639. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29640. }
  29641. auto start = std::chrono::steady_clock::now();
  29642. svr.stop();
  29643. running.thread.join();
  29644. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29645. std::chrono::milliseconds(500));
  29646. auto deadline = in_ms(1000);
  29647. for (auto s : socks.socks) {
  29648. EXPECT_TRUE(sees_eof(s, deadline));
  29649. }
  29650. }
  29651. }
  29652. #ifdef CPPHTTPLIB_SSL_ENABLED
  29653. namespace parking_test {
  29654. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29655. // that has opened a connection ahead of time. Freeing the session sends no
  29656. // close_notify, so the connection stays quiet.
  29657. bool handshake_only(socket_t sock) {
  29658. auto ctx = tls::create_client_context();
  29659. tls::set_verify_client(ctx, false);
  29660. auto session = tls::create_session(ctx, sock);
  29661. auto se = detail::scope_exit([&] {
  29662. tls::free_session(session);
  29663. tls::free_context(ctx);
  29664. });
  29665. tls::TlsError err;
  29666. return session &&
  29667. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29668. }
  29669. Client tls_client(int port) {
  29670. Client cli("https://127.0.0.1:" + std::to_string(port));
  29671. cli.enable_server_certificate_verification(false);
  29672. cli.set_keep_alive(true);
  29673. cli.set_connection_timeout(1);
  29674. cli.set_read_timeout(1);
  29675. return cli;
  29676. }
  29677. bool tls_get_ok(Client &cli) {
  29678. auto res = cli.Get("/");
  29679. return res && res->body == "ok";
  29680. }
  29681. } // namespace parking_test
  29682. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29683. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29684. struct {
  29685. unsigned long version;
  29686. bool safe;
  29687. } cases[] = {
  29688. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29689. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29690. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29691. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29692. };
  29693. for (const auto &c : cases) {
  29694. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29695. << std::hex << c.version;
  29696. }
  29697. }
  29698. #endif
  29699. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29700. using namespace parking_test;
  29701. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29702. ASSERT_TRUE(svr.is_valid());
  29703. serve_ok(svr, threads(1));
  29704. svr.set_read_timeout(1); // so that a failing run does not take long
  29705. RunningServer running(svr);
  29706. Sockets socks;
  29707. // One served connection, some that have not started their handshake, and
  29708. // one that has finished it and gone quiet. None may keep the only worker.
  29709. auto served = tls_client(running.port);
  29710. ASSERT_TRUE(tls_get_ok(served));
  29711. for (int i = 0; i < 10; i++) {
  29712. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29713. }
  29714. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29715. auto other = tls_client(running.port);
  29716. EXPECT_TRUE(tls_get_ok(other));
  29717. EXPECT_TRUE(tls_get_ok(served));
  29718. }
  29719. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29720. using namespace parking_test;
  29721. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29722. ASSERT_TRUE(svr.is_valid());
  29723. serve_ok(svr, threads(1));
  29724. RunningServer running(svr);
  29725. Sockets socks;
  29726. auto plain = socks.connect(running.port);
  29727. ASSERT_TRUE(send_get(plain));
  29728. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29729. EXPECT_NE(0, svr.ssl_last_error());
  29730. }
  29731. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29732. using namespace parking_test;
  29733. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29734. ASSERT_TRUE(svr.is_valid());
  29735. serve_ok(svr, threads(2));
  29736. RunningServer running(svr);
  29737. std::vector<Client> clients;
  29738. for (int i = 0; i < 5; i++) {
  29739. clients.push_back(tls_client(running.port));
  29740. ASSERT_TRUE(tls_get_ok(clients.back()));
  29741. }
  29742. auto start = std::chrono::steady_clock::now();
  29743. svr.stop();
  29744. running.thread.join();
  29745. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29746. std::chrono::milliseconds(500));
  29747. }
  29748. #endif
  29749. TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
  29750. using namespace parking_test;
  29751. for (auto parking : {false, true}) {
  29752. SCOPED_TRACE(parking);
  29753. Server svr;
  29754. serve_ok(svr, threads(2));
  29755. svr.set_keep_alive_parking(parking);
  29756. std::atomic<int> served{0};
  29757. svr.set_pre_routing_handler([&](const Request &, Response &) {
  29758. served++;
  29759. return Server::HandlerResponse::Unhandled;
  29760. });
  29761. std::atomic<bool> allow{false};
  29762. std::atomic<bool> peer_seen{false};
  29763. svr.set_accept_handler([&](socket_t sock) {
  29764. sockaddr_in addr{};
  29765. socklen_t len = sizeof(addr);
  29766. peer_seen =
  29767. getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
  29768. addr.sin_family == AF_INET &&
  29769. ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
  29770. return allow.load();
  29771. });
  29772. RunningServer running(svr);
  29773. Sockets socks;
  29774. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29775. EXPECT_TRUE(peer_seen);
  29776. EXPECT_EQ(0, served);
  29777. allow = true;
  29778. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29779. EXPECT_EQ(1, served);
  29780. }
  29781. }
  29782. TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
  29783. using namespace parking_test;
  29784. Server svr;
  29785. serve_ok(svr, threads(1));
  29786. svr.set_read_timeout(std::chrono::milliseconds(50));
  29787. std::atomic<bool> timed_out{false};
  29788. svr.set_accept_handler([&](socket_t sock) {
  29789. char c;
  29790. timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
  29791. return true;
  29792. });
  29793. RunningServer running(svr);
  29794. Sockets socks;
  29795. auto sock = socks.connect(running.port);
  29796. EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
  29797. EXPECT_TRUE(get_ok(sock, 1000));
  29798. }
  29799. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  29800. TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
  29801. using namespace parking_test;
  29802. Server svr;
  29803. serve_ok(svr, threads(1));
  29804. std::atomic<bool> throws{true};
  29805. svr.set_accept_handler([&](socket_t) -> bool {
  29806. if (throws) { throw std::runtime_error("refused"); }
  29807. return true;
  29808. });
  29809. std::atomic<int> logged{0};
  29810. svr.set_error_logger([&](const Error &err, const Request *) {
  29811. if (err == Error::UserCallbackException) { logged++; }
  29812. });
  29813. RunningServer running(svr);
  29814. Sockets socks;
  29815. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29816. EXPECT_EQ(1, logged);
  29817. throws = false;
  29818. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29819. }
  29820. #endif
  29821. #ifdef CPPHTTPLIB_SSL_ENABLED
  29822. TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
  29823. using namespace parking_test;
  29824. for (auto parking : {false, true}) {
  29825. SCOPED_TRACE(parking);
  29826. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29827. ASSERT_TRUE(svr.is_valid());
  29828. serve_ok(svr, threads(1));
  29829. svr.set_keep_alive_parking(parking);
  29830. svr.set_accept_handler([](socket_t) { return false; });
  29831. RunningServer running(svr);
  29832. Sockets socks;
  29833. // A handshake on a plain request would fail and set ssl_last_error().
  29834. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29835. EXPECT_EQ(0, svr.ssl_last_error());
  29836. }
  29837. }
  29838. #endif