test.cc 1.1 MB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795179617971798179918001801180218031804180518061807180818091810181118121813181418151816181718181819182018211822182318241825182618271828182918301831183218331834183518361837183818391840184118421843184418451846184718481849185018511852185318541855185618571858185918601861186218631864186518661867186818691870187118721873187418751876187718781879188018811882188318841885188618871888188918901891189218931894189518961897189818991900190119021903190419051906190719081909191019111912191319141915191619171918191919201921192219231924192519261927192819291930193119321933193419351936193719381939194019411942194319441945194619471948194919501951195219531954195519561957195819591960196119621963196419651966196719681969197019711972197319741975197619771978197919801981198219831984198519861987198819891990199119921993199419951996199719981999200020012002200320042005200620072008200920102011201220132014201520162017201820192020202120222023202420252026202720282029203020312032203320342035203620372038203920402041204220432044204520462047204820492050205120522053205420552056205720582059206020612062206320642065206620672068206920702071207220732074207520762077207820792080208120822083208420852086208720882089209020912092209320942095209620972098209921002101210221032104210521062107210821092110211121122113211421152116211721182119212021212122212321242125212621272128212921302131213221332134213521362137213821392140214121422143214421452146214721482149215021512152215321542155215621572158215921602161216221632164216521662167216821692170217121722173217421752176217721782179218021812182218321842185218621872188218921902191219221932194219521962197219821992200220122022203220422052206220722082209221022112212221322142215221622172218221922202221222222232224222522262227222822292230223122322233223422352236223722382239224022412242224322442245224622472248224922502251225222532254225522562257225822592260226122622263226422652266226722682269227022712272227322742275227622772278227922802281228222832284228522862287228822892290229122922293229422952296229722982299230023012302230323042305230623072308230923102311231223132314231523162317231823192320232123222323232423252326232723282329233023312332233323342335233623372338233923402341234223432344234523462347234823492350235123522353235423552356235723582359236023612362236323642365236623672368236923702371237223732374237523762377237823792380238123822383238423852386238723882389239023912392239323942395239623972398239924002401240224032404240524062407240824092410241124122413241424152416241724182419242024212422242324242425242624272428242924302431243224332434243524362437243824392440244124422443244424452446244724482449245024512452245324542455245624572458245924602461246224632464246524662467246824692470247124722473247424752476247724782479248024812482248324842485248624872488248924902491249224932494249524962497249824992500250125022503250425052506250725082509251025112512251325142515251625172518251925202521252225232524252525262527252825292530253125322533253425352536253725382539254025412542254325442545254625472548254925502551255225532554255525562557255825592560256125622563256425652566256725682569257025712572257325742575257625772578257925802581258225832584258525862587258825892590259125922593259425952596259725982599260026012602260326042605260626072608260926102611261226132614261526162617261826192620262126222623262426252626262726282629263026312632263326342635263626372638263926402641264226432644264526462647264826492650265126522653265426552656265726582659266026612662266326642665266626672668266926702671267226732674267526762677267826792680268126822683268426852686268726882689269026912692269326942695269626972698269927002701270227032704270527062707270827092710271127122713271427152716271727182719272027212722272327242725272627272728272927302731273227332734273527362737273827392740274127422743274427452746274727482749275027512752275327542755275627572758275927602761276227632764276527662767276827692770277127722773277427752776277727782779278027812782278327842785278627872788278927902791279227932794279527962797279827992800280128022803280428052806280728082809281028112812281328142815281628172818281928202821282228232824282528262827282828292830283128322833283428352836283728382839284028412842284328442845284628472848284928502851285228532854285528562857285828592860286128622863286428652866286728682869287028712872287328742875287628772878287928802881288228832884288528862887288828892890289128922893289428952896289728982899290029012902290329042905290629072908290929102911291229132914291529162917291829192920292129222923292429252926292729282929293029312932293329342935293629372938293929402941294229432944294529462947294829492950295129522953295429552956295729582959296029612962296329642965296629672968296929702971297229732974297529762977297829792980298129822983298429852986298729882989299029912992299329942995299629972998299930003001300230033004300530063007300830093010301130123013301430153016301730183019302030213022302330243025302630273028302930303031303230333034303530363037303830393040304130423043304430453046304730483049305030513052305330543055305630573058305930603061306230633064306530663067306830693070307130723073307430753076307730783079308030813082308330843085308630873088308930903091309230933094309530963097309830993100310131023103310431053106310731083109311031113112311331143115311631173118311931203121312231233124312531263127312831293130313131323133313431353136313731383139314031413142314331443145314631473148314931503151315231533154315531563157315831593160316131623163316431653166316731683169317031713172317331743175317631773178317931803181318231833184318531863187318831893190319131923193319431953196319731983199320032013202320332043205320632073208320932103211321232133214321532163217321832193220322132223223322432253226322732283229323032313232323332343235323632373238323932403241324232433244324532463247324832493250325132523253325432553256325732583259326032613262326332643265326632673268326932703271327232733274327532763277327832793280328132823283328432853286328732883289329032913292329332943295329632973298329933003301330233033304330533063307330833093310331133123313331433153316331733183319332033213322332333243325332633273328332933303331333233333334333533363337333833393340334133423343334433453346334733483349335033513352335333543355335633573358335933603361336233633364336533663367336833693370337133723373337433753376337733783379338033813382338333843385338633873388338933903391339233933394339533963397339833993400340134023403340434053406340734083409341034113412341334143415341634173418341934203421342234233424342534263427342834293430343134323433343434353436343734383439344034413442344334443445344634473448344934503451345234533454345534563457345834593460346134623463346434653466346734683469347034713472347334743475347634773478347934803481348234833484348534863487348834893490349134923493349434953496349734983499350035013502350335043505350635073508350935103511351235133514351535163517351835193520352135223523352435253526352735283529353035313532353335343535353635373538353935403541354235433544354535463547354835493550355135523553355435553556355735583559356035613562356335643565356635673568356935703571357235733574357535763577357835793580358135823583358435853586358735883589359035913592359335943595359635973598359936003601360236033604360536063607360836093610361136123613361436153616361736183619362036213622362336243625362636273628362936303631363236333634363536363637363836393640364136423643364436453646364736483649365036513652365336543655365636573658365936603661366236633664366536663667366836693670367136723673367436753676367736783679368036813682368336843685368636873688368936903691369236933694369536963697369836993700370137023703370437053706370737083709371037113712371337143715371637173718371937203721372237233724372537263727372837293730373137323733373437353736373737383739374037413742374337443745374637473748374937503751375237533754375537563757375837593760376137623763376437653766376737683769377037713772377337743775377637773778377937803781378237833784378537863787378837893790379137923793379437953796379737983799380038013802380338043805380638073808380938103811381238133814381538163817381838193820382138223823382438253826382738283829383038313832383338343835383638373838383938403841384238433844384538463847384838493850385138523853385438553856385738583859386038613862386338643865386638673868386938703871387238733874387538763877387838793880388138823883388438853886388738883889389038913892389338943895389638973898389939003901390239033904390539063907390839093910391139123913391439153916391739183919392039213922392339243925392639273928392939303931393239333934393539363937393839393940394139423943394439453946394739483949395039513952395339543955395639573958395939603961396239633964396539663967396839693970397139723973397439753976397739783979398039813982398339843985398639873988398939903991399239933994399539963997399839994000400140024003400440054006400740084009401040114012401340144015401640174018401940204021402240234024402540264027402840294030403140324033403440354036403740384039404040414042404340444045404640474048404940504051405240534054405540564057405840594060406140624063406440654066406740684069407040714072407340744075407640774078407940804081408240834084408540864087408840894090409140924093409440954096409740984099410041014102410341044105410641074108410941104111411241134114411541164117411841194120412141224123412441254126412741284129413041314132413341344135413641374138413941404141414241434144414541464147414841494150415141524153415441554156415741584159416041614162416341644165416641674168416941704171417241734174417541764177417841794180418141824183418441854186418741884189419041914192419341944195419641974198419942004201420242034204420542064207420842094210421142124213421442154216421742184219422042214222422342244225422642274228422942304231423242334234423542364237423842394240424142424243424442454246424742484249425042514252425342544255425642574258425942604261426242634264426542664267426842694270427142724273427442754276427742784279428042814282428342844285428642874288428942904291429242934294429542964297429842994300430143024303430443054306430743084309431043114312431343144315431643174318431943204321432243234324432543264327432843294330433143324333433443354336433743384339434043414342434343444345434643474348434943504351435243534354435543564357435843594360436143624363436443654366436743684369437043714372437343744375437643774378437943804381438243834384438543864387438843894390439143924393439443954396439743984399440044014402440344044405440644074408440944104411441244134414441544164417441844194420442144224423442444254426442744284429443044314432443344344435443644374438443944404441444244434444444544464447444844494450445144524453445444554456445744584459446044614462446344644465446644674468446944704471447244734474447544764477447844794480448144824483448444854486448744884489449044914492449344944495449644974498449945004501450245034504450545064507450845094510451145124513451445154516451745184519452045214522452345244525452645274528452945304531453245334534453545364537453845394540454145424543454445454546454745484549455045514552455345544555455645574558455945604561456245634564456545664567456845694570457145724573457445754576457745784579458045814582458345844585458645874588458945904591459245934594459545964597459845994600460146024603460446054606460746084609461046114612461346144615461646174618461946204621462246234624462546264627462846294630463146324633463446354636463746384639464046414642464346444645464646474648464946504651465246534654465546564657465846594660466146624663466446654666466746684669467046714672467346744675467646774678467946804681468246834684468546864687468846894690469146924693469446954696469746984699470047014702470347044705470647074708470947104711471247134714471547164717471847194720472147224723472447254726472747284729473047314732473347344735473647374738473947404741474247434744474547464747474847494750475147524753475447554756475747584759476047614762476347644765476647674768476947704771477247734774477547764777477847794780478147824783478447854786478747884789479047914792479347944795479647974798479948004801480248034804480548064807480848094810481148124813481448154816481748184819482048214822482348244825482648274828482948304831483248334834483548364837483848394840484148424843484448454846484748484849485048514852485348544855485648574858485948604861486248634864486548664867486848694870487148724873487448754876487748784879488048814882488348844885488648874888488948904891489248934894489548964897489848994900490149024903490449054906490749084909491049114912491349144915491649174918491949204921492249234924492549264927492849294930493149324933493449354936493749384939494049414942494349444945494649474948494949504951495249534954495549564957495849594960496149624963496449654966496749684969497049714972497349744975497649774978497949804981498249834984498549864987498849894990499149924993499449954996499749984999500050015002500350045005500650075008500950105011501250135014501550165017501850195020502150225023502450255026502750285029503050315032503350345035503650375038503950405041504250435044504550465047504850495050505150525053505450555056505750585059506050615062506350645065506650675068506950705071507250735074507550765077507850795080508150825083508450855086508750885089509050915092509350945095509650975098509951005101510251035104510551065107510851095110511151125113511451155116511751185119512051215122512351245125512651275128512951305131513251335134513551365137513851395140514151425143514451455146514751485149515051515152515351545155515651575158515951605161516251635164516551665167516851695170517151725173517451755176517751785179518051815182518351845185518651875188518951905191519251935194519551965197519851995200520152025203520452055206520752085209521052115212521352145215521652175218521952205221522252235224522552265227522852295230523152325233523452355236523752385239524052415242524352445245524652475248524952505251525252535254525552565257525852595260526152625263526452655266526752685269527052715272527352745275527652775278527952805281528252835284528552865287528852895290529152925293529452955296529752985299530053015302530353045305530653075308530953105311531253135314531553165317531853195320532153225323532453255326532753285329533053315332533353345335533653375338533953405341534253435344534553465347534853495350535153525353535453555356535753585359536053615362536353645365536653675368536953705371537253735374537553765377537853795380538153825383538453855386538753885389539053915392539353945395539653975398539954005401540254035404540554065407540854095410541154125413541454155416541754185419542054215422542354245425542654275428542954305431543254335434543554365437543854395440544154425443544454455446544754485449545054515452545354545455545654575458545954605461546254635464546554665467546854695470547154725473547454755476547754785479548054815482548354845485548654875488548954905491549254935494549554965497549854995500550155025503550455055506550755085509551055115512551355145515551655175518551955205521552255235524552555265527552855295530553155325533553455355536553755385539554055415542554355445545554655475548554955505551555255535554555555565557555855595560556155625563556455655566556755685569557055715572557355745575557655775578557955805581558255835584558555865587558855895590559155925593559455955596559755985599560056015602560356045605560656075608560956105611561256135614561556165617561856195620562156225623562456255626562756285629563056315632563356345635563656375638563956405641564256435644564556465647564856495650565156525653565456555656565756585659566056615662566356645665566656675668566956705671567256735674567556765677567856795680568156825683568456855686568756885689569056915692569356945695569656975698569957005701570257035704570557065707570857095710571157125713571457155716571757185719572057215722572357245725572657275728572957305731573257335734573557365737573857395740574157425743574457455746574757485749575057515752575357545755575657575758575957605761576257635764576557665767576857695770577157725773577457755776577757785779578057815782578357845785578657875788578957905791579257935794579557965797579857995800580158025803580458055806580758085809581058115812581358145815581658175818581958205821582258235824582558265827582858295830583158325833583458355836583758385839584058415842584358445845584658475848584958505851585258535854585558565857585858595860586158625863586458655866586758685869587058715872587358745875587658775878587958805881588258835884588558865887588858895890589158925893589458955896589758985899590059015902590359045905590659075908590959105911591259135914591559165917591859195920592159225923592459255926592759285929593059315932593359345935593659375938593959405941594259435944594559465947594859495950595159525953595459555956595759585959596059615962596359645965596659675968596959705971597259735974597559765977597859795980598159825983598459855986598759885989599059915992599359945995599659975998599960006001600260036004600560066007600860096010601160126013601460156016601760186019602060216022602360246025602660276028602960306031603260336034603560366037603860396040604160426043604460456046604760486049605060516052605360546055605660576058605960606061606260636064606560666067606860696070607160726073607460756076607760786079608060816082608360846085608660876088608960906091609260936094609560966097609860996100610161026103610461056106610761086109611061116112611361146115611661176118611961206121612261236124612561266127612861296130613161326133613461356136613761386139614061416142614361446145614661476148614961506151615261536154615561566157615861596160616161626163616461656166616761686169617061716172617361746175617661776178617961806181618261836184618561866187618861896190619161926193619461956196619761986199620062016202620362046205620662076208620962106211621262136214621562166217621862196220622162226223622462256226622762286229623062316232623362346235623662376238623962406241624262436244624562466247624862496250625162526253625462556256625762586259626062616262626362646265626662676268626962706271627262736274627562766277627862796280628162826283628462856286628762886289629062916292629362946295629662976298629963006301630263036304630563066307630863096310631163126313631463156316631763186319632063216322632363246325632663276328632963306331633263336334633563366337633863396340634163426343634463456346634763486349635063516352635363546355635663576358635963606361636263636364636563666367636863696370637163726373637463756376637763786379638063816382638363846385638663876388638963906391639263936394639563966397639863996400640164026403640464056406640764086409641064116412641364146415641664176418641964206421642264236424642564266427642864296430643164326433643464356436643764386439644064416442644364446445644664476448644964506451645264536454645564566457645864596460646164626463646464656466646764686469647064716472647364746475647664776478647964806481648264836484648564866487648864896490649164926493649464956496649764986499650065016502650365046505650665076508650965106511651265136514651565166517651865196520652165226523652465256526652765286529653065316532653365346535653665376538653965406541654265436544654565466547654865496550655165526553655465556556655765586559656065616562656365646565656665676568656965706571657265736574657565766577657865796580658165826583658465856586658765886589659065916592659365946595659665976598659966006601660266036604660566066607660866096610661166126613661466156616661766186619662066216622662366246625662666276628662966306631663266336634663566366637663866396640664166426643664466456646664766486649665066516652665366546655665666576658665966606661666266636664666566666667666866696670667166726673667466756676667766786679668066816682668366846685668666876688668966906691669266936694669566966697669866996700670167026703670467056706670767086709671067116712671367146715671667176718671967206721672267236724672567266727672867296730673167326733673467356736673767386739674067416742674367446745674667476748674967506751675267536754675567566757675867596760676167626763676467656766676767686769677067716772677367746775677667776778677967806781678267836784678567866787678867896790679167926793679467956796679767986799680068016802680368046805680668076808680968106811681268136814681568166817681868196820682168226823682468256826682768286829683068316832683368346835683668376838683968406841684268436844684568466847684868496850685168526853685468556856685768586859686068616862686368646865686668676868686968706871687268736874687568766877687868796880688168826883688468856886688768886889689068916892689368946895689668976898689969006901690269036904690569066907690869096910691169126913691469156916691769186919692069216922692369246925692669276928692969306931693269336934693569366937693869396940694169426943694469456946694769486949695069516952695369546955695669576958695969606961696269636964696569666967696869696970697169726973697469756976697769786979698069816982698369846985698669876988698969906991699269936994699569966997699869997000700170027003700470057006700770087009701070117012701370147015701670177018701970207021702270237024702570267027702870297030703170327033703470357036703770387039704070417042704370447045704670477048704970507051705270537054705570567057705870597060706170627063706470657066706770687069707070717072707370747075707670777078707970807081708270837084708570867087708870897090709170927093709470957096709770987099710071017102710371047105710671077108710971107111711271137114711571167117711871197120712171227123712471257126712771287129713071317132713371347135713671377138713971407141714271437144714571467147714871497150715171527153715471557156715771587159716071617162716371647165716671677168716971707171717271737174717571767177717871797180718171827183718471857186718771887189719071917192719371947195719671977198719972007201720272037204720572067207720872097210721172127213721472157216721772187219722072217222722372247225722672277228722972307231723272337234723572367237723872397240724172427243724472457246724772487249725072517252725372547255725672577258725972607261726272637264726572667267726872697270727172727273727472757276727772787279728072817282728372847285728672877288728972907291729272937294729572967297729872997300730173027303730473057306730773087309731073117312731373147315731673177318731973207321732273237324732573267327732873297330733173327333733473357336733773387339734073417342734373447345734673477348734973507351735273537354735573567357735873597360736173627363736473657366736773687369737073717372737373747375737673777378737973807381738273837384738573867387738873897390739173927393739473957396739773987399740074017402740374047405740674077408740974107411741274137414741574167417741874197420742174227423742474257426742774287429743074317432743374347435743674377438743974407441744274437444744574467447744874497450745174527453745474557456745774587459746074617462746374647465746674677468746974707471747274737474747574767477747874797480748174827483748474857486748774887489749074917492749374947495749674977498749975007501750275037504750575067507750875097510751175127513751475157516751775187519752075217522752375247525752675277528752975307531753275337534753575367537753875397540754175427543754475457546754775487549755075517552755375547555755675577558755975607561756275637564756575667567756875697570757175727573757475757576757775787579758075817582758375847585758675877588758975907591759275937594759575967597759875997600760176027603760476057606760776087609761076117612761376147615761676177618761976207621762276237624762576267627762876297630763176327633763476357636763776387639764076417642764376447645764676477648764976507651765276537654765576567657765876597660766176627663766476657666766776687669767076717672767376747675767676777678767976807681768276837684768576867687768876897690769176927693769476957696769776987699770077017702770377047705770677077708770977107711771277137714771577167717771877197720772177227723772477257726772777287729773077317732773377347735773677377738773977407741774277437744774577467747774877497750775177527753775477557756775777587759776077617762776377647765776677677768776977707771777277737774777577767777777877797780778177827783778477857786778777887789779077917792779377947795779677977798779978007801780278037804780578067807780878097810781178127813781478157816781778187819782078217822782378247825782678277828782978307831783278337834783578367837783878397840784178427843784478457846784778487849785078517852785378547855785678577858785978607861786278637864786578667867786878697870787178727873787478757876787778787879788078817882788378847885788678877888788978907891789278937894789578967897789878997900790179027903790479057906790779087909791079117912791379147915791679177918791979207921792279237924792579267927792879297930793179327933793479357936793779387939794079417942794379447945794679477948794979507951795279537954795579567957795879597960796179627963796479657966796779687969797079717972797379747975797679777978797979807981798279837984798579867987798879897990799179927993799479957996799779987999800080018002800380048005800680078008800980108011801280138014801580168017801880198020802180228023802480258026802780288029803080318032803380348035803680378038803980408041804280438044804580468047804880498050805180528053805480558056805780588059806080618062806380648065806680678068806980708071807280738074807580768077807880798080808180828083808480858086808780888089809080918092809380948095809680978098809981008101810281038104810581068107810881098110811181128113811481158116811781188119812081218122812381248125812681278128812981308131813281338134813581368137813881398140814181428143814481458146814781488149815081518152815381548155815681578158815981608161816281638164816581668167816881698170817181728173817481758176817781788179818081818182818381848185818681878188818981908191819281938194819581968197819881998200820182028203820482058206820782088209821082118212821382148215821682178218821982208221822282238224822582268227822882298230823182328233823482358236823782388239824082418242824382448245824682478248824982508251825282538254825582568257825882598260826182628263826482658266826782688269827082718272827382748275827682778278827982808281828282838284828582868287828882898290829182928293829482958296829782988299830083018302830383048305830683078308830983108311831283138314831583168317831883198320832183228323832483258326832783288329833083318332833383348335833683378338833983408341834283438344834583468347834883498350835183528353835483558356835783588359836083618362836383648365836683678368836983708371837283738374837583768377837883798380838183828383838483858386838783888389839083918392839383948395839683978398839984008401840284038404840584068407840884098410841184128413841484158416841784188419842084218422842384248425842684278428842984308431843284338434843584368437843884398440844184428443844484458446844784488449845084518452845384548455845684578458845984608461846284638464846584668467846884698470847184728473847484758476847784788479848084818482848384848485848684878488848984908491849284938494849584968497849884998500850185028503850485058506850785088509851085118512851385148515851685178518851985208521852285238524852585268527852885298530853185328533853485358536853785388539854085418542854385448545854685478548854985508551855285538554855585568557855885598560856185628563856485658566856785688569857085718572857385748575857685778578857985808581858285838584858585868587858885898590859185928593859485958596859785988599860086018602860386048605860686078608860986108611861286138614861586168617861886198620862186228623862486258626862786288629863086318632863386348635863686378638863986408641864286438644864586468647864886498650865186528653865486558656865786588659866086618662866386648665866686678668866986708671867286738674867586768677867886798680868186828683868486858686868786888689869086918692869386948695869686978698869987008701870287038704870587068707870887098710871187128713871487158716871787188719872087218722872387248725872687278728872987308731873287338734873587368737873887398740874187428743874487458746874787488749875087518752875387548755875687578758875987608761876287638764876587668767876887698770877187728773877487758776877787788779878087818782878387848785878687878788878987908791879287938794879587968797879887998800880188028803880488058806880788088809881088118812881388148815881688178818881988208821882288238824882588268827882888298830883188328833883488358836883788388839884088418842884388448845884688478848884988508851885288538854885588568857885888598860886188628863886488658866886788688869887088718872887388748875887688778878887988808881888288838884888588868887888888898890889188928893889488958896889788988899890089018902890389048905890689078908890989108911891289138914891589168917891889198920892189228923892489258926892789288929893089318932893389348935893689378938893989408941894289438944894589468947894889498950895189528953895489558956895789588959896089618962896389648965896689678968896989708971897289738974897589768977897889798980898189828983898489858986898789888989899089918992899389948995899689978998899990009001900290039004900590069007900890099010901190129013901490159016901790189019902090219022902390249025902690279028902990309031903290339034903590369037903890399040904190429043904490459046904790489049905090519052905390549055905690579058905990609061906290639064906590669067906890699070907190729073907490759076907790789079908090819082908390849085908690879088908990909091909290939094909590969097909890999100910191029103910491059106910791089109911091119112911391149115911691179118911991209121912291239124912591269127912891299130913191329133913491359136913791389139914091419142914391449145914691479148914991509151915291539154915591569157915891599160916191629163916491659166916791689169917091719172917391749175917691779178917991809181918291839184918591869187918891899190919191929193919491959196919791989199920092019202920392049205920692079208920992109211921292139214921592169217921892199220922192229223922492259226922792289229923092319232923392349235923692379238923992409241924292439244924592469247924892499250925192529253925492559256925792589259926092619262926392649265926692679268926992709271927292739274927592769277927892799280928192829283928492859286928792889289929092919292929392949295929692979298929993009301930293039304930593069307930893099310931193129313931493159316931793189319932093219322932393249325932693279328932993309331933293339334933593369337933893399340934193429343934493459346934793489349935093519352935393549355935693579358935993609361936293639364936593669367936893699370937193729373937493759376937793789379938093819382938393849385938693879388938993909391939293939394939593969397939893999400940194029403940494059406940794089409941094119412941394149415941694179418941994209421942294239424942594269427942894299430943194329433943494359436943794389439944094419442944394449445944694479448944994509451945294539454945594569457945894599460946194629463946494659466946794689469947094719472947394749475947694779478947994809481948294839484948594869487948894899490949194929493949494959496949794989499950095019502950395049505950695079508950995109511951295139514951595169517951895199520952195229523952495259526952795289529953095319532953395349535953695379538953995409541954295439544954595469547954895499550955195529553955495559556955795589559956095619562956395649565956695679568956995709571957295739574957595769577957895799580958195829583958495859586958795889589959095919592959395949595959695979598959996009601960296039604960596069607960896099610961196129613961496159616961796189619962096219622962396249625962696279628962996309631963296339634963596369637963896399640964196429643964496459646964796489649965096519652965396549655965696579658965996609661966296639664966596669667966896699670967196729673967496759676967796789679968096819682968396849685968696879688968996909691969296939694969596969697969896999700970197029703970497059706970797089709971097119712971397149715971697179718971997209721972297239724972597269727972897299730973197329733973497359736973797389739974097419742974397449745974697479748974997509751975297539754975597569757975897599760976197629763976497659766976797689769977097719772977397749775977697779778977997809781978297839784978597869787978897899790979197929793979497959796979797989799980098019802980398049805980698079808980998109811981298139814981598169817981898199820982198229823982498259826982798289829983098319832983398349835983698379838983998409841984298439844984598469847984898499850985198529853985498559856985798589859986098619862986398649865986698679868986998709871987298739874987598769877987898799880988198829883988498859886988798889889989098919892989398949895989698979898989999009901990299039904990599069907990899099910991199129913991499159916991799189919992099219922992399249925992699279928992999309931993299339934993599369937993899399940994199429943994499459946994799489949995099519952995399549955995699579958995999609961996299639964996599669967996899699970997199729973997499759976997799789979998099819982998399849985998699879988998999909991999299939994999599969997999899991000010001100021000310004100051000610007100081000910010100111001210013100141001510016100171001810019100201002110022100231002410025100261002710028100291003010031100321003310034100351003610037100381003910040100411004210043100441004510046100471004810049100501005110052100531005410055100561005710058100591006010061100621006310064100651006610067100681006910070100711007210073100741007510076100771007810079100801008110082100831008410085100861008710088100891009010091100921009310094100951009610097100981009910100101011010210103101041010510106101071010810109101101011110112101131011410115101161011710118101191012010121101221012310124101251012610127101281012910130101311013210133101341013510136101371013810139101401014110142101431014410145101461014710148101491015010151101521015310154101551015610157101581015910160101611016210163101641016510166101671016810169101701017110172101731017410175101761017710178101791018010181101821018310184101851018610187101881018910190101911019210193101941019510196101971019810199102001020110202102031020410205102061020710208102091021010211102121021310214102151021610217102181021910220102211022210223102241022510226102271022810229102301023110232102331023410235102361023710238102391024010241102421024310244102451024610247102481024910250102511025210253102541025510256102571025810259102601026110262102631026410265102661026710268102691027010271102721027310274102751027610277102781027910280102811028210283102841028510286102871028810289102901029110292102931029410295102961029710298102991030010301103021030310304103051030610307103081030910310103111031210313103141031510316103171031810319103201032110322103231032410325103261032710328103291033010331103321033310334103351033610337103381033910340103411034210343103441034510346103471034810349103501035110352103531035410355103561035710358103591036010361103621036310364103651036610367103681036910370103711037210373103741037510376103771037810379103801038110382103831038410385103861038710388103891039010391103921039310394103951039610397103981039910400104011040210403104041040510406104071040810409104101041110412104131041410415104161041710418104191042010421104221042310424104251042610427104281042910430104311043210433104341043510436104371043810439104401044110442104431044410445104461044710448104491045010451104521045310454104551045610457104581045910460104611046210463104641046510466104671046810469104701047110472104731047410475104761047710478104791048010481104821048310484104851048610487104881048910490104911049210493104941049510496104971049810499105001050110502105031050410505105061050710508105091051010511105121051310514105151051610517105181051910520105211052210523105241052510526105271052810529105301053110532105331053410535105361053710538105391054010541105421054310544105451054610547105481054910550105511055210553105541055510556105571055810559105601056110562105631056410565105661056710568105691057010571105721057310574105751057610577105781057910580105811058210583105841058510586105871058810589105901059110592105931059410595105961059710598105991060010601106021060310604106051060610607106081060910610106111061210613106141061510616106171061810619106201062110622106231062410625106261062710628106291063010631106321063310634106351063610637106381063910640106411064210643106441064510646106471064810649106501065110652106531065410655106561065710658106591066010661106621066310664106651066610667106681066910670106711067210673106741067510676106771067810679106801068110682106831068410685106861068710688106891069010691106921069310694106951069610697106981069910700107011070210703107041070510706107071070810709107101071110712107131071410715107161071710718107191072010721107221072310724107251072610727107281072910730107311073210733107341073510736107371073810739107401074110742107431074410745107461074710748107491075010751107521075310754107551075610757107581075910760107611076210763107641076510766107671076810769107701077110772107731077410775107761077710778107791078010781107821078310784107851078610787107881078910790107911079210793107941079510796107971079810799108001080110802108031080410805108061080710808108091081010811108121081310814108151081610817108181081910820108211082210823108241082510826108271082810829108301083110832108331083410835108361083710838108391084010841108421084310844108451084610847108481084910850108511085210853108541085510856108571085810859108601086110862108631086410865108661086710868108691087010871108721087310874108751087610877108781087910880108811088210883108841088510886108871088810889108901089110892108931089410895108961089710898108991090010901109021090310904109051090610907109081090910910109111091210913109141091510916109171091810919109201092110922109231092410925109261092710928109291093010931109321093310934109351093610937109381093910940109411094210943109441094510946109471094810949109501095110952109531095410955109561095710958109591096010961109621096310964109651096610967109681096910970109711097210973109741097510976109771097810979109801098110982109831098410985109861098710988109891099010991109921099310994109951099610997109981099911000110011100211003110041100511006110071100811009110101101111012110131101411015110161101711018110191102011021110221102311024110251102611027110281102911030110311103211033110341103511036110371103811039110401104111042110431104411045110461104711048110491105011051110521105311054110551105611057110581105911060110611106211063110641106511066110671106811069110701107111072110731107411075110761107711078110791108011081110821108311084110851108611087110881108911090110911109211093110941109511096110971109811099111001110111102111031110411105111061110711108111091111011111111121111311114111151111611117111181111911120111211112211123111241112511126111271112811129111301113111132111331113411135111361113711138111391114011141111421114311144111451114611147111481114911150111511115211153111541115511156111571115811159111601116111162111631116411165111661116711168111691117011171111721117311174111751117611177111781117911180111811118211183111841118511186111871118811189111901119111192111931119411195111961119711198111991120011201112021120311204112051120611207112081120911210112111121211213112141121511216112171121811219112201122111222112231122411225112261122711228112291123011231112321123311234112351123611237112381123911240112411124211243112441124511246112471124811249112501125111252112531125411255112561125711258112591126011261112621126311264112651126611267112681126911270112711127211273112741127511276112771127811279112801128111282112831128411285112861128711288112891129011291112921129311294112951129611297112981129911300113011130211303113041130511306113071130811309113101131111312113131131411315113161131711318113191132011321113221132311324113251132611327113281132911330113311133211333113341133511336113371133811339113401134111342113431134411345113461134711348113491135011351113521135311354113551135611357113581135911360113611136211363113641136511366113671136811369113701137111372113731137411375113761137711378113791138011381113821138311384113851138611387113881138911390113911139211393113941139511396113971139811399114001140111402114031140411405114061140711408114091141011411114121141311414114151141611417114181141911420114211142211423114241142511426114271142811429114301143111432114331143411435114361143711438114391144011441114421144311444114451144611447114481144911450114511145211453114541145511456114571145811459114601146111462114631146411465114661146711468114691147011471114721147311474114751147611477114781147911480114811148211483114841148511486114871148811489114901149111492114931149411495114961149711498114991150011501115021150311504115051150611507115081150911510115111151211513115141151511516115171151811519115201152111522115231152411525115261152711528115291153011531115321153311534115351153611537115381153911540115411154211543115441154511546115471154811549115501155111552115531155411555115561155711558115591156011561115621156311564115651156611567115681156911570115711157211573115741157511576115771157811579115801158111582115831158411585115861158711588115891159011591115921159311594115951159611597115981159911600116011160211603116041160511606116071160811609116101161111612116131161411615116161161711618116191162011621116221162311624116251162611627116281162911630116311163211633116341163511636116371163811639116401164111642116431164411645116461164711648116491165011651116521165311654116551165611657116581165911660116611166211663116641166511666116671166811669116701167111672116731167411675116761167711678116791168011681116821168311684116851168611687116881168911690116911169211693116941169511696116971169811699117001170111702117031170411705117061170711708117091171011711117121171311714117151171611717117181171911720117211172211723117241172511726117271172811729117301173111732117331173411735117361173711738117391174011741117421174311744117451174611747117481174911750117511175211753117541175511756117571175811759117601176111762117631176411765117661176711768117691177011771117721177311774117751177611777117781177911780117811178211783117841178511786117871178811789117901179111792117931179411795117961179711798117991180011801118021180311804118051180611807118081180911810118111181211813118141181511816118171181811819118201182111822118231182411825118261182711828118291183011831118321183311834118351183611837118381183911840118411184211843118441184511846118471184811849118501185111852118531185411855118561185711858118591186011861118621186311864118651186611867118681186911870118711187211873118741187511876118771187811879118801188111882118831188411885118861188711888118891189011891118921189311894118951189611897118981189911900119011190211903119041190511906119071190811909119101191111912119131191411915119161191711918119191192011921119221192311924119251192611927119281192911930119311193211933119341193511936119371193811939119401194111942119431194411945119461194711948119491195011951119521195311954119551195611957119581195911960119611196211963119641196511966119671196811969119701197111972119731197411975119761197711978119791198011981119821198311984119851198611987119881198911990119911199211993119941199511996119971199811999120001200112002120031200412005120061200712008120091201012011120121201312014120151201612017120181201912020120211202212023120241202512026120271202812029120301203112032120331203412035120361203712038120391204012041120421204312044120451204612047120481204912050120511205212053120541205512056120571205812059120601206112062120631206412065120661206712068120691207012071120721207312074120751207612077120781207912080120811208212083120841208512086120871208812089120901209112092120931209412095120961209712098120991210012101121021210312104121051210612107121081210912110121111211212113121141211512116121171211812119121201212112122121231212412125121261212712128121291213012131121321213312134121351213612137121381213912140121411214212143121441214512146121471214812149121501215112152121531215412155121561215712158121591216012161121621216312164121651216612167121681216912170121711217212173121741217512176121771217812179121801218112182121831218412185121861218712188121891219012191121921219312194121951219612197121981219912200122011220212203122041220512206122071220812209122101221112212122131221412215122161221712218122191222012221122221222312224122251222612227122281222912230122311223212233122341223512236122371223812239122401224112242122431224412245122461224712248122491225012251122521225312254122551225612257122581225912260122611226212263122641226512266122671226812269122701227112272122731227412275122761227712278122791228012281122821228312284122851228612287122881228912290122911229212293122941229512296122971229812299123001230112302123031230412305123061230712308123091231012311123121231312314123151231612317123181231912320123211232212323123241232512326123271232812329123301233112332123331233412335123361233712338123391234012341123421234312344123451234612347123481234912350123511235212353123541235512356123571235812359123601236112362123631236412365123661236712368123691237012371123721237312374123751237612377123781237912380123811238212383123841238512386123871238812389123901239112392123931239412395123961239712398123991240012401124021240312404124051240612407124081240912410124111241212413124141241512416124171241812419124201242112422124231242412425124261242712428124291243012431124321243312434124351243612437124381243912440124411244212443124441244512446124471244812449124501245112452124531245412455124561245712458124591246012461124621246312464124651246612467124681246912470124711247212473124741247512476124771247812479124801248112482124831248412485124861248712488124891249012491124921249312494124951249612497124981249912500125011250212503125041250512506125071250812509125101251112512125131251412515125161251712518125191252012521125221252312524125251252612527125281252912530125311253212533125341253512536125371253812539125401254112542125431254412545125461254712548125491255012551125521255312554125551255612557125581255912560125611256212563125641256512566125671256812569125701257112572125731257412575125761257712578125791258012581125821258312584125851258612587125881258912590125911259212593125941259512596125971259812599126001260112602126031260412605126061260712608126091261012611126121261312614126151261612617126181261912620126211262212623126241262512626126271262812629126301263112632126331263412635126361263712638126391264012641126421264312644126451264612647126481264912650126511265212653126541265512656126571265812659126601266112662126631266412665126661266712668126691267012671126721267312674126751267612677126781267912680126811268212683126841268512686126871268812689126901269112692126931269412695126961269712698126991270012701127021270312704127051270612707127081270912710127111271212713127141271512716127171271812719127201272112722127231272412725127261272712728127291273012731127321273312734127351273612737127381273912740127411274212743127441274512746127471274812749127501275112752127531275412755127561275712758127591276012761127621276312764127651276612767127681276912770127711277212773127741277512776127771277812779127801278112782127831278412785127861278712788127891279012791127921279312794127951279612797127981279912800128011280212803128041280512806128071280812809128101281112812128131281412815128161281712818128191282012821128221282312824128251282612827128281282912830128311283212833128341283512836128371283812839128401284112842128431284412845128461284712848128491285012851128521285312854128551285612857128581285912860128611286212863128641286512866128671286812869128701287112872128731287412875128761287712878128791288012881128821288312884128851288612887128881288912890128911289212893128941289512896128971289812899129001290112902129031290412905129061290712908129091291012911129121291312914129151291612917129181291912920129211292212923129241292512926129271292812929129301293112932129331293412935129361293712938129391294012941129421294312944129451294612947129481294912950129511295212953129541295512956129571295812959129601296112962129631296412965129661296712968129691297012971129721297312974129751297612977129781297912980129811298212983129841298512986129871298812989129901299112992129931299412995129961299712998129991300013001130021300313004130051300613007130081300913010130111301213013130141301513016130171301813019130201302113022130231302413025130261302713028130291303013031130321303313034130351303613037130381303913040130411304213043130441304513046130471304813049130501305113052130531305413055130561305713058130591306013061130621306313064130651306613067130681306913070130711307213073130741307513076130771307813079130801308113082130831308413085130861308713088130891309013091130921309313094130951309613097130981309913100131011310213103131041310513106131071310813109131101311113112131131311413115131161311713118131191312013121131221312313124131251312613127131281312913130131311313213133131341313513136131371313813139131401314113142131431314413145131461314713148131491315013151131521315313154131551315613157131581315913160131611316213163131641316513166131671316813169131701317113172131731317413175131761317713178131791318013181131821318313184131851318613187131881318913190131911319213193131941319513196131971319813199132001320113202132031320413205132061320713208132091321013211132121321313214132151321613217132181321913220132211322213223132241322513226132271322813229132301323113232132331323413235132361323713238132391324013241132421324313244132451324613247132481324913250132511325213253132541325513256132571325813259132601326113262132631326413265132661326713268132691327013271132721327313274132751327613277132781327913280132811328213283132841328513286132871328813289132901329113292132931329413295132961329713298132991330013301133021330313304133051330613307133081330913310133111331213313133141331513316133171331813319133201332113322133231332413325133261332713328133291333013331133321333313334133351333613337133381333913340133411334213343133441334513346133471334813349133501335113352133531335413355133561335713358133591336013361133621336313364133651336613367133681336913370133711337213373133741337513376133771337813379133801338113382133831338413385133861338713388133891339013391133921339313394133951339613397133981339913400134011340213403134041340513406134071340813409134101341113412134131341413415134161341713418134191342013421134221342313424134251342613427134281342913430134311343213433134341343513436134371343813439134401344113442134431344413445134461344713448134491345013451134521345313454134551345613457134581345913460134611346213463134641346513466134671346813469134701347113472134731347413475134761347713478134791348013481134821348313484134851348613487134881348913490134911349213493134941349513496134971349813499135001350113502135031350413505135061350713508135091351013511135121351313514135151351613517135181351913520135211352213523135241352513526135271352813529135301353113532135331353413535135361353713538135391354013541135421354313544135451354613547135481354913550135511355213553135541355513556135571355813559135601356113562135631356413565135661356713568135691357013571135721357313574135751357613577135781357913580135811358213583135841358513586135871358813589135901359113592135931359413595135961359713598135991360013601136021360313604136051360613607136081360913610136111361213613136141361513616136171361813619136201362113622136231362413625136261362713628136291363013631136321363313634136351363613637136381363913640136411364213643136441364513646136471364813649136501365113652136531365413655136561365713658136591366013661136621366313664136651366613667136681366913670136711367213673136741367513676136771367813679136801368113682136831368413685136861368713688136891369013691136921369313694136951369613697136981369913700137011370213703137041370513706137071370813709137101371113712137131371413715137161371713718137191372013721137221372313724137251372613727137281372913730137311373213733137341373513736137371373813739137401374113742137431374413745137461374713748137491375013751137521375313754137551375613757137581375913760137611376213763137641376513766137671376813769137701377113772137731377413775137761377713778137791378013781137821378313784137851378613787137881378913790137911379213793137941379513796137971379813799138001380113802138031380413805138061380713808138091381013811138121381313814138151381613817138181381913820138211382213823138241382513826138271382813829138301383113832138331383413835138361383713838138391384013841138421384313844138451384613847138481384913850138511385213853138541385513856138571385813859138601386113862138631386413865138661386713868138691387013871138721387313874138751387613877138781387913880138811388213883138841388513886138871388813889138901389113892138931389413895138961389713898138991390013901139021390313904139051390613907139081390913910139111391213913139141391513916139171391813919139201392113922139231392413925139261392713928139291393013931139321393313934139351393613937139381393913940139411394213943139441394513946139471394813949139501395113952139531395413955139561395713958139591396013961139621396313964139651396613967139681396913970139711397213973139741397513976139771397813979139801398113982139831398413985139861398713988139891399013991139921399313994139951399613997139981399914000140011400214003140041400514006140071400814009140101401114012140131401414015140161401714018140191402014021140221402314024140251402614027140281402914030140311403214033140341403514036140371403814039140401404114042140431404414045140461404714048140491405014051140521405314054140551405614057140581405914060140611406214063140641406514066140671406814069140701407114072140731407414075140761407714078140791408014081140821408314084140851408614087140881408914090140911409214093140941409514096140971409814099141001410114102141031410414105141061410714108141091411014111141121411314114141151411614117141181411914120141211412214123141241412514126141271412814129141301413114132141331413414135141361413714138141391414014141141421414314144141451414614147141481414914150141511415214153141541415514156141571415814159141601416114162141631416414165141661416714168141691417014171141721417314174141751417614177141781417914180141811418214183141841418514186141871418814189141901419114192141931419414195141961419714198141991420014201142021420314204142051420614207142081420914210142111421214213142141421514216142171421814219142201422114222142231422414225142261422714228142291423014231142321423314234142351423614237142381423914240142411424214243142441424514246142471424814249142501425114252142531425414255142561425714258142591426014261142621426314264142651426614267142681426914270142711427214273142741427514276142771427814279142801428114282142831428414285142861428714288142891429014291142921429314294142951429614297142981429914300143011430214303143041430514306143071430814309143101431114312143131431414315143161431714318143191432014321143221432314324143251432614327143281432914330143311433214333143341433514336143371433814339143401434114342143431434414345143461434714348143491435014351143521435314354143551435614357143581435914360143611436214363143641436514366143671436814369143701437114372143731437414375143761437714378143791438014381143821438314384143851438614387143881438914390143911439214393143941439514396143971439814399144001440114402144031440414405144061440714408144091441014411144121441314414144151441614417144181441914420144211442214423144241442514426144271442814429144301443114432144331443414435144361443714438144391444014441144421444314444144451444614447144481444914450144511445214453144541445514456144571445814459144601446114462144631446414465144661446714468144691447014471144721447314474144751447614477144781447914480144811448214483144841448514486144871448814489144901449114492144931449414495144961449714498144991450014501145021450314504145051450614507145081450914510145111451214513145141451514516145171451814519145201452114522145231452414525145261452714528145291453014531145321453314534145351453614537145381453914540145411454214543145441454514546145471454814549145501455114552145531455414555145561455714558145591456014561145621456314564145651456614567145681456914570145711457214573145741457514576145771457814579145801458114582145831458414585145861458714588145891459014591145921459314594145951459614597145981459914600146011460214603146041460514606146071460814609146101461114612146131461414615146161461714618146191462014621146221462314624146251462614627146281462914630146311463214633146341463514636146371463814639146401464114642146431464414645146461464714648146491465014651146521465314654146551465614657146581465914660146611466214663146641466514666146671466814669146701467114672146731467414675146761467714678146791468014681146821468314684146851468614687146881468914690146911469214693146941469514696146971469814699147001470114702147031470414705147061470714708147091471014711147121471314714147151471614717147181471914720147211472214723147241472514726147271472814729147301473114732147331473414735147361473714738147391474014741147421474314744147451474614747147481474914750147511475214753147541475514756147571475814759147601476114762147631476414765147661476714768147691477014771147721477314774147751477614777147781477914780147811478214783147841478514786147871478814789147901479114792147931479414795147961479714798147991480014801148021480314804148051480614807148081480914810148111481214813148141481514816148171481814819148201482114822148231482414825148261482714828148291483014831148321483314834148351483614837148381483914840148411484214843148441484514846148471484814849148501485114852148531485414855148561485714858148591486014861148621486314864148651486614867148681486914870148711487214873148741487514876148771487814879148801488114882148831488414885148861488714888148891489014891148921489314894148951489614897148981489914900149011490214903149041490514906149071490814909149101491114912149131491414915149161491714918149191492014921149221492314924149251492614927149281492914930149311493214933149341493514936149371493814939149401494114942149431494414945149461494714948149491495014951149521495314954149551495614957149581495914960149611496214963149641496514966149671496814969149701497114972149731497414975149761497714978149791498014981149821498314984149851498614987149881498914990149911499214993149941499514996149971499814999150001500115002150031500415005150061500715008150091501015011150121501315014150151501615017150181501915020150211502215023150241502515026150271502815029150301503115032150331503415035150361503715038150391504015041150421504315044150451504615047150481504915050150511505215053150541505515056150571505815059150601506115062150631506415065150661506715068150691507015071150721507315074150751507615077150781507915080150811508215083150841508515086150871508815089150901509115092150931509415095150961509715098150991510015101151021510315104151051510615107151081510915110151111511215113151141511515116151171511815119151201512115122151231512415125151261512715128151291513015131151321513315134151351513615137151381513915140151411514215143151441514515146151471514815149151501515115152151531515415155151561515715158151591516015161151621516315164151651516615167151681516915170151711517215173151741517515176151771517815179151801518115182151831518415185151861518715188151891519015191151921519315194151951519615197151981519915200152011520215203152041520515206152071520815209152101521115212152131521415215152161521715218152191522015221152221522315224152251522615227152281522915230152311523215233152341523515236152371523815239152401524115242152431524415245152461524715248152491525015251152521525315254152551525615257152581525915260152611526215263152641526515266152671526815269152701527115272152731527415275152761527715278152791528015281152821528315284152851528615287152881528915290152911529215293152941529515296152971529815299153001530115302153031530415305153061530715308153091531015311153121531315314153151531615317153181531915320153211532215323153241532515326153271532815329153301533115332153331533415335153361533715338153391534015341153421534315344153451534615347153481534915350153511535215353153541535515356153571535815359153601536115362153631536415365153661536715368153691537015371153721537315374153751537615377153781537915380153811538215383153841538515386153871538815389153901539115392153931539415395153961539715398153991540015401154021540315404154051540615407154081540915410154111541215413154141541515416154171541815419154201542115422154231542415425154261542715428154291543015431154321543315434154351543615437154381543915440154411544215443154441544515446154471544815449154501545115452154531545415455154561545715458154591546015461154621546315464154651546615467154681546915470154711547215473154741547515476154771547815479154801548115482154831548415485154861548715488154891549015491154921549315494154951549615497154981549915500155011550215503155041550515506155071550815509155101551115512155131551415515155161551715518155191552015521155221552315524155251552615527155281552915530155311553215533155341553515536155371553815539155401554115542155431554415545155461554715548155491555015551155521555315554155551555615557155581555915560155611556215563155641556515566155671556815569155701557115572155731557415575155761557715578155791558015581155821558315584155851558615587155881558915590155911559215593155941559515596155971559815599156001560115602156031560415605156061560715608156091561015611156121561315614156151561615617156181561915620156211562215623156241562515626156271562815629156301563115632156331563415635156361563715638156391564015641156421564315644156451564615647156481564915650156511565215653156541565515656156571565815659156601566115662156631566415665156661566715668156691567015671156721567315674156751567615677156781567915680156811568215683156841568515686156871568815689156901569115692156931569415695156961569715698156991570015701157021570315704157051570615707157081570915710157111571215713157141571515716157171571815719157201572115722157231572415725157261572715728157291573015731157321573315734157351573615737157381573915740157411574215743157441574515746157471574815749157501575115752157531575415755157561575715758157591576015761157621576315764157651576615767157681576915770157711577215773157741577515776157771577815779157801578115782157831578415785157861578715788157891579015791157921579315794157951579615797157981579915800158011580215803158041580515806158071580815809158101581115812158131581415815158161581715818158191582015821158221582315824158251582615827158281582915830158311583215833158341583515836158371583815839158401584115842158431584415845158461584715848158491585015851158521585315854158551585615857158581585915860158611586215863158641586515866158671586815869158701587115872158731587415875158761587715878158791588015881158821588315884158851588615887158881588915890158911589215893158941589515896158971589815899159001590115902159031590415905159061590715908159091591015911159121591315914159151591615917159181591915920159211592215923159241592515926159271592815929159301593115932159331593415935159361593715938159391594015941159421594315944159451594615947159481594915950159511595215953159541595515956159571595815959159601596115962159631596415965159661596715968159691597015971159721597315974159751597615977159781597915980159811598215983159841598515986159871598815989159901599115992159931599415995159961599715998159991600016001160021600316004160051600616007160081600916010160111601216013160141601516016160171601816019160201602116022160231602416025160261602716028160291603016031160321603316034160351603616037160381603916040160411604216043160441604516046160471604816049160501605116052160531605416055160561605716058160591606016061160621606316064160651606616067160681606916070160711607216073160741607516076160771607816079160801608116082160831608416085160861608716088160891609016091160921609316094160951609616097160981609916100161011610216103161041610516106161071610816109161101611116112161131611416115161161611716118161191612016121161221612316124161251612616127161281612916130161311613216133161341613516136161371613816139161401614116142161431614416145161461614716148161491615016151161521615316154161551615616157161581615916160161611616216163161641616516166161671616816169161701617116172161731617416175161761617716178161791618016181161821618316184161851618616187161881618916190161911619216193161941619516196161971619816199162001620116202162031620416205162061620716208162091621016211162121621316214162151621616217162181621916220162211622216223162241622516226162271622816229162301623116232162331623416235162361623716238162391624016241162421624316244162451624616247162481624916250162511625216253162541625516256162571625816259162601626116262162631626416265162661626716268162691627016271162721627316274162751627616277162781627916280162811628216283162841628516286162871628816289162901629116292162931629416295162961629716298162991630016301163021630316304163051630616307163081630916310163111631216313163141631516316163171631816319163201632116322163231632416325163261632716328163291633016331163321633316334163351633616337163381633916340163411634216343163441634516346163471634816349163501635116352163531635416355163561635716358163591636016361163621636316364163651636616367163681636916370163711637216373163741637516376163771637816379163801638116382163831638416385163861638716388163891639016391163921639316394163951639616397163981639916400164011640216403164041640516406164071640816409164101641116412164131641416415164161641716418164191642016421164221642316424164251642616427164281642916430164311643216433164341643516436164371643816439164401644116442164431644416445164461644716448164491645016451164521645316454164551645616457164581645916460164611646216463164641646516466164671646816469164701647116472164731647416475164761647716478164791648016481164821648316484164851648616487164881648916490164911649216493164941649516496164971649816499165001650116502165031650416505165061650716508165091651016511165121651316514165151651616517165181651916520165211652216523165241652516526165271652816529165301653116532165331653416535165361653716538165391654016541165421654316544165451654616547165481654916550165511655216553165541655516556165571655816559165601656116562165631656416565165661656716568165691657016571165721657316574165751657616577165781657916580165811658216583165841658516586165871658816589165901659116592165931659416595165961659716598165991660016601166021660316604166051660616607166081660916610166111661216613166141661516616166171661816619166201662116622166231662416625166261662716628166291663016631166321663316634166351663616637166381663916640166411664216643166441664516646166471664816649166501665116652166531665416655166561665716658166591666016661166621666316664166651666616667166681666916670166711667216673166741667516676166771667816679166801668116682166831668416685166861668716688166891669016691166921669316694166951669616697166981669916700167011670216703167041670516706167071670816709167101671116712167131671416715167161671716718167191672016721167221672316724167251672616727167281672916730167311673216733167341673516736167371673816739167401674116742167431674416745167461674716748167491675016751167521675316754167551675616757167581675916760167611676216763167641676516766167671676816769167701677116772167731677416775167761677716778167791678016781167821678316784167851678616787167881678916790167911679216793167941679516796167971679816799168001680116802168031680416805168061680716808168091681016811168121681316814168151681616817168181681916820168211682216823168241682516826168271682816829168301683116832168331683416835168361683716838168391684016841168421684316844168451684616847168481684916850168511685216853168541685516856168571685816859168601686116862168631686416865168661686716868168691687016871168721687316874168751687616877168781687916880168811688216883168841688516886168871688816889168901689116892168931689416895168961689716898168991690016901169021690316904169051690616907169081690916910169111691216913169141691516916169171691816919169201692116922169231692416925169261692716928169291693016931169321693316934169351693616937169381693916940169411694216943169441694516946169471694816949169501695116952169531695416955169561695716958169591696016961169621696316964169651696616967169681696916970169711697216973169741697516976169771697816979169801698116982169831698416985169861698716988169891699016991169921699316994169951699616997169981699917000170011700217003170041700517006170071700817009170101701117012170131701417015170161701717018170191702017021170221702317024170251702617027170281702917030170311703217033170341703517036170371703817039170401704117042170431704417045170461704717048170491705017051170521705317054170551705617057170581705917060170611706217063170641706517066170671706817069170701707117072170731707417075170761707717078170791708017081170821708317084170851708617087170881708917090170911709217093170941709517096170971709817099171001710117102171031710417105171061710717108171091711017111171121711317114171151711617117171181711917120171211712217123171241712517126171271712817129171301713117132171331713417135171361713717138171391714017141171421714317144171451714617147171481714917150171511715217153171541715517156171571715817159171601716117162171631716417165171661716717168171691717017171171721717317174171751717617177171781717917180171811718217183171841718517186171871718817189171901719117192171931719417195171961719717198171991720017201172021720317204172051720617207172081720917210172111721217213172141721517216172171721817219172201722117222172231722417225172261722717228172291723017231172321723317234172351723617237172381723917240172411724217243172441724517246172471724817249172501725117252172531725417255172561725717258172591726017261172621726317264172651726617267172681726917270172711727217273172741727517276172771727817279172801728117282172831728417285172861728717288172891729017291172921729317294172951729617297172981729917300173011730217303173041730517306173071730817309173101731117312173131731417315173161731717318173191732017321173221732317324173251732617327173281732917330173311733217333173341733517336173371733817339173401734117342173431734417345173461734717348173491735017351173521735317354173551735617357173581735917360173611736217363173641736517366173671736817369173701737117372173731737417375173761737717378173791738017381173821738317384173851738617387173881738917390173911739217393173941739517396173971739817399174001740117402174031740417405174061740717408174091741017411174121741317414174151741617417174181741917420174211742217423174241742517426174271742817429174301743117432174331743417435174361743717438174391744017441174421744317444174451744617447174481744917450174511745217453174541745517456174571745817459174601746117462174631746417465174661746717468174691747017471174721747317474174751747617477174781747917480174811748217483174841748517486174871748817489174901749117492174931749417495174961749717498174991750017501175021750317504175051750617507175081750917510175111751217513175141751517516175171751817519175201752117522175231752417525175261752717528175291753017531175321753317534175351753617537175381753917540175411754217543175441754517546175471754817549175501755117552175531755417555175561755717558175591756017561175621756317564175651756617567175681756917570175711757217573175741757517576175771757817579175801758117582175831758417585175861758717588175891759017591175921759317594175951759617597175981759917600176011760217603176041760517606176071760817609176101761117612176131761417615176161761717618176191762017621176221762317624176251762617627176281762917630176311763217633176341763517636176371763817639176401764117642176431764417645176461764717648176491765017651176521765317654176551765617657176581765917660176611766217663176641766517666176671766817669176701767117672176731767417675176761767717678176791768017681176821768317684176851768617687176881768917690176911769217693176941769517696176971769817699177001770117702177031770417705177061770717708177091771017711177121771317714177151771617717177181771917720177211772217723177241772517726177271772817729177301773117732177331773417735177361773717738177391774017741177421774317744177451774617747177481774917750177511775217753177541775517756177571775817759177601776117762177631776417765177661776717768177691777017771177721777317774177751777617777177781777917780177811778217783177841778517786177871778817789177901779117792177931779417795177961779717798177991780017801178021780317804178051780617807178081780917810178111781217813178141781517816178171781817819178201782117822178231782417825178261782717828178291783017831178321783317834178351783617837178381783917840178411784217843178441784517846178471784817849178501785117852178531785417855178561785717858178591786017861178621786317864178651786617867178681786917870178711787217873178741787517876178771787817879178801788117882178831788417885178861788717888178891789017891178921789317894178951789617897178981789917900179011790217903179041790517906179071790817909179101791117912179131791417915179161791717918179191792017921179221792317924179251792617927179281792917930179311793217933179341793517936179371793817939179401794117942179431794417945179461794717948179491795017951179521795317954179551795617957179581795917960179611796217963179641796517966179671796817969179701797117972179731797417975179761797717978179791798017981179821798317984179851798617987179881798917990179911799217993179941799517996179971799817999180001800118002180031800418005180061800718008180091801018011180121801318014180151801618017180181801918020180211802218023180241802518026180271802818029180301803118032180331803418035180361803718038180391804018041180421804318044180451804618047180481804918050180511805218053180541805518056180571805818059180601806118062180631806418065180661806718068180691807018071180721807318074180751807618077180781807918080180811808218083180841808518086180871808818089180901809118092180931809418095180961809718098180991810018101181021810318104181051810618107181081810918110181111811218113181141811518116181171811818119181201812118122181231812418125181261812718128181291813018131181321813318134181351813618137181381813918140181411814218143181441814518146181471814818149181501815118152181531815418155181561815718158181591816018161181621816318164181651816618167181681816918170181711817218173181741817518176181771817818179181801818118182181831818418185181861818718188181891819018191181921819318194181951819618197181981819918200182011820218203182041820518206182071820818209182101821118212182131821418215182161821718218182191822018221182221822318224182251822618227182281822918230182311823218233182341823518236182371823818239182401824118242182431824418245182461824718248182491825018251182521825318254182551825618257182581825918260182611826218263182641826518266182671826818269182701827118272182731827418275182761827718278182791828018281182821828318284182851828618287182881828918290182911829218293182941829518296182971829818299183001830118302183031830418305183061830718308183091831018311183121831318314183151831618317183181831918320183211832218323183241832518326183271832818329183301833118332183331833418335183361833718338183391834018341183421834318344183451834618347183481834918350183511835218353183541835518356183571835818359183601836118362183631836418365183661836718368183691837018371183721837318374183751837618377183781837918380183811838218383183841838518386183871838818389183901839118392183931839418395183961839718398183991840018401184021840318404184051840618407184081840918410184111841218413184141841518416184171841818419184201842118422184231842418425184261842718428184291843018431184321843318434184351843618437184381843918440184411844218443184441844518446184471844818449184501845118452184531845418455184561845718458184591846018461184621846318464184651846618467184681846918470184711847218473184741847518476184771847818479184801848118482184831848418485184861848718488184891849018491184921849318494184951849618497184981849918500185011850218503185041850518506185071850818509185101851118512185131851418515185161851718518185191852018521185221852318524185251852618527185281852918530185311853218533185341853518536185371853818539185401854118542185431854418545185461854718548185491855018551185521855318554185551855618557185581855918560185611856218563185641856518566185671856818569185701857118572185731857418575185761857718578185791858018581185821858318584185851858618587185881858918590185911859218593185941859518596185971859818599186001860118602186031860418605186061860718608186091861018611186121861318614186151861618617186181861918620186211862218623186241862518626186271862818629186301863118632186331863418635186361863718638186391864018641186421864318644186451864618647186481864918650186511865218653186541865518656186571865818659186601866118662186631866418665186661866718668186691867018671186721867318674186751867618677186781867918680186811868218683186841868518686186871868818689186901869118692186931869418695186961869718698186991870018701187021870318704187051870618707187081870918710187111871218713187141871518716187171871818719187201872118722187231872418725187261872718728187291873018731187321873318734187351873618737187381873918740187411874218743187441874518746187471874818749187501875118752187531875418755187561875718758187591876018761187621876318764187651876618767187681876918770187711877218773187741877518776187771877818779187801878118782187831878418785187861878718788187891879018791187921879318794187951879618797187981879918800188011880218803188041880518806188071880818809188101881118812188131881418815188161881718818188191882018821188221882318824188251882618827188281882918830188311883218833188341883518836188371883818839188401884118842188431884418845188461884718848188491885018851188521885318854188551885618857188581885918860188611886218863188641886518866188671886818869188701887118872188731887418875188761887718878188791888018881188821888318884188851888618887188881888918890188911889218893188941889518896188971889818899189001890118902189031890418905189061890718908189091891018911189121891318914189151891618917189181891918920189211892218923189241892518926189271892818929189301893118932189331893418935189361893718938189391894018941189421894318944189451894618947189481894918950189511895218953189541895518956189571895818959189601896118962189631896418965189661896718968189691897018971189721897318974189751897618977189781897918980189811898218983189841898518986189871898818989189901899118992189931899418995189961899718998189991900019001190021900319004190051900619007190081900919010190111901219013190141901519016190171901819019190201902119022190231902419025190261902719028190291903019031190321903319034190351903619037190381903919040190411904219043190441904519046190471904819049190501905119052190531905419055190561905719058190591906019061190621906319064190651906619067190681906919070190711907219073190741907519076190771907819079190801908119082190831908419085190861908719088190891909019091190921909319094190951909619097190981909919100191011910219103191041910519106191071910819109191101911119112191131911419115191161911719118191191912019121191221912319124191251912619127191281912919130191311913219133191341913519136191371913819139191401914119142191431914419145191461914719148191491915019151191521915319154191551915619157191581915919160191611916219163191641916519166191671916819169191701917119172191731917419175191761917719178191791918019181191821918319184191851918619187191881918919190191911919219193191941919519196191971919819199192001920119202192031920419205192061920719208192091921019211192121921319214192151921619217192181921919220192211922219223192241922519226192271922819229192301923119232192331923419235192361923719238192391924019241192421924319244192451924619247192481924919250192511925219253192541925519256192571925819259192601926119262192631926419265192661926719268192691927019271192721927319274192751927619277192781927919280192811928219283192841928519286192871928819289192901929119292192931929419295192961929719298192991930019301193021930319304193051930619307193081930919310193111931219313193141931519316193171931819319193201932119322193231932419325193261932719328193291933019331193321933319334193351933619337193381933919340193411934219343193441934519346193471934819349193501935119352193531935419355193561935719358193591936019361193621936319364193651936619367193681936919370193711937219373193741937519376193771937819379193801938119382193831938419385193861938719388193891939019391193921939319394193951939619397193981939919400194011940219403194041940519406194071940819409194101941119412194131941419415194161941719418194191942019421194221942319424194251942619427194281942919430194311943219433194341943519436194371943819439194401944119442194431944419445194461944719448194491945019451194521945319454194551945619457194581945919460194611946219463194641946519466194671946819469194701947119472194731947419475194761947719478194791948019481194821948319484194851948619487194881948919490194911949219493194941949519496194971949819499195001950119502195031950419505195061950719508195091951019511195121951319514195151951619517195181951919520195211952219523195241952519526195271952819529195301953119532195331953419535195361953719538195391954019541195421954319544195451954619547195481954919550195511955219553195541955519556195571955819559195601956119562195631956419565195661956719568195691957019571195721957319574195751957619577195781957919580195811958219583195841958519586195871958819589195901959119592195931959419595195961959719598195991960019601196021960319604196051960619607196081960919610196111961219613196141961519616196171961819619196201962119622196231962419625196261962719628196291963019631196321963319634196351963619637196381963919640196411964219643196441964519646196471964819649196501965119652196531965419655196561965719658196591966019661196621966319664196651966619667196681966919670196711967219673196741967519676196771967819679196801968119682196831968419685196861968719688196891969019691196921969319694196951969619697196981969919700197011970219703197041970519706197071970819709197101971119712197131971419715197161971719718197191972019721197221972319724197251972619727197281972919730197311973219733197341973519736197371973819739197401974119742197431974419745197461974719748197491975019751197521975319754197551975619757197581975919760197611976219763197641976519766197671976819769197701977119772197731977419775197761977719778197791978019781197821978319784197851978619787197881978919790197911979219793197941979519796197971979819799198001980119802198031980419805198061980719808198091981019811198121981319814198151981619817198181981919820198211982219823198241982519826198271982819829198301983119832198331983419835198361983719838198391984019841198421984319844198451984619847198481984919850198511985219853198541985519856198571985819859198601986119862198631986419865198661986719868198691987019871198721987319874198751987619877198781987919880198811988219883198841988519886198871988819889198901989119892198931989419895198961989719898198991990019901199021990319904199051990619907199081990919910199111991219913199141991519916199171991819919199201992119922199231992419925199261992719928199291993019931199321993319934199351993619937199381993919940199411994219943199441994519946199471994819949199501995119952199531995419955199561995719958199591996019961199621996319964199651996619967199681996919970199711997219973199741997519976199771997819979199801998119982199831998419985199861998719988199891999019991199921999319994199951999619997199981999920000200012000220003200042000520006200072000820009200102001120012200132001420015200162001720018200192002020021200222002320024200252002620027200282002920030200312003220033200342003520036200372003820039200402004120042200432004420045200462004720048200492005020051200522005320054200552005620057200582005920060200612006220063200642006520066200672006820069200702007120072200732007420075200762007720078200792008020081200822008320084200852008620087200882008920090200912009220093200942009520096200972009820099201002010120102201032010420105201062010720108201092011020111201122011320114201152011620117201182011920120201212012220123201242012520126201272012820129201302013120132201332013420135201362013720138201392014020141201422014320144201452014620147201482014920150201512015220153201542015520156201572015820159201602016120162201632016420165201662016720168201692017020171201722017320174201752017620177201782017920180201812018220183201842018520186201872018820189201902019120192201932019420195201962019720198201992020020201202022020320204202052020620207202082020920210202112021220213202142021520216202172021820219202202022120222202232022420225202262022720228202292023020231202322023320234202352023620237202382023920240202412024220243202442024520246202472024820249202502025120252202532025420255202562025720258202592026020261202622026320264202652026620267202682026920270202712027220273202742027520276202772027820279202802028120282202832028420285202862028720288202892029020291202922029320294202952029620297202982029920300203012030220303203042030520306203072030820309203102031120312203132031420315203162031720318203192032020321203222032320324203252032620327203282032920330203312033220333203342033520336203372033820339203402034120342203432034420345203462034720348203492035020351203522035320354203552035620357203582035920360203612036220363203642036520366203672036820369203702037120372203732037420375203762037720378203792038020381203822038320384203852038620387203882038920390203912039220393203942039520396203972039820399204002040120402204032040420405204062040720408204092041020411204122041320414204152041620417204182041920420204212042220423204242042520426204272042820429204302043120432204332043420435204362043720438204392044020441204422044320444204452044620447204482044920450204512045220453204542045520456204572045820459204602046120462204632046420465204662046720468204692047020471204722047320474204752047620477204782047920480204812048220483204842048520486204872048820489204902049120492204932049420495204962049720498204992050020501205022050320504205052050620507205082050920510205112051220513205142051520516205172051820519205202052120522205232052420525205262052720528205292053020531205322053320534205352053620537205382053920540205412054220543205442054520546205472054820549205502055120552205532055420555205562055720558205592056020561205622056320564205652056620567205682056920570205712057220573205742057520576205772057820579205802058120582205832058420585205862058720588205892059020591205922059320594205952059620597205982059920600206012060220603206042060520606206072060820609206102061120612206132061420615206162061720618206192062020621206222062320624206252062620627206282062920630206312063220633206342063520636206372063820639206402064120642206432064420645206462064720648206492065020651206522065320654206552065620657206582065920660206612066220663206642066520666206672066820669206702067120672206732067420675206762067720678206792068020681206822068320684206852068620687206882068920690206912069220693206942069520696206972069820699207002070120702207032070420705207062070720708207092071020711207122071320714207152071620717207182071920720207212072220723207242072520726207272072820729207302073120732207332073420735207362073720738207392074020741207422074320744207452074620747207482074920750207512075220753207542075520756207572075820759207602076120762207632076420765207662076720768207692077020771207722077320774207752077620777207782077920780207812078220783207842078520786207872078820789207902079120792207932079420795207962079720798207992080020801208022080320804208052080620807208082080920810208112081220813208142081520816208172081820819208202082120822208232082420825208262082720828208292083020831208322083320834208352083620837208382083920840208412084220843208442084520846208472084820849208502085120852208532085420855208562085720858208592086020861208622086320864208652086620867208682086920870208712087220873208742087520876208772087820879208802088120882208832088420885208862088720888208892089020891208922089320894208952089620897208982089920900209012090220903209042090520906209072090820909209102091120912209132091420915209162091720918209192092020921209222092320924209252092620927209282092920930209312093220933209342093520936209372093820939209402094120942209432094420945209462094720948209492095020951209522095320954209552095620957209582095920960209612096220963209642096520966209672096820969209702097120972209732097420975209762097720978209792098020981209822098320984209852098620987209882098920990209912099220993209942099520996209972099820999210002100121002210032100421005210062100721008210092101021011210122101321014210152101621017210182101921020210212102221023210242102521026210272102821029210302103121032210332103421035210362103721038210392104021041210422104321044210452104621047210482104921050210512105221053210542105521056210572105821059210602106121062210632106421065210662106721068210692107021071210722107321074210752107621077210782107921080210812108221083210842108521086210872108821089210902109121092210932109421095210962109721098210992110021101211022110321104211052110621107211082110921110211112111221113211142111521116211172111821119211202112121122211232112421125211262112721128211292113021131211322113321134211352113621137211382113921140211412114221143211442114521146211472114821149211502115121152211532115421155211562115721158211592116021161211622116321164211652116621167211682116921170211712117221173211742117521176211772117821179211802118121182211832118421185211862118721188211892119021191211922119321194211952119621197211982119921200212012120221203212042120521206212072120821209212102121121212212132121421215212162121721218212192122021221212222122321224212252122621227212282122921230212312123221233212342123521236212372123821239212402124121242212432124421245212462124721248212492125021251212522125321254212552125621257212582125921260212612126221263212642126521266212672126821269212702127121272212732127421275212762127721278212792128021281212822128321284212852128621287212882128921290212912129221293212942129521296212972129821299213002130121302213032130421305213062130721308213092131021311213122131321314213152131621317213182131921320213212132221323213242132521326213272132821329213302133121332213332133421335213362133721338213392134021341213422134321344213452134621347213482134921350213512135221353213542135521356213572135821359213602136121362213632136421365213662136721368213692137021371213722137321374213752137621377213782137921380213812138221383213842138521386213872138821389213902139121392213932139421395213962139721398213992140021401214022140321404214052140621407214082140921410214112141221413214142141521416214172141821419214202142121422214232142421425214262142721428214292143021431214322143321434214352143621437214382143921440214412144221443214442144521446214472144821449214502145121452214532145421455214562145721458214592146021461214622146321464214652146621467214682146921470214712147221473214742147521476214772147821479214802148121482214832148421485214862148721488214892149021491214922149321494214952149621497214982149921500215012150221503215042150521506215072150821509215102151121512215132151421515215162151721518215192152021521215222152321524215252152621527215282152921530215312153221533215342153521536215372153821539215402154121542215432154421545215462154721548215492155021551215522155321554215552155621557215582155921560215612156221563215642156521566215672156821569215702157121572215732157421575215762157721578215792158021581215822158321584215852158621587215882158921590215912159221593215942159521596215972159821599216002160121602216032160421605216062160721608216092161021611216122161321614216152161621617216182161921620216212162221623216242162521626216272162821629216302163121632216332163421635216362163721638216392164021641216422164321644216452164621647216482164921650216512165221653216542165521656216572165821659216602166121662216632166421665216662166721668216692167021671216722167321674216752167621677216782167921680216812168221683216842168521686216872168821689216902169121692216932169421695216962169721698216992170021701217022170321704217052170621707217082170921710217112171221713217142171521716217172171821719217202172121722217232172421725217262172721728217292173021731217322173321734217352173621737217382173921740217412174221743217442174521746217472174821749217502175121752217532175421755217562175721758217592176021761217622176321764217652176621767217682176921770217712177221773217742177521776217772177821779217802178121782217832178421785217862178721788217892179021791217922179321794217952179621797217982179921800218012180221803218042180521806218072180821809218102181121812218132181421815218162181721818218192182021821218222182321824218252182621827218282182921830218312183221833218342183521836218372183821839218402184121842218432184421845218462184721848218492185021851218522185321854218552185621857218582185921860218612186221863218642186521866218672186821869218702187121872218732187421875218762187721878218792188021881218822188321884218852188621887218882188921890218912189221893218942189521896218972189821899219002190121902219032190421905219062190721908219092191021911219122191321914219152191621917219182191921920219212192221923219242192521926219272192821929219302193121932219332193421935219362193721938219392194021941219422194321944219452194621947219482194921950219512195221953219542195521956219572195821959219602196121962219632196421965219662196721968219692197021971219722197321974219752197621977219782197921980219812198221983219842198521986219872198821989219902199121992219932199421995219962199721998219992200022001220022200322004220052200622007220082200922010220112201222013220142201522016220172201822019220202202122022220232202422025220262202722028220292203022031220322203322034220352203622037220382203922040220412204222043220442204522046220472204822049220502205122052220532205422055220562205722058220592206022061220622206322064220652206622067220682206922070220712207222073220742207522076220772207822079220802208122082220832208422085220862208722088220892209022091220922209322094220952209622097220982209922100221012210222103221042210522106221072210822109221102211122112221132211422115221162211722118221192212022121221222212322124221252212622127221282212922130221312213222133221342213522136221372213822139221402214122142221432214422145221462214722148221492215022151221522215322154221552215622157221582215922160221612216222163221642216522166221672216822169221702217122172221732217422175221762217722178221792218022181221822218322184221852218622187221882218922190221912219222193221942219522196221972219822199222002220122202222032220422205222062220722208222092221022211222122221322214222152221622217222182221922220222212222222223222242222522226222272222822229222302223122232222332223422235222362223722238222392224022241222422224322244222452224622247222482224922250222512225222253222542225522256222572225822259222602226122262222632226422265222662226722268222692227022271222722227322274222752227622277222782227922280222812228222283222842228522286222872228822289222902229122292222932229422295222962229722298222992230022301223022230322304223052230622307223082230922310223112231222313223142231522316223172231822319223202232122322223232232422325223262232722328223292233022331223322233322334223352233622337223382233922340223412234222343223442234522346223472234822349223502235122352223532235422355223562235722358223592236022361223622236322364223652236622367223682236922370223712237222373223742237522376223772237822379223802238122382223832238422385223862238722388223892239022391223922239322394223952239622397223982239922400224012240222403224042240522406224072240822409224102241122412224132241422415224162241722418224192242022421224222242322424224252242622427224282242922430224312243222433224342243522436224372243822439224402244122442224432244422445224462244722448224492245022451224522245322454224552245622457224582245922460224612246222463224642246522466224672246822469224702247122472224732247422475224762247722478224792248022481224822248322484224852248622487224882248922490224912249222493224942249522496224972249822499225002250122502225032250422505225062250722508225092251022511225122251322514225152251622517225182251922520225212252222523225242252522526225272252822529225302253122532225332253422535225362253722538225392254022541225422254322544225452254622547225482254922550225512255222553225542255522556225572255822559225602256122562225632256422565225662256722568225692257022571225722257322574225752257622577225782257922580225812258222583225842258522586225872258822589225902259122592225932259422595225962259722598225992260022601226022260322604226052260622607226082260922610226112261222613226142261522616226172261822619226202262122622226232262422625226262262722628226292263022631226322263322634226352263622637226382263922640226412264222643226442264522646226472264822649226502265122652226532265422655226562265722658226592266022661226622266322664226652266622667226682266922670226712267222673226742267522676226772267822679226802268122682226832268422685226862268722688226892269022691226922269322694226952269622697226982269922700227012270222703227042270522706227072270822709227102271122712227132271422715227162271722718227192272022721227222272322724227252272622727227282272922730227312273222733227342273522736227372273822739227402274122742227432274422745227462274722748227492275022751227522275322754227552275622757227582275922760227612276222763227642276522766227672276822769227702277122772227732277422775227762277722778227792278022781227822278322784227852278622787227882278922790227912279222793227942279522796227972279822799228002280122802228032280422805228062280722808228092281022811228122281322814228152281622817228182281922820228212282222823228242282522826228272282822829228302283122832228332283422835228362283722838228392284022841228422284322844228452284622847228482284922850228512285222853228542285522856228572285822859228602286122862228632286422865228662286722868228692287022871228722287322874228752287622877228782287922880228812288222883228842288522886228872288822889228902289122892228932289422895228962289722898228992290022901229022290322904229052290622907229082290922910229112291222913229142291522916229172291822919229202292122922229232292422925229262292722928229292293022931229322293322934229352293622937229382293922940229412294222943229442294522946229472294822949229502295122952229532295422955229562295722958229592296022961229622296322964229652296622967229682296922970229712297222973229742297522976229772297822979229802298122982229832298422985229862298722988229892299022991229922299322994229952299622997229982299923000230012300223003230042300523006230072300823009230102301123012230132301423015230162301723018230192302023021230222302323024230252302623027230282302923030230312303223033230342303523036230372303823039230402304123042230432304423045230462304723048230492305023051230522305323054230552305623057230582305923060230612306223063230642306523066230672306823069230702307123072230732307423075230762307723078230792308023081230822308323084230852308623087230882308923090230912309223093230942309523096230972309823099231002310123102231032310423105231062310723108231092311023111231122311323114231152311623117231182311923120231212312223123231242312523126231272312823129231302313123132231332313423135231362313723138231392314023141231422314323144231452314623147231482314923150231512315223153231542315523156231572315823159231602316123162231632316423165231662316723168231692317023171231722317323174231752317623177231782317923180231812318223183231842318523186231872318823189231902319123192231932319423195231962319723198231992320023201232022320323204232052320623207232082320923210232112321223213232142321523216232172321823219232202322123222232232322423225232262322723228232292323023231232322323323234232352323623237232382323923240232412324223243232442324523246232472324823249232502325123252232532325423255232562325723258232592326023261232622326323264232652326623267232682326923270232712327223273232742327523276232772327823279232802328123282232832328423285232862328723288232892329023291232922329323294232952329623297232982329923300233012330223303233042330523306233072330823309233102331123312233132331423315233162331723318233192332023321233222332323324233252332623327233282332923330233312333223333233342333523336233372333823339233402334123342233432334423345233462334723348233492335023351233522335323354233552335623357233582335923360233612336223363233642336523366233672336823369233702337123372233732337423375233762337723378233792338023381233822338323384233852338623387233882338923390233912339223393233942339523396233972339823399234002340123402234032340423405234062340723408234092341023411234122341323414234152341623417234182341923420234212342223423234242342523426234272342823429234302343123432234332343423435234362343723438234392344023441234422344323444234452344623447234482344923450234512345223453234542345523456234572345823459234602346123462234632346423465234662346723468234692347023471234722347323474234752347623477234782347923480234812348223483234842348523486234872348823489234902349123492234932349423495234962349723498234992350023501235022350323504235052350623507235082350923510235112351223513235142351523516235172351823519235202352123522235232352423525235262352723528235292353023531235322353323534235352353623537235382353923540235412354223543235442354523546235472354823549235502355123552235532355423555235562355723558235592356023561235622356323564235652356623567235682356923570235712357223573235742357523576235772357823579235802358123582235832358423585235862358723588235892359023591235922359323594235952359623597235982359923600236012360223603236042360523606236072360823609236102361123612236132361423615236162361723618236192362023621236222362323624236252362623627236282362923630236312363223633236342363523636236372363823639236402364123642236432364423645236462364723648236492365023651236522365323654236552365623657236582365923660236612366223663236642366523666236672366823669236702367123672236732367423675236762367723678236792368023681236822368323684236852368623687236882368923690236912369223693236942369523696236972369823699237002370123702237032370423705237062370723708237092371023711237122371323714237152371623717237182371923720237212372223723237242372523726237272372823729237302373123732237332373423735237362373723738237392374023741237422374323744237452374623747237482374923750237512375223753237542375523756237572375823759237602376123762237632376423765237662376723768237692377023771237722377323774237752377623777237782377923780237812378223783237842378523786237872378823789237902379123792237932379423795237962379723798237992380023801238022380323804238052380623807238082380923810238112381223813238142381523816238172381823819238202382123822238232382423825238262382723828238292383023831238322383323834238352383623837238382383923840238412384223843238442384523846238472384823849238502385123852238532385423855238562385723858238592386023861238622386323864238652386623867238682386923870238712387223873238742387523876238772387823879238802388123882238832388423885238862388723888238892389023891238922389323894238952389623897238982389923900239012390223903239042390523906239072390823909239102391123912239132391423915239162391723918239192392023921239222392323924239252392623927239282392923930239312393223933239342393523936239372393823939239402394123942239432394423945239462394723948239492395023951239522395323954239552395623957239582395923960239612396223963239642396523966239672396823969239702397123972239732397423975239762397723978239792398023981239822398323984239852398623987239882398923990239912399223993239942399523996239972399823999240002400124002240032400424005240062400724008240092401024011240122401324014240152401624017240182401924020240212402224023240242402524026240272402824029240302403124032240332403424035240362403724038240392404024041240422404324044240452404624047240482404924050240512405224053240542405524056240572405824059240602406124062240632406424065240662406724068240692407024071240722407324074240752407624077240782407924080240812408224083240842408524086240872408824089240902409124092240932409424095240962409724098240992410024101241022410324104241052410624107241082410924110241112411224113241142411524116241172411824119241202412124122241232412424125241262412724128241292413024131241322413324134241352413624137241382413924140241412414224143241442414524146241472414824149241502415124152241532415424155241562415724158241592416024161241622416324164241652416624167241682416924170241712417224173241742417524176241772417824179241802418124182241832418424185241862418724188241892419024191241922419324194241952419624197241982419924200242012420224203242042420524206242072420824209242102421124212242132421424215242162421724218242192422024221242222422324224242252422624227242282422924230242312423224233242342423524236242372423824239242402424124242242432424424245242462424724248242492425024251242522425324254242552425624257242582425924260242612426224263242642426524266242672426824269242702427124272242732427424275242762427724278242792428024281242822428324284242852428624287242882428924290242912429224293242942429524296242972429824299243002430124302243032430424305243062430724308243092431024311243122431324314243152431624317243182431924320243212432224323243242432524326243272432824329243302433124332243332433424335243362433724338243392434024341243422434324344243452434624347243482434924350243512435224353243542435524356243572435824359243602436124362243632436424365243662436724368243692437024371243722437324374243752437624377243782437924380243812438224383243842438524386243872438824389243902439124392243932439424395243962439724398243992440024401244022440324404244052440624407244082440924410244112441224413244142441524416244172441824419244202442124422244232442424425244262442724428244292443024431244322443324434244352443624437244382443924440244412444224443244442444524446244472444824449244502445124452244532445424455244562445724458244592446024461244622446324464244652446624467244682446924470244712447224473244742447524476244772447824479244802448124482244832448424485244862448724488244892449024491244922449324494244952449624497244982449924500245012450224503245042450524506245072450824509245102451124512245132451424515245162451724518245192452024521245222452324524245252452624527245282452924530245312453224533245342453524536245372453824539245402454124542245432454424545245462454724548245492455024551245522455324554245552455624557245582455924560245612456224563245642456524566245672456824569245702457124572245732457424575245762457724578245792458024581245822458324584245852458624587245882458924590245912459224593245942459524596245972459824599246002460124602246032460424605246062460724608246092461024611246122461324614246152461624617246182461924620246212462224623246242462524626246272462824629246302463124632246332463424635246362463724638246392464024641246422464324644246452464624647246482464924650246512465224653246542465524656246572465824659246602466124662246632466424665246662466724668246692467024671246722467324674246752467624677246782467924680246812468224683246842468524686246872468824689246902469124692246932469424695246962469724698246992470024701247022470324704247052470624707247082470924710247112471224713247142471524716247172471824719247202472124722247232472424725247262472724728247292473024731247322473324734247352473624737247382473924740247412474224743247442474524746247472474824749247502475124752247532475424755247562475724758247592476024761247622476324764247652476624767247682476924770247712477224773247742477524776247772477824779247802478124782247832478424785247862478724788247892479024791247922479324794247952479624797247982479924800248012480224803248042480524806248072480824809248102481124812248132481424815248162481724818248192482024821248222482324824248252482624827248282482924830248312483224833248342483524836248372483824839248402484124842248432484424845248462484724848248492485024851248522485324854248552485624857248582485924860248612486224863248642486524866248672486824869248702487124872248732487424875248762487724878248792488024881248822488324884248852488624887248882488924890248912489224893248942489524896248972489824899249002490124902249032490424905249062490724908249092491024911249122491324914249152491624917249182491924920249212492224923249242492524926249272492824929249302493124932249332493424935249362493724938249392494024941249422494324944249452494624947249482494924950249512495224953249542495524956249572495824959249602496124962249632496424965249662496724968249692497024971249722497324974249752497624977249782497924980249812498224983249842498524986249872498824989249902499124992249932499424995249962499724998249992500025001250022500325004250052500625007250082500925010250112501225013250142501525016250172501825019250202502125022250232502425025250262502725028250292503025031250322503325034250352503625037250382503925040250412504225043250442504525046250472504825049250502505125052250532505425055250562505725058250592506025061250622506325064250652506625067250682506925070250712507225073250742507525076250772507825079250802508125082250832508425085250862508725088250892509025091250922509325094250952509625097250982509925100251012510225103251042510525106251072510825109251102511125112251132511425115251162511725118251192512025121251222512325124251252512625127251282512925130251312513225133251342513525136251372513825139251402514125142251432514425145251462514725148251492515025151251522515325154251552515625157251582515925160251612516225163251642516525166251672516825169251702517125172251732517425175251762517725178251792518025181251822518325184251852518625187251882518925190251912519225193251942519525196251972519825199252002520125202252032520425205252062520725208252092521025211252122521325214252152521625217252182521925220252212522225223252242522525226252272522825229252302523125232252332523425235252362523725238252392524025241252422524325244252452524625247252482524925250252512525225253252542525525256252572525825259252602526125262252632526425265252662526725268252692527025271252722527325274252752527625277252782527925280252812528225283252842528525286252872528825289252902529125292252932529425295252962529725298252992530025301253022530325304253052530625307253082530925310253112531225313253142531525316253172531825319253202532125322253232532425325253262532725328253292533025331253322533325334253352533625337253382533925340253412534225343253442534525346253472534825349253502535125352253532535425355253562535725358253592536025361253622536325364253652536625367253682536925370253712537225373253742537525376253772537825379253802538125382253832538425385253862538725388253892539025391253922539325394253952539625397253982539925400254012540225403254042540525406254072540825409254102541125412254132541425415254162541725418254192542025421254222542325424254252542625427254282542925430254312543225433254342543525436254372543825439254402544125442254432544425445254462544725448254492545025451254522545325454254552545625457254582545925460254612546225463254642546525466254672546825469254702547125472254732547425475254762547725478254792548025481254822548325484254852548625487254882548925490254912549225493254942549525496254972549825499255002550125502255032550425505255062550725508255092551025511255122551325514255152551625517255182551925520255212552225523255242552525526255272552825529255302553125532255332553425535255362553725538255392554025541255422554325544255452554625547255482554925550255512555225553255542555525556255572555825559255602556125562255632556425565255662556725568255692557025571255722557325574255752557625577255782557925580255812558225583255842558525586255872558825589255902559125592255932559425595255962559725598255992560025601256022560325604256052560625607256082560925610256112561225613256142561525616256172561825619256202562125622256232562425625256262562725628256292563025631256322563325634256352563625637256382563925640256412564225643256442564525646256472564825649256502565125652256532565425655256562565725658256592566025661256622566325664256652566625667256682566925670256712567225673256742567525676256772567825679256802568125682256832568425685256862568725688256892569025691256922569325694256952569625697256982569925700257012570225703257042570525706257072570825709257102571125712257132571425715257162571725718257192572025721257222572325724257252572625727257282572925730257312573225733257342573525736257372573825739257402574125742257432574425745257462574725748257492575025751257522575325754257552575625757257582575925760257612576225763257642576525766257672576825769257702577125772257732577425775257762577725778257792578025781257822578325784257852578625787257882578925790257912579225793257942579525796257972579825799258002580125802258032580425805258062580725808258092581025811258122581325814258152581625817258182581925820258212582225823258242582525826258272582825829258302583125832258332583425835258362583725838258392584025841258422584325844258452584625847258482584925850258512585225853258542585525856258572585825859258602586125862258632586425865258662586725868258692587025871258722587325874258752587625877258782587925880258812588225883258842588525886258872588825889258902589125892258932589425895258962589725898258992590025901259022590325904259052590625907259082590925910259112591225913259142591525916259172591825919259202592125922259232592425925259262592725928259292593025931259322593325934259352593625937259382593925940259412594225943259442594525946259472594825949259502595125952259532595425955259562595725958259592596025961259622596325964259652596625967259682596925970259712597225973259742597525976259772597825979259802598125982259832598425985259862598725988259892599025991259922599325994259952599625997259982599926000260012600226003260042600526006260072600826009260102601126012260132601426015260162601726018260192602026021260222602326024260252602626027260282602926030260312603226033260342603526036260372603826039260402604126042260432604426045260462604726048260492605026051260522605326054260552605626057260582605926060260612606226063260642606526066260672606826069260702607126072260732607426075260762607726078260792608026081260822608326084260852608626087260882608926090260912609226093260942609526096260972609826099261002610126102261032610426105261062610726108261092611026111261122611326114261152611626117261182611926120261212612226123261242612526126261272612826129261302613126132261332613426135261362613726138261392614026141261422614326144261452614626147261482614926150261512615226153261542615526156261572615826159261602616126162261632616426165261662616726168261692617026171261722617326174261752617626177261782617926180261812618226183261842618526186261872618826189261902619126192261932619426195261962619726198261992620026201262022620326204262052620626207262082620926210262112621226213262142621526216262172621826219262202622126222262232622426225262262622726228262292623026231262322623326234262352623626237262382623926240262412624226243262442624526246262472624826249262502625126252262532625426255262562625726258262592626026261262622626326264262652626626267262682626926270262712627226273262742627526276262772627826279262802628126282262832628426285262862628726288262892629026291262922629326294262952629626297262982629926300263012630226303263042630526306263072630826309263102631126312263132631426315263162631726318263192632026321263222632326324263252632626327263282632926330263312633226333263342633526336263372633826339263402634126342263432634426345263462634726348263492635026351263522635326354263552635626357263582635926360263612636226363263642636526366263672636826369263702637126372263732637426375263762637726378263792638026381263822638326384263852638626387263882638926390263912639226393263942639526396263972639826399264002640126402264032640426405264062640726408264092641026411264122641326414264152641626417264182641926420264212642226423264242642526426264272642826429264302643126432264332643426435264362643726438264392644026441264422644326444264452644626447264482644926450264512645226453264542645526456264572645826459264602646126462264632646426465264662646726468264692647026471264722647326474264752647626477264782647926480264812648226483264842648526486264872648826489264902649126492264932649426495264962649726498264992650026501265022650326504265052650626507265082650926510265112651226513265142651526516265172651826519265202652126522265232652426525265262652726528265292653026531265322653326534265352653626537265382653926540265412654226543265442654526546265472654826549265502655126552265532655426555265562655726558265592656026561265622656326564265652656626567265682656926570265712657226573265742657526576265772657826579265802658126582265832658426585265862658726588265892659026591265922659326594265952659626597265982659926600266012660226603266042660526606266072660826609266102661126612266132661426615266162661726618266192662026621266222662326624266252662626627266282662926630266312663226633266342663526636266372663826639266402664126642266432664426645266462664726648266492665026651266522665326654266552665626657266582665926660266612666226663266642666526666266672666826669266702667126672266732667426675266762667726678266792668026681266822668326684266852668626687266882668926690266912669226693266942669526696266972669826699267002670126702267032670426705267062670726708267092671026711267122671326714267152671626717267182671926720267212672226723267242672526726267272672826729267302673126732267332673426735267362673726738267392674026741267422674326744267452674626747267482674926750267512675226753267542675526756267572675826759267602676126762267632676426765267662676726768267692677026771267722677326774267752677626777267782677926780267812678226783267842678526786267872678826789267902679126792267932679426795267962679726798267992680026801268022680326804268052680626807268082680926810268112681226813268142681526816268172681826819268202682126822268232682426825268262682726828268292683026831268322683326834268352683626837268382683926840268412684226843268442684526846268472684826849268502685126852268532685426855268562685726858268592686026861268622686326864268652686626867268682686926870268712687226873268742687526876268772687826879268802688126882268832688426885268862688726888268892689026891268922689326894268952689626897268982689926900269012690226903269042690526906269072690826909269102691126912269132691426915269162691726918269192692026921269222692326924269252692626927269282692926930269312693226933269342693526936269372693826939269402694126942269432694426945269462694726948269492695026951269522695326954269552695626957269582695926960269612696226963269642696526966269672696826969269702697126972269732697426975269762697726978269792698026981269822698326984269852698626987269882698926990269912699226993269942699526996269972699826999270002700127002270032700427005270062700727008270092701027011270122701327014270152701627017270182701927020270212702227023270242702527026270272702827029270302703127032270332703427035270362703727038270392704027041270422704327044270452704627047270482704927050270512705227053270542705527056270572705827059270602706127062270632706427065270662706727068270692707027071270722707327074270752707627077270782707927080270812708227083270842708527086270872708827089270902709127092270932709427095270962709727098270992710027101271022710327104271052710627107271082710927110271112711227113271142711527116271172711827119271202712127122271232712427125271262712727128271292713027131271322713327134271352713627137271382713927140271412714227143271442714527146271472714827149271502715127152271532715427155271562715727158271592716027161271622716327164271652716627167271682716927170271712717227173271742717527176271772717827179271802718127182271832718427185271862718727188271892719027191271922719327194271952719627197271982719927200272012720227203272042720527206272072720827209272102721127212272132721427215272162721727218272192722027221272222722327224272252722627227272282722927230272312723227233272342723527236272372723827239272402724127242272432724427245272462724727248272492725027251272522725327254272552725627257272582725927260272612726227263272642726527266272672726827269272702727127272272732727427275272762727727278272792728027281272822728327284272852728627287272882728927290272912729227293272942729527296272972729827299273002730127302273032730427305273062730727308273092731027311273122731327314273152731627317273182731927320273212732227323273242732527326273272732827329273302733127332273332733427335273362733727338273392734027341273422734327344273452734627347273482734927350273512735227353273542735527356273572735827359273602736127362273632736427365273662736727368273692737027371273722737327374273752737627377273782737927380273812738227383273842738527386273872738827389273902739127392273932739427395273962739727398273992740027401274022740327404274052740627407274082740927410274112741227413274142741527416274172741827419274202742127422274232742427425274262742727428274292743027431274322743327434274352743627437274382743927440274412744227443274442744527446274472744827449274502745127452274532745427455274562745727458274592746027461274622746327464274652746627467274682746927470274712747227473274742747527476274772747827479274802748127482274832748427485274862748727488274892749027491274922749327494274952749627497274982749927500275012750227503275042750527506275072750827509275102751127512275132751427515275162751727518275192752027521275222752327524275252752627527275282752927530275312753227533275342753527536275372753827539275402754127542275432754427545275462754727548275492755027551275522755327554275552755627557275582755927560275612756227563275642756527566275672756827569275702757127572275732757427575275762757727578275792758027581275822758327584275852758627587275882758927590275912759227593275942759527596275972759827599276002760127602276032760427605276062760727608276092761027611276122761327614276152761627617276182761927620276212762227623276242762527626276272762827629276302763127632276332763427635276362763727638276392764027641276422764327644276452764627647276482764927650276512765227653276542765527656276572765827659276602766127662276632766427665276662766727668276692767027671276722767327674276752767627677276782767927680276812768227683276842768527686276872768827689276902769127692276932769427695276962769727698276992770027701277022770327704277052770627707277082770927710277112771227713277142771527716277172771827719277202772127722277232772427725277262772727728277292773027731277322773327734277352773627737277382773927740277412774227743277442774527746277472774827749277502775127752277532775427755277562775727758277592776027761277622776327764277652776627767277682776927770277712777227773277742777527776277772777827779277802778127782277832778427785277862778727788277892779027791277922779327794277952779627797277982779927800278012780227803278042780527806278072780827809278102781127812278132781427815278162781727818278192782027821278222782327824278252782627827278282782927830278312783227833278342783527836278372783827839278402784127842278432784427845278462784727848278492785027851278522785327854278552785627857278582785927860278612786227863278642786527866278672786827869278702787127872278732787427875278762787727878278792788027881278822788327884278852788627887278882788927890278912789227893278942789527896278972789827899279002790127902279032790427905279062790727908279092791027911279122791327914279152791627917279182791927920279212792227923279242792527926279272792827929279302793127932279332793427935279362793727938279392794027941279422794327944279452794627947279482794927950279512795227953279542795527956279572795827959279602796127962279632796427965279662796727968279692797027971279722797327974279752797627977279782797927980279812798227983279842798527986279872798827989279902799127992279932799427995279962799727998279992800028001280022800328004280052800628007280082800928010280112801228013280142801528016280172801828019280202802128022280232802428025280262802728028280292803028031280322803328034280352803628037280382803928040280412804228043280442804528046280472804828049280502805128052280532805428055280562805728058280592806028061280622806328064280652806628067280682806928070280712807228073280742807528076280772807828079280802808128082280832808428085280862808728088280892809028091280922809328094280952809628097280982809928100281012810228103281042810528106281072810828109281102811128112281132811428115281162811728118281192812028121281222812328124281252812628127281282812928130281312813228133281342813528136281372813828139281402814128142281432814428145281462814728148281492815028151281522815328154281552815628157281582815928160281612816228163281642816528166281672816828169281702817128172281732817428175281762817728178281792818028181281822818328184281852818628187281882818928190281912819228193281942819528196281972819828199282002820128202282032820428205282062820728208282092821028211282122821328214282152821628217282182821928220282212822228223282242822528226282272822828229282302823128232282332823428235282362823728238282392824028241282422824328244282452824628247282482824928250282512825228253282542825528256282572825828259282602826128262282632826428265282662826728268282692827028271282722827328274282752827628277282782827928280282812828228283282842828528286282872828828289282902829128292282932829428295282962829728298282992830028301283022830328304283052830628307283082830928310283112831228313283142831528316283172831828319283202832128322283232832428325283262832728328283292833028331283322833328334283352833628337283382833928340283412834228343283442834528346283472834828349283502835128352283532835428355283562835728358283592836028361283622836328364283652836628367283682836928370283712837228373283742837528376283772837828379283802838128382283832838428385283862838728388283892839028391283922839328394283952839628397283982839928400284012840228403284042840528406284072840828409284102841128412284132841428415284162841728418284192842028421284222842328424284252842628427284282842928430284312843228433284342843528436284372843828439284402844128442284432844428445284462844728448284492845028451284522845328454284552845628457284582845928460284612846228463284642846528466284672846828469284702847128472284732847428475284762847728478284792848028481284822848328484284852848628487284882848928490284912849228493284942849528496284972849828499285002850128502285032850428505285062850728508285092851028511285122851328514285152851628517285182851928520285212852228523285242852528526285272852828529285302853128532285332853428535285362853728538285392854028541285422854328544285452854628547285482854928550285512855228553285542855528556285572855828559285602856128562285632856428565285662856728568285692857028571285722857328574285752857628577285782857928580285812858228583285842858528586285872858828589285902859128592285932859428595285962859728598285992860028601286022860328604286052860628607286082860928610286112861228613286142861528616286172861828619286202862128622286232862428625286262862728628286292863028631286322863328634286352863628637286382863928640286412864228643286442864528646286472864828649286502865128652286532865428655286562865728658286592866028661286622866328664286652866628667286682866928670286712867228673286742867528676286772867828679286802868128682286832868428685286862868728688286892869028691286922869328694286952869628697286982869928700287012870228703287042870528706287072870828709287102871128712287132871428715287162871728718287192872028721287222872328724287252872628727287282872928730287312873228733287342873528736287372873828739287402874128742287432874428745287462874728748287492875028751287522875328754287552875628757287582875928760287612876228763287642876528766287672876828769287702877128772287732877428775287762877728778287792878028781287822878328784287852878628787287882878928790287912879228793287942879528796287972879828799288002880128802288032880428805288062880728808288092881028811288122881328814288152881628817288182881928820288212882228823288242882528826288272882828829288302883128832288332883428835288362883728838288392884028841288422884328844288452884628847288482884928850288512885228853288542885528856288572885828859288602886128862288632886428865288662886728868288692887028871288722887328874288752887628877288782887928880288812888228883288842888528886288872888828889288902889128892288932889428895288962889728898288992890028901289022890328904289052890628907289082890928910289112891228913289142891528916289172891828919289202892128922289232892428925289262892728928289292893028931289322893328934289352893628937289382893928940289412894228943289442894528946289472894828949289502895128952289532895428955289562895728958289592896028961289622896328964289652896628967289682896928970289712897228973289742897528976289772897828979289802898128982289832898428985289862898728988289892899028991289922899328994289952899628997289982899929000290012900229003290042900529006290072900829009290102901129012290132901429015290162901729018290192902029021290222902329024290252902629027290282902929030290312903229033290342903529036290372903829039290402904129042290432904429045290462904729048290492905029051290522905329054290552905629057290582905929060290612906229063290642906529066290672906829069290702907129072290732907429075290762907729078290792908029081290822908329084290852908629087290882908929090290912909229093290942909529096290972909829099291002910129102291032910429105291062910729108291092911029111291122911329114291152911629117291182911929120291212912229123291242912529126291272912829129291302913129132291332913429135291362913729138291392914029141291422914329144291452914629147291482914929150291512915229153291542915529156291572915829159291602916129162291632916429165291662916729168291692917029171291722917329174291752917629177291782917929180291812918229183291842918529186291872918829189291902919129192291932919429195291962919729198291992920029201292022920329204292052920629207292082920929210292112921229213292142921529216292172921829219292202922129222292232922429225292262922729228292292923029231292322923329234292352923629237292382923929240292412924229243292442924529246292472924829249292502925129252292532925429255292562925729258292592926029261292622926329264292652926629267292682926929270292712927229273292742927529276292772927829279292802928129282292832928429285292862928729288292892929029291292922929329294292952929629297292982929929300293012930229303293042930529306293072930829309293102931129312293132931429315293162931729318293192932029321293222932329324293252932629327293282932929330293312933229333293342933529336293372933829339293402934129342293432934429345293462934729348293492935029351293522935329354293552935629357293582935929360293612936229363293642936529366293672936829369293702937129372293732937429375293762937729378293792938029381293822938329384293852938629387293882938929390293912939229393293942939529396293972939829399294002940129402294032940429405294062940729408294092941029411294122941329414294152941629417294182941929420294212942229423294242942529426294272942829429294302943129432294332943429435294362943729438294392944029441294422944329444294452944629447294482944929450294512945229453294542945529456294572945829459294602946129462294632946429465294662946729468294692947029471294722947329474294752947629477294782947929480294812948229483294842948529486294872948829489294902949129492294932949429495294962949729498294992950029501295022950329504295052950629507295082950929510295112951229513295142951529516295172951829519295202952129522295232952429525295262952729528295292953029531295322953329534295352953629537295382953929540295412954229543295442954529546295472954829549295502955129552295532955429555295562955729558295592956029561295622956329564295652956629567295682956929570295712957229573295742957529576295772957829579295802958129582295832958429585295862958729588295892959029591295922959329594295952959629597295982959929600296012960229603296042960529606296072960829609296102961129612296132961429615296162961729618296192962029621296222962329624296252962629627296282962929630296312963229633296342963529636296372963829639296402964129642296432964429645296462964729648296492965029651296522965329654296552965629657296582965929660296612966229663296642966529666296672966829669296702967129672296732967429675296762967729678296792968029681296822968329684296852968629687296882968929690296912969229693296942969529696296972969829699297002970129702297032970429705297062970729708297092971029711297122971329714297152971629717297182971929720297212972229723297242972529726297272972829729297302973129732297332973429735297362973729738297392974029741297422974329744297452974629747297482974929750297512975229753297542975529756297572975829759297602976129762297632976429765297662976729768297692977029771297722977329774297752977629777297782977929780297812978229783297842978529786297872978829789297902979129792297932979429795297962979729798297992980029801298022980329804298052980629807298082980929810298112981229813298142981529816298172981829819298202982129822298232982429825298262982729828298292983029831298322983329834298352983629837298382983929840298412984229843298442984529846298472984829849298502985129852298532985429855298562985729858298592986029861298622986329864298652986629867298682986929870298712987229873298742987529876298772987829879298802988129882298832988429885298862988729888298892989029891298922989329894298952989629897298982989929900299012990229903299042990529906299072990829909299102991129912299132991429915299162991729918299192992029921299222992329924299252992629927299282992929930299312993229933299342993529936299372993829939299402994129942299432994429945299462994729948299492995029951299522995329954299552995629957299582995929960299612996229963299642996529966299672996829969299702997129972299732997429975299762997729978299792998029981299822998329984299852998629987299882998929990299912999229993299942999529996299972999829999300003000130002300033000430005300063000730008300093001030011300123001330014300153001630017300183001930020300213002230023300243002530026300273002830029300303003130032300333003430035300363003730038300393004030041300423004330044300453004630047300483004930050300513005230053300543005530056300573005830059300603006130062300633006430065300663006730068300693007030071300723007330074300753007630077300783007930080300813008230083300843008530086300873008830089300903009130092300933009430095300963009730098300993010030101301023010330104301053010630107301083010930110301113011230113301143011530116301173011830119301203012130122301233012430125301263012730128301293013030131301323013330134301353013630137301383013930140301413014230143301443014530146301473014830149301503015130152301533015430155301563015730158301593016030161301623016330164301653016630167301683016930170301713017230173301743017530176301773017830179301803018130182301833018430185301863018730188301893019030191301923019330194301953019630197301983019930200302013020230203302043020530206302073020830209302103021130212302133021430215302163021730218302193022030221302223022330224302253022630227302283022930230302313023230233302343023530236302373023830239302403024130242302433024430245302463024730248302493025030251302523025330254302553025630257302583025930260302613026230263302643026530266302673026830269302703027130272302733027430275302763027730278302793028030281302823028330284302853028630287302883028930290302913029230293302943029530296302973029830299303003030130302303033030430305303063030730308303093031030311303123031330314303153031630317303183031930320303213032230323303243032530326303273032830329303303033130332303333033430335303363033730338303393034030341303423034330344303453034630347303483034930350303513035230353303543035530356303573035830359303603036130362303633036430365303663036730368303693037030371303723037330374303753037630377303783037930380303813038230383303843038530386303873038830389303903039130392303933039430395303963039730398303993040030401304023040330404304053040630407304083040930410304113041230413304143041530416304173041830419304203042130422304233042430425304263042730428304293043030431304323043330434304353043630437304383043930440304413044230443304443044530446304473044830449304503045130452304533045430455304563045730458304593046030461304623046330464304653046630467304683046930470304713047230473304743047530476304773047830479304803048130482304833048430485304863048730488304893049030491304923049330494304953049630497304983049930500305013050230503305043050530506305073050830509305103051130512305133051430515305163051730518305193052030521305223052330524305253052630527305283052930530305313053230533305343053530536305373053830539305403054130542305433054430545305463054730548305493055030551305523055330554305553055630557305583055930560305613056230563305643056530566305673056830569305703057130572305733057430575305763057730578305793058030581305823058330584305853058630587305883058930590305913059230593305943059530596305973059830599306003060130602306033060430605306063060730608306093061030611306123061330614306153061630617306183061930620306213062230623306243062530626306273062830629306303063130632306333063430635306363063730638306393064030641306423064330644306453064630647306483064930650306513065230653306543065530656306573065830659306603066130662306633066430665306663066730668306693067030671306723067330674306753067630677306783067930680306813068230683306843068530686306873068830689306903069130692306933069430695306963069730698306993070030701307023070330704307053070630707307083070930710307113071230713307143071530716307173071830719307203072130722307233072430725307263072730728307293073030731307323073330734307353073630737307383073930740307413074230743307443074530746307473074830749307503075130752307533075430755307563075730758307593076030761307623076330764307653076630767307683076930770307713077230773307743077530776307773077830779307803078130782307833078430785307863078730788307893079030791307923079330794307953079630797307983079930800308013080230803308043080530806308073080830809308103081130812308133081430815308163081730818308193082030821308223082330824308253082630827308283082930830308313083230833308343083530836308373083830839308403084130842308433084430845308463084730848308493085030851308523085330854308553085630857308583085930860308613086230863308643086530866308673086830869308703087130872308733087430875308763087730878308793088030881308823088330884308853088630887308883088930890308913089230893308943089530896308973089830899309003090130902309033090430905309063090730908309093091030911309123091330914309153091630917309183091930920309213092230923309243092530926309273092830929309303093130932309333093430935309363093730938309393094030941309423094330944309453094630947309483094930950309513095230953309543095530956309573095830959309603096130962309633096430965309663096730968309693097030971309723097330974309753097630977309783097930980309813098230983309843098530986309873098830989309903099130992309933099430995309963099730998309993100031001310023100331004310053100631007310083100931010310113101231013310143101531016310173101831019310203102131022310233102431025310263102731028310293103031031310323103331034310353103631037310383103931040310413104231043310443104531046310473104831049310503105131052310533105431055310563105731058310593106031061310623106331064310653106631067310683106931070310713107231073310743107531076310773107831079310803108131082310833108431085310863108731088310893109031091310923109331094310953109631097310983109931100311013110231103311043110531106311073110831109311103111131112311133111431115311163111731118311193112031121311223112331124311253112631127311283112931130311313113231133311343113531136311373113831139311403114131142311433114431145311463114731148311493115031151311523115331154311553115631157311583115931160311613116231163311643116531166311673116831169311703117131172311733117431175311763117731178311793118031181311823118331184311853118631187311883118931190311913119231193311943119531196311973119831199312003120131202312033120431205312063120731208312093121031211312123121331214312153121631217312183121931220312213122231223312243122531226312273122831229312303123131232312333123431235312363123731238312393124031241312423124331244312453124631247312483124931250312513125231253312543125531256312573125831259312603126131262312633126431265312663126731268312693127031271312723127331274312753127631277312783127931280312813128231283312843128531286312873128831289312903129131292312933129431295312963129731298312993130031301313023130331304313053130631307313083130931310313113131231313313143131531316313173131831319313203132131322313233132431325313263132731328313293133031331313323133331334313353133631337313383133931340313413134231343313443134531346313473134831349313503135131352313533135431355313563135731358313593136031361313623136331364313653136631367313683136931370313713137231373313743137531376313773137831379313803138131382313833138431385313863138731388313893139031391313923139331394313953139631397313983139931400314013140231403314043140531406314073140831409314103141131412314133141431415314163141731418314193142031421314223142331424314253142631427314283142931430314313143231433314343143531436314373143831439314403144131442314433144431445314463144731448314493145031451314523145331454314553145631457314583145931460314613146231463314643146531466314673146831469314703147131472314733147431475314763147731478314793148031481314823148331484314853148631487314883148931490314913149231493314943149531496314973149831499315003150131502315033150431505315063150731508315093151031511315123151331514315153151631517315183151931520315213152231523315243152531526315273152831529315303153131532315333153431535315363153731538315393154031541315423154331544315453154631547315483154931550315513155231553315543155531556315573155831559315603156131562315633156431565315663156731568315693157031571315723157331574315753157631577315783157931580315813158231583315843158531586315873158831589315903159131592315933159431595315963159731598315993160031601316023160331604316053160631607316083160931610316113161231613316143161531616316173161831619316203162131622316233162431625316263162731628316293163031631316323163331634316353163631637316383163931640316413164231643316443164531646316473164831649316503165131652316533165431655316563165731658316593166031661316623166331664316653166631667316683166931670316713167231673316743167531676316773167831679316803168131682316833168431685316863168731688316893169031691316923169331694316953169631697316983169931700317013170231703317043170531706317073170831709317103171131712317133171431715317163171731718317193172031721317223172331724317253172631727317283172931730317313173231733317343173531736317373173831739317403174131742317433174431745317463174731748317493175031751317523175331754317553175631757317583175931760317613176231763317643176531766317673176831769317703177131772317733177431775317763177731778317793178031781317823178331784317853178631787317883178931790317913179231793317943179531796317973179831799318003180131802318033180431805318063180731808318093181031811318123181331814318153181631817318183181931820318213182231823318243182531826318273182831829318303183131832318333183431835318363183731838318393184031841318423184331844318453184631847318483184931850318513185231853318543185531856318573185831859318603186131862318633186431865318663186731868318693187031871318723187331874318753187631877318783187931880318813188231883318843188531886318873188831889318903189131892318933189431895318963189731898318993190031901319023190331904319053190631907319083190931910319113191231913319143191531916319173191831919319203192131922319233192431925319263192731928319293193031931319323193331934319353193631937319383193931940319413194231943319443194531946319473194831949319503195131952319533195431955319563195731958319593196031961319623196331964319653196631967319683196931970319713197231973319743197531976319773197831979319803198131982319833198431985319863198731988319893199031991319923199331994319953199631997319983199932000320013200232003320043200532006320073200832009320103201132012320133201432015320163201732018320193202032021320223202332024320253202632027320283202932030320313203232033320343203532036320373203832039320403204132042320433204432045320463204732048320493205032051320523205332054320553205632057320583205932060320613206232063320643206532066320673206832069320703207132072320733207432075320763207732078320793208032081320823208332084320853208632087320883208932090320913209232093320943209532096320973209832099321003210132102321033210432105321063210732108321093211032111321123211332114321153211632117321183211932120321213212232123321243212532126321273212832129321303213132132321333213432135321363213732138321393214032141321423214332144321453214632147321483214932150321513215232153321543215532156321573215832159321603216132162321633216432165321663216732168321693217032171321723217332174321753217632177321783217932180321813218232183321843218532186321873218832189321903219132192321933219432195321963219732198321993220032201322023220332204322053220632207322083220932210322113221232213322143221532216322173221832219322203222132222322233222432225322263222732228322293223032231322323223332234322353223632237322383223932240322413224232243322443224532246322473224832249322503225132252322533225432255322563225732258322593226032261322623226332264322653226632267322683226932270322713227232273322743227532276322773227832279322803228132282322833228432285322863228732288322893229032291322923229332294322953229632297322983229932300323013230232303323043230532306323073230832309323103231132312323133231432315323163231732318323193232032321323223232332324323253232632327323283232932330323313233232333323343233532336323373233832339323403234132342323433234432345323463234732348323493235032351323523235332354323553235632357323583235932360323613236232363323643236532366323673236832369323703237132372323733237432375323763237732378323793238032381323823238332384323853238632387323883238932390323913239232393323943239532396323973239832399324003240132402324033240432405324063240732408324093241032411324123241332414324153241632417324183241932420324213242232423324243242532426324273242832429324303243132432324333243432435324363243732438324393244032441324423244332444324453244632447324483244932450324513245232453324543245532456324573245832459324603246132462324633246432465324663246732468324693247032471324723247332474324753247632477324783247932480324813248232483324843248532486324873248832489324903249132492324933249432495324963249732498324993250032501325023250332504325053250632507325083250932510325113251232513325143251532516325173251832519325203252132522325233252432525325263252732528325293253032531325323253332534325353253632537325383253932540325413254232543325443254532546325473254832549325503255132552325533255432555325563255732558325593256032561325623256332564325653256632567325683256932570325713257232573325743257532576325773257832579325803258132582325833258432585325863258732588325893259032591325923259332594325953259632597325983259932600326013260232603326043260532606326073260832609326103261132612326133261432615326163261732618326193262032621326223262332624326253262632627326283262932630326313263232633326343263532636326373263832639326403264132642326433264432645326463264732648326493265032651326523265332654326553265632657326583265932660326613266232663326643266532666326673266832669326703267132672326733267432675326763267732678326793268032681326823268332684326853268632687326883268932690326913269232693326943269532696326973269832699327003270132702327033270432705327063270732708327093271032711327123271332714327153271632717327183271932720327213272232723327243272532726327273272832729327303273132732327333273432735327363273732738327393274032741327423274332744327453274632747327483274932750327513275232753327543275532756327573275832759327603276132762327633276432765327663276732768327693277032771327723277332774327753277632777327783277932780327813278232783327843278532786327873278832789327903279132792327933279432795327963279732798327993280032801328023280332804328053280632807328083280932810328113281232813328143281532816328173281832819328203282132822328233282432825328263282732828328293283032831328323283332834328353283632837328383283932840328413284232843328443284532846328473284832849328503285132852328533285432855328563285732858328593286032861328623286332864328653286632867328683286932870328713287232873328743287532876328773287832879328803288132882328833288432885328863288732888328893289032891328923289332894328953289632897328983289932900329013290232903329043290532906329073290832909329103291132912329133291432915329163291732918329193292032921329223292332924329253292632927329283292932930329313293232933329343293532936329373293832939329403294132942329433294432945329463294732948329493295032951329523295332954329553295632957329583295932960329613296232963329643296532966329673296832969329703297132972329733297432975329763297732978329793298032981329823298332984329853298632987329883298932990329913299232993329943299532996329973299832999330003300133002330033300433005330063300733008330093301033011330123301333014330153301633017330183301933020330213302233023330243302533026330273302833029330303303133032330333303433035330363303733038330393304033041330423304333044330453304633047330483304933050330513305233053330543305533056330573305833059330603306133062330633306433065330663306733068330693307033071330723307333074330753307633077330783307933080330813308233083330843308533086330873308833089330903309133092330933309433095330963309733098330993310033101331023310333104331053310633107331083310933110331113311233113331143311533116331173311833119331203312133122331233312433125331263312733128331293313033131331323313333134331353313633137331383313933140331413314233143331443314533146331473314833149331503315133152331533315433155331563315733158331593316033161331623316333164331653316633167331683316933170331713317233173331743317533176331773317833179331803318133182331833318433185331863318733188331893319033191331923319333194331953319633197331983319933200332013320233203332043320533206332073320833209332103321133212332133321433215332163321733218332193322033221332223322333224332253322633227332283322933230332313323233233332343323533236332373323833239332403324133242332433324433245332463324733248332493325033251332523325333254332553325633257332583325933260332613326233263332643326533266332673326833269332703327133272332733327433275332763327733278332793328033281332823328333284332853328633287332883328933290332913329233293332943329533296332973329833299333003330133302333033330433305333063330733308333093331033311333123331333314333153331633317333183331933320333213332233323333243332533326333273332833329333303333133332333333333433335333363333733338333393334033341333423334333344333453334633347333483334933350333513335233353333543335533356333573335833359333603336133362333633336433365333663336733368333693337033371333723337333374333753337633377333783337933380333813338233383333843338533386333873338833389333903339133392333933339433395333963339733398333993340033401334023340333404334053340633407334083340933410334113341233413334143341533416334173341833419334203342133422334233342433425334263342733428334293343033431334323343333434334353343633437334383343933440334413344233443334443344533446334473344833449334503345133452334533345433455334563345733458334593346033461334623346333464334653346633467334683346933470334713347233473334743347533476334773347833479334803348133482334833348433485334863348733488334893349033491334923349333494334953349633497334983349933500335013350233503335043350533506335073350833509335103351133512335133351433515335163351733518335193352033521335223352333524335253352633527335283352933530335313353233533335343353533536335373353833539335403354133542335433354433545335463354733548335493355033551335523355333554335553355633557335583355933560335613356233563335643356533566335673356833569335703357133572335733357433575335763357733578335793358033581335823358333584335853358633587335883358933590335913359233593335943359533596335973359833599336003360133602336033360433605336063360733608336093361033611336123361333614336153361633617336183361933620336213362233623336243362533626336273362833629336303363133632336333363433635336363363733638336393364033641336423364333644336453364633647336483364933650336513365233653336543365533656336573365833659336603366133662336633366433665336663366733668336693367033671336723367333674336753367633677336783367933680336813368233683336843368533686336873368833689336903369133692336933369433695336963369733698336993370033701337023370333704337053370633707337083370933710337113371233713337143371533716337173371833719337203372133722337233372433725337263372733728337293373033731337323373333734337353373633737337383373933740337413374233743337443374533746337473374833749337503375133752337533375433755337563375733758337593376033761337623376333764337653376633767337683376933770337713377233773337743377533776337773377833779337803378133782337833378433785337863378733788337893379033791337923379333794337953379633797337983379933800338013380233803338043380533806338073380833809338103381133812338133381433815338163381733818338193382033821338223382333824338253382633827338283382933830338313383233833338343383533836338373383833839338403384133842338433384433845338463384733848338493385033851338523385333854338553385633857338583385933860338613386233863338643386533866338673386833869338703387133872338733387433875338763387733878338793388033881338823388333884338853388633887338883388933890338913389233893338943389533896338973389833899339003390133902339033390433905339063390733908339093391033911339123391333914339153391633917339183391933920339213392233923339243392533926339273392833929339303393133932339333393433935339363393733938339393394033941339423394333944339453394633947339483394933950339513395233953339543395533956339573395833959339603396133962339633396433965339663396733968339693397033971339723397333974339753397633977339783397933980339813398233983339843398533986339873398833989339903399133992339933399433995339963399733998339993400034001340023400334004340053400634007340083400934010340113401234013340143401534016340173401834019340203402134022340233402434025340263402734028340293403034031340323403334034340353403634037340383403934040340413404234043340443404534046340473404834049340503405134052340533405434055340563405734058340593406034061340623406334064340653406634067340683406934070340713407234073340743407534076340773407834079340803408134082340833408434085340863408734088340893409034091340923409334094340953409634097340983409934100341013410234103341043410534106341073410834109341103411134112341133411434115341163411734118341193412034121341223412334124341253412634127341283412934130341313413234133341343413534136341373413834139341403414134142341433414434145341463414734148341493415034151341523415334154341553415634157341583415934160341613416234163341643416534166341673416834169341703417134172341733417434175341763417734178341793418034181341823418334184341853418634187341883418934190341913419234193341943419534196341973419834199342003420134202342033420434205342063420734208342093421034211342123421334214342153421634217342183421934220342213422234223342243422534226342273422834229342303423134232342333423434235342363423734238342393424034241342423424334244342453424634247342483424934250342513425234253342543425534256342573425834259342603426134262342633426434265342663426734268342693427034271342723427334274342753427634277342783427934280342813428234283342843428534286342873428834289342903429134292342933429434295342963429734298342993430034301343023430334304343053430634307343083430934310343113431234313343143431534316343173431834319343203432134322343233432434325343263432734328343293433034331343323433334334343353433634337343383433934340343413434234343343443434534346343473434834349343503435134352343533435434355343563435734358343593436034361343623436334364343653436634367343683436934370343713437234373343743437534376343773437834379343803438134382343833438434385343863438734388343893439034391343923439334394343953439634397343983439934400344013440234403344043440534406344073440834409344103441134412344133441434415344163441734418344193442034421344223442334424344253442634427344283442934430344313443234433344343443534436344373443834439344403444134442344433444434445344463444734448344493445034451344523445334454344553445634457344583445934460344613446234463344643446534466344673446834469344703447134472344733447434475344763447734478344793448034481344823448334484344853448634487344883448934490344913449234493344943449534496344973449834499345003450134502345033450434505345063450734508345093451034511345123451334514345153451634517345183451934520345213452234523345243452534526345273452834529345303453134532345333453434535345363453734538345393454034541345423454334544345453454634547345483454934550345513455234553345543455534556345573455834559345603456134562345633456434565345663456734568345693457034571345723457334574345753457634577345783457934580345813458234583345843458534586345873458834589345903459134592345933459434595345963459734598345993460034601346023460334604346053460634607346083460934610346113461234613346143461534616346173461834619346203462134622346233462434625346263462734628346293463034631346323463334634346353463634637346383463934640346413464234643346443464534646346473464834649346503465134652346533465434655346563465734658346593466034661346623466334664346653466634667346683466934670346713467234673346743467534676346773467834679346803468134682346833468434685346863468734688346893469034691346923469334694346953469634697346983469934700347013470234703347043470534706347073470834709347103471134712347133471434715347163471734718347193472034721347223472334724347253472634727347283472934730347313473234733347343473534736347373473834739347403474134742347433474434745347463474734748347493475034751347523475334754347553475634757347583475934760347613476234763347643476534766347673476834769347703477134772347733477434775347763477734778347793478034781347823478334784347853478634787347883478934790347913479234793347943479534796347973479834799348003480134802348033480434805348063480734808348093481034811348123481334814348153481634817348183481934820348213482234823348243482534826348273482834829348303483134832348333483434835348363483734838348393484034841348423484334844348453484634847348483484934850348513485234853348543485534856348573485834859348603486134862348633486434865348663486734868348693487034871348723487334874348753487634877348783487934880348813488234883348843488534886348873488834889348903489134892348933489434895348963489734898348993490034901349023490334904349053490634907349083490934910349113491234913349143491534916349173491834919349203492134922349233492434925349263492734928349293493034931349323493334934349353493634937349383493934940349413494234943349443494534946349473494834949349503495134952349533495434955349563495734958349593496034961349623496334964349653496634967349683496934970349713497234973349743497534976349773497834979349803498134982349833498434985349863498734988349893499034991349923499334994349953499634997349983499935000350013500235003350043500535006350073500835009350103501135012350133501435015350163501735018350193502035021350223502335024350253502635027350283502935030350313503235033350343503535036350373503835039350403504135042350433504435045350463504735048350493505035051350523505335054350553505635057350583505935060350613506235063350643506535066350673506835069350703507135072350733507435075350763507735078350793508035081350823508335084350853508635087350883508935090350913509235093350943509535096350973509835099351003510135102351033510435105351063510735108351093511035111351123511335114351153511635117351183511935120351213512235123351243512535126351273512835129351303513135132351333513435135351363513735138351393514035141351423514335144351453514635147351483514935150351513515235153351543515535156351573515835159351603516135162351633516435165351663516735168351693517035171351723517335174351753517635177351783517935180351813518235183
  1. // NOTE: This file should be saved as UTF-8 w/ BOM
  2. #include <httplib.h>
  3. #include <signal.h>
  4. #ifndef _WIN32
  5. #include <arpa/inet.h>
  6. #include <ctime>
  7. #include <curl/curl.h>
  8. #include <netinet/in.h>
  9. #include <sys/socket.h>
  10. #include <sys/time.h>
  11. #include <unistd.h>
  12. #endif
  13. #include <gtest/gtest.h>
  14. #include <algorithm>
  15. #include <atomic>
  16. #include <cctype>
  17. #include <chrono>
  18. #include <clocale>
  19. #include <cstdio>
  20. #include <fstream>
  21. #include <future>
  22. #include <limits>
  23. #include <memory>
  24. #include <sstream>
  25. #include <stdexcept>
  26. #include <thread>
  27. #include <type_traits>
  28. #include <vector>
  29. #if __cplusplus >= 202002L
  30. inline std::string u8_to_string(const char8_t *s) {
  31. return std::string(reinterpret_cast<const char *>(s));
  32. }
  33. #define U8(x) u8_to_string(u8##x)
  34. #else
  35. #define U8(x) u8##x
  36. #endif
  37. #define SERVER_CERT_FILE "./cert.pem"
  38. #define SERVER_CERT2_FILE "./cert2.pem"
  39. #define SERVER_CERT_IP_CN_FILE "./cert_ip_cn.pem"
  40. #define SERVER_CERT_DNS_CN_FILE "./cert_dns_cn.pem"
  41. #define SERVER_CERT_IPV6_FILE "./cert_ipv6.pem"
  42. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  43. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  44. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  45. #define CA_CERT_FILE "./ca-bundle.crt"
  46. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  47. #define CLIENT_CA_CERT_DIR "."
  48. #define CLIENT_CERT_FILE "./client.cert.pem"
  49. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  50. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  51. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  52. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  53. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  54. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  55. #else
  56. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  57. #endif
  58. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  59. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  61. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  62. #ifdef CPPHTTPLIB_SSL_ENABLED
  63. namespace httplib {
  64. namespace tls {
  65. // Declared here for the split build, where the TLS abstraction declarations
  66. // live below the split border; the definitions are linked from httplib.cc.
  67. ca_store_t create_ca_store(const char *pem, size_t len);
  68. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  69. std::vector<std::string> get_ca_names(ctx_t ctx);
  70. ctx_t create_server_context();
  71. void free_context(ctx_t ctx);
  72. bool set_server_cert_file(ctx_t ctx, const char *cert_path,
  73. const char *key_path, const char *password);
  74. ctx_t create_client_context();
  75. void set_verify_client(ctx_t ctx, bool require);
  76. session_t create_session(ctx_t ctx, socket_t sock);
  77. void free_session(session_t session);
  78. bool connect_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  79. time_t timeout_usec, TlsError *err,
  80. const std::function<bool()> &interrupted);
  81. bool accept_nonblocking(session_t session, socket_t sock, time_t timeout_sec,
  82. time_t timeout_usec, TlsError *err,
  83. const std::function<bool()> &interrupted);
  84. ssize_t read(session_t session, void *buf, size_t len, TlsError &err);
  85. ssize_t write(session_t session, const void *buf, size_t len, TlsError &err);
  86. void shutdown(session_t session, bool graceful);
  87. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  88. namespace impl {
  89. SecTrustSettingsResult
  90. macos_ssl_trust_settings_result(CFArrayRef trust_settings);
  91. } // namespace impl
  92. #endif
  93. } // namespace tls
  94. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  95. namespace detail {
  96. bool ssl_free_buffers_is_safe(unsigned long version);
  97. } // namespace detail
  98. #endif
  99. } // namespace httplib
  100. #endif
  101. using namespace std;
  102. using namespace httplib;
  103. const char *HOST = "localhost";
  104. static int get_base_port() {
  105. const char *shard = getenv("GTEST_SHARD_INDEX");
  106. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  107. }
  108. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  109. // New standalone tests MUST use svr.bind_to_any_port() instead.
  110. const int PORT = get_base_port();
  111. const string LONG_QUERY_VALUE = string(25000, '@');
  112. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  113. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  114. const string TOO_LONG_QUERY_URL =
  115. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  116. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  117. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  118. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  119. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  120. return file.name == key;
  121. });
  122. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  123. return *it;
  124. #else
  125. if (it != items.end()) { return *it; }
  126. throw std::runtime_error("invalid multipart form data name error");
  127. #endif
  128. }
  129. static void read_file(const std::string &path, std::string &out) {
  130. std::ifstream fs(path, std::ios_base::binary);
  131. if (!fs) {
  132. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  133. return;
  134. #else
  135. throw std::runtime_error("File not found: " + path);
  136. #endif
  137. }
  138. fs.seekg(0, std::ios_base::end);
  139. auto size = fs.tellg();
  140. fs.seekg(0);
  141. out.resize(static_cast<size_t>(size));
  142. fs.read(&out[0], static_cast<std::streamsize>(size));
  143. }
  144. // Failures of the services that the *_Online tests reach, unrelated to the
  145. // client under test: httpbingo.org intermittently answers with gateway errors,
  146. // and badssl.com drops connections from CI runners before it sends its
  147. // certificate. A handshake that fails before any verdict on the certificate is
  148. // left to the tests against local servers.
  149. static bool is_service_failure(const Result &res) {
  150. if (res) {
  151. return res->status == StatusCode::BadGateway_502 ||
  152. res->status == StatusCode::ServiceUnavailable_503 ||
  153. res->status == StatusCode::GatewayTimeout_504;
  154. }
  155. return res.error() == Error::SSLConnection;
  156. }
  157. template <typename F> static Result retry_service_failures(F &&send) {
  158. auto res = send();
  159. for (auto wait : {1, 2}) {
  160. if (!is_service_failure(res)) { break; }
  161. std::this_thread::sleep_for(std::chrono::seconds(wait));
  162. res = send();
  163. }
  164. return res;
  165. }
  166. #define SKIP_ON_SERVICE_FAILURE(res) \
  167. do { \
  168. if (is_service_failure(res)) { \
  169. if (res) { \
  170. GTEST_SKIP() << "service failure: status " << (res)->status; \
  171. } else { \
  172. GTEST_SKIP() << "service failure: " << to_string((res).error()); \
  173. } \
  174. } \
  175. } while (0)
  176. class UnixSocketTest : public ::testing::Test {
  177. protected:
  178. void TearDown() override { std::remove(pathname_.c_str()); }
  179. void client_GET(const std::string &addr) {
  180. httplib::Client cli{addr};
  181. cli.set_address_family(AF_UNIX);
  182. ASSERT_TRUE(cli.is_valid());
  183. const auto &result = cli.Get(pattern_);
  184. ASSERT_TRUE(result) << "error: " << result.error();
  185. const auto &resp = result.value();
  186. EXPECT_EQ(resp.status, StatusCode::OK_200);
  187. EXPECT_EQ(resp.body, content_);
  188. }
  189. static std::string make_sock_path() {
  190. const char *shard = getenv("GTEST_SHARD_INDEX");
  191. return shard ? std::string("./httplib-server-") + shard + ".sock"
  192. : "./httplib-server.sock";
  193. }
  194. const std::string pathname_{make_sock_path()};
  195. const std::string pattern_{"/hi"};
  196. const std::string content_{"Hello World!"};
  197. };
  198. TEST_F(UnixSocketTest, pathname) {
  199. httplib::Server svr;
  200. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  201. res.set_content(content_, "text/plain");
  202. });
  203. std::thread t{[&] {
  204. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  205. }};
  206. auto se = detail::scope_exit([&] {
  207. svr.stop();
  208. t.join();
  209. ASSERT_FALSE(svr.is_running());
  210. });
  211. svr.wait_until_ready();
  212. ASSERT_TRUE(svr.is_running());
  213. client_GET(pathname_);
  214. // ".//x.sock", which is not taken for a URL
  215. client_GET("./" + pathname_.substr(1));
  216. }
  217. #if defined(__linux__) || \
  218. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  219. TEST_F(UnixSocketTest, PeerPid) {
  220. httplib::Server svr;
  221. std::string remote_port_val;
  222. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  223. res.set_content(content_, "text/plain");
  224. remote_port_val = std::to_string(req.remote_port);
  225. });
  226. std::thread t{[&] {
  227. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  228. }};
  229. auto se = detail::scope_exit([&] {
  230. svr.stop();
  231. t.join();
  232. ASSERT_FALSE(svr.is_running());
  233. });
  234. svr.wait_until_ready();
  235. ASSERT_TRUE(svr.is_running());
  236. client_GET(pathname_);
  237. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  238. }
  239. #endif
  240. #ifdef __linux__
  241. TEST_F(UnixSocketTest, abstract) {
  242. constexpr char svr_path[]{"\x00httplib-server.sock"};
  243. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  244. httplib::Server svr;
  245. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  246. res.set_content(content_, "text/plain");
  247. });
  248. std::thread t{[&] {
  249. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  250. }};
  251. auto se = detail::scope_exit([&] {
  252. svr.stop();
  253. t.join();
  254. ASSERT_FALSE(svr.is_running());
  255. });
  256. svr.wait_until_ready();
  257. ASSERT_TRUE(svr.is_running());
  258. client_GET(abstract_addr);
  259. }
  260. #endif
  261. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  262. httplib::Server svr;
  263. std::string received_host_header;
  264. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  265. // Capture the Host header sent by the client
  266. auto host_iter = req.headers.find("Host");
  267. if (host_iter != req.headers.end()) {
  268. received_host_header = host_iter->second;
  269. }
  270. res.set_content(content_, "text/plain");
  271. });
  272. std::thread t{[&] {
  273. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  274. }};
  275. auto se = detail::scope_exit([&] {
  276. svr.stop();
  277. t.join();
  278. ASSERT_FALSE(svr.is_running());
  279. });
  280. svr.wait_until_ready();
  281. ASSERT_TRUE(svr.is_running());
  282. // Test that Host header is automatically set to "localhost" for Unix socket
  283. // connections
  284. httplib::Client cli{pathname_};
  285. cli.set_address_family(AF_UNIX);
  286. ASSERT_TRUE(cli.is_valid());
  287. const auto &result = cli.Get(pattern_);
  288. ASSERT_TRUE(result) << "error: " << result.error();
  289. const auto &resp = result.value();
  290. EXPECT_EQ(resp.status, StatusCode::OK_200);
  291. EXPECT_EQ(resp.body, content_);
  292. // Verify that Host header was automatically set to "localhost"
  293. EXPECT_EQ(received_host_header, "localhost");
  294. }
  295. TEST_F(UnixSocketTest, RedirectStaysOnSocket) {
  296. // Another socket in the working directory, which a Location can name as
  297. // its host
  298. const auto other_path = "other-" + pathname_.substr(2);
  299. httplib::Server svr;
  300. svr.Get("/redirect", [&](const httplib::Request &, httplib::Response &res) {
  301. // An absolute Location naming the Host this client sends
  302. res.set_redirect("http://localhost" + pattern_);
  303. });
  304. svr.Get("/cross", [&](const httplib::Request &, httplib::Response &res) {
  305. res.set_redirect("http://" + other_path + pattern_);
  306. });
  307. svr.Get("/mapped", [&](const httplib::Request &, httplib::Response &res) {
  308. res.set_redirect("http://mapped.test" + pattern_);
  309. });
  310. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  311. res.set_header("X-Auth", req.get_header_value("Authorization"));
  312. res.set_content(content_, "text/plain");
  313. });
  314. httplib::Server other;
  315. other.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  316. res.set_content("other", "text/plain");
  317. });
  318. std::thread t{[&] {
  319. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  320. }};
  321. std::thread t2{[&] {
  322. ASSERT_TRUE(other.set_address_family(AF_UNIX).listen(other_path, 80));
  323. }};
  324. auto se = detail::scope_exit([&] {
  325. svr.stop();
  326. other.stop();
  327. t.join();
  328. t2.join();
  329. std::remove(other_path.c_str());
  330. });
  331. svr.wait_until_ready();
  332. other.wait_until_ready();
  333. httplib::Client cli{pathname_};
  334. cli.set_address_family(AF_UNIX);
  335. cli.set_follow_location(true);
  336. cli.set_bearer_token_auth("token");
  337. // Another host: the same socket, without the credentials
  338. auto res = cli.Get("/cross");
  339. ASSERT_TRUE(res) << "error: " << res.error();
  340. EXPECT_EQ(StatusCode::OK_200, res->status);
  341. EXPECT_EQ(content_, res->body);
  342. EXPECT_EQ("", res->get_header_value("X-Auth"));
  343. // localhost is this client's own host
  344. res = cli.Get("/redirect");
  345. ASSERT_TRUE(res) << "error: " << res.error();
  346. EXPECT_EQ(StatusCode::OK_200, res->status);
  347. EXPECT_EQ(content_, res->body);
  348. EXPECT_EQ("Bearer token", res->get_header_value("X-Auth"));
  349. // A host the caller mapped to a socket goes there
  350. cli.set_direct_hostname_addr_map({{"mapped.test", other_path}});
  351. res = cli.Get("/mapped");
  352. ASSERT_TRUE(res) << "error: " << res.error();
  353. EXPECT_EQ(StatusCode::OK_200, res->status);
  354. EXPECT_EQ("other", res->body);
  355. }
  356. #ifndef _WIN32
  357. TEST(SocketStream, wait_writable_UNIX) {
  358. int fds[2];
  359. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  360. const auto asSocketStream = [&](socket_t fd,
  361. std::function<bool(Stream &)> func) {
  362. return detail::process_client_socket(
  363. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  364. };
  365. asSocketStream(fds[0], [&](Stream &s0) {
  366. EXPECT_EQ(s0.socket(), fds[0]);
  367. EXPECT_TRUE(s0.wait_writable());
  368. EXPECT_TRUE(s0.is_peer_alive());
  369. EXPECT_EQ(0, close(fds[1]));
  370. EXPECT_FALSE(s0.is_peer_alive());
  371. return true;
  372. });
  373. EXPECT_EQ(0, close(fds[0]));
  374. }
  375. TEST(SocketStream, wait_writable_INET) {
  376. sockaddr_in addr;
  377. memset(&addr, 0, sizeof(addr));
  378. addr.sin_family = AF_INET;
  379. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  380. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  381. int disconnected_svr_sock = -1;
  382. std::thread svr{[&] {
  383. const int s = socket(AF_INET, SOCK_STREAM, 0);
  384. ASSERT_LE(0, s);
  385. // PORT + 1 is shared with the SSL redirect tests and with
  386. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  387. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  388. // because that happens on a worker thread the ASSERT does not stop the
  389. // test: it runs on and fails at the disconnected_svr_sock check instead.
  390. default_socket_options(s);
  391. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  392. ASSERT_EQ(0, listen(s, 1));
  393. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  394. ASSERT_EQ(0, close(s));
  395. }};
  396. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  397. std::thread cli{[&] {
  398. const int s = socket(AF_INET, SOCK_STREAM, 0);
  399. ASSERT_LE(0, s);
  400. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  401. ASSERT_EQ(0, close(s));
  402. }};
  403. cli.join();
  404. svr.join();
  405. ASSERT_NE(disconnected_svr_sock, -1);
  406. const auto asSocketStream = [&](socket_t fd,
  407. std::function<bool(Stream &)> func) {
  408. return detail::process_client_socket(
  409. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  410. };
  411. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  412. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  413. // wait_writable() returns true because select_write() only checks if the
  414. // send buffer has space. Peer disconnection is detected later by send().
  415. EXPECT_TRUE(ss.wait_writable());
  416. return true;
  417. });
  418. ASSERT_EQ(0, close(disconnected_svr_sock));
  419. }
  420. #endif // #ifndef _WIN32
  421. TEST(SetSocketOptTest, TcpNoDelay) {
  422. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  423. ASSERT_NE(sock, INVALID_SOCKET);
  424. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  425. int val = 0;
  426. socklen_t len = sizeof(val);
  427. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  428. reinterpret_cast<char *>(&val), &len));
  429. EXPECT_NE(val, 0);
  430. detail::close_socket(sock);
  431. }
  432. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  433. // accept() reports failures through WSAGetLastError() on Windows and through
  434. // errno everywhere else. Asking the wrong one is what made the accept loop
  435. // treat every recoverable failure as fatal on Windows.
  436. struct Classification {
  437. bool resource;
  438. bool transient;
  439. };
  440. auto classify = [](int err) {
  441. #ifdef _WIN32
  442. WSASetLastError(err);
  443. #else
  444. errno = err;
  445. #endif
  446. // Read both before asserting: an assertion may clobber the error slot.
  447. Classification c;
  448. c.resource = detail::is_accept_resource_error();
  449. c.transient = detail::is_accept_transient_error();
  450. return c;
  451. };
  452. #ifdef _WIN32
  453. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  454. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  455. WSAECONNRESET, WSAECONNABORTED};
  456. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  457. #else
  458. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  459. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  460. ECONNABORTED};
  461. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  462. #endif
  463. for (auto err : resource_errors) {
  464. const auto c = classify(err);
  465. EXPECT_TRUE(c.resource) << "error " << err;
  466. EXPECT_FALSE(c.transient) << "error " << err;
  467. }
  468. for (auto err : transient_errors) {
  469. const auto c = classify(err);
  470. EXPECT_TRUE(c.transient) << "error " << err;
  471. EXPECT_FALSE(c.resource) << "error " << err;
  472. }
  473. for (auto err : fatal_errors) {
  474. const auto c = classify(err);
  475. EXPECT_FALSE(c.resource) << "error " << err;
  476. EXPECT_FALSE(c.transient) << "error " << err;
  477. }
  478. #ifdef _WIN32
  479. WSASetLastError(0);
  480. #else
  481. errno = 0;
  482. #endif
  483. }
  484. TEST(ClientTest, MoveConstructible) {
  485. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  486. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  487. }
  488. TEST(ClientTest, MoveAssignable) {
  489. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  490. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  491. }
  492. #ifdef _WIN32
  493. TEST(StartupTest, WSAStartup) {
  494. WSADATA wsaData;
  495. int ret = WSAStartup(0x0002, &wsaData);
  496. ASSERT_EQ(0, ret);
  497. }
  498. #endif
  499. TEST(DecodePathTest, PercentCharacter) {
  500. EXPECT_EQ(
  501. decode_path_component(
  502. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  503. U8("descrip=Gastos áéíóúñÑ 6"));
  504. }
  505. TEST(DecodePathTest, PercentCharacterNUL) {
  506. string expected;
  507. expected.push_back('x');
  508. expected.push_back('\0');
  509. expected.push_back('x');
  510. EXPECT_EQ(decode_path_component("x%00x"), expected);
  511. }
  512. TEST(DecodePathTest, UnicodeEncoding) {
  513. // %u0041 = 'A' (1-byte UTF-8)
  514. EXPECT_EQ("A", decode_path_component("%u0041"));
  515. // %u00E9 = 'é' (2-byte UTF-8)
  516. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  517. // %u3042 = 'あ' (3-byte UTF-8)
  518. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  519. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  520. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  521. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  522. // neighbours)
  523. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  524. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  525. }
  526. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  527. // A sign or whitespace inside the two-character escape window must not be
  528. // accepted as a valid percent-encoding; the sequence is passed through
  529. // literally, matching decode_uri_component / decode_path_component.
  530. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  531. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  532. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  533. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  534. // Well-formed escapes still decode.
  535. EXPECT_EQ("-", decode_query_component("%2D", false));
  536. EXPECT_EQ("A", decode_query_component("%41", false));
  537. }
  538. TEST(SanitizeFilenameTest, VariousPatterns) {
  539. // Path traversal
  540. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  541. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  542. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  543. // Normal and edge cases
  544. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  545. EXPECT_EQ("filename.txt",
  546. httplib::sanitize_filename("/path/to/filename.txt"));
  547. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  548. EXPECT_EQ("", httplib::sanitize_filename(".."));
  549. EXPECT_EQ("", httplib::sanitize_filename(""));
  550. // Null bytes stripped
  551. EXPECT_EQ("safe.txt",
  552. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  553. // Whitespace-only rejected
  554. EXPECT_EQ("", httplib::sanitize_filename(" "));
  555. }
  556. // On Windows a ':' ends a drive prefix or names an NTFS stream, so what comes
  557. // before it is dropped; anywhere else it is an ordinary file name character.
  558. TEST(SanitizeFilenameTest, ColonEndsPrefixOnlyOnWindows) {
  559. #ifdef _WIN32
  560. EXPECT_EQ("", httplib::sanitize_filename("C:.."));
  561. EXPECT_EQ("evil.dll", httplib::sanitize_filename("C:evil.dll"));
  562. EXPECT_EQ("stream", httplib::sanitize_filename("a.txt:stream"));
  563. #else
  564. EXPECT_EQ("C:..", httplib::sanitize_filename("C:.."));
  565. EXPECT_EQ("C:evil.dll", httplib::sanitize_filename("C:evil.dll"));
  566. EXPECT_EQ("a.txt:stream", httplib::sanitize_filename("a.txt:stream"));
  567. #endif
  568. }
  569. // Forward declaration (see the base64_encode note below): split builds move the
  570. // definition into httplib.cc, so re-declaring it here lets the test link.
  571. namespace httplib {
  572. namespace detail {
  573. bool is_chunked_transfer_encoding(const Headers &headers);
  574. } // namespace detail
  575. } // namespace httplib
  576. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  577. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  578. auto make = [](std::initializer_list<const char *> lines) {
  579. Headers h;
  580. for (auto te : lines) {
  581. if (te) { h.emplace("Transfer-Encoding", te); }
  582. }
  583. return h;
  584. };
  585. // Sole coding, matched case-insensitively.
  586. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  587. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  588. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  589. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  590. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  591. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  592. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  593. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  594. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  595. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  596. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  597. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  598. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  599. // were received, into one list. Headers preserves that order, so the answer
  600. // is decided by the last coding of the last line and the order the lines
  601. // arrived in is significant.
  602. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  603. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  604. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  605. // The split can fall anywhere in the list.
  606. EXPECT_TRUE(
  607. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  608. EXPECT_FALSE(
  609. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  610. // A trailing line naming no coding leaves the list ending in nothing, so it
  611. // must not inherit the chunked from the line before it.
  612. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  613. }
  614. // Forward declarations (see the base64_encode note below).
  615. namespace httplib {
  616. namespace detail {
  617. bool parse_status_line(const char *line, std::string &version, int &status,
  618. std::string &reason);
  619. std::string file_extension(const std::string &path);
  620. std::string
  621. find_content_type(const std::string &path,
  622. const std::map<std::string, std::string> &user_data,
  623. const std::string &default_content_type);
  624. bool can_compress_content_type(const std::string &content_type);
  625. bool is_prohibited_header_name(const std::string &name);
  626. bool is_valid_path(const std::string &path);
  627. #ifdef CPPHTTPLIB_SSL_ENABLED
  628. bool match_hostname(const std::string &pattern, const std::string &hostname);
  629. #endif
  630. } // namespace detail
  631. } // namespace httplib
  632. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  633. struct {
  634. const char *line;
  635. const char *version;
  636. int status;
  637. const char *reason;
  638. } cases[] = {
  639. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  640. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  641. // The reason phrase may be empty, or left out along with its space.
  642. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  643. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  644. };
  645. for (const auto &c : cases) {
  646. std::string version;
  647. int status = 0;
  648. std::string reason = "unset";
  649. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  650. << c.line;
  651. EXPECT_EQ(c.version, version);
  652. EXPECT_EQ(c.status, status);
  653. EXPECT_EQ(c.reason, reason);
  654. }
  655. }
  656. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  657. const char *lines[] = {
  658. "HTTP/2 200 OK\r\n",
  659. "HTTP/1.2 200 OK\r\n",
  660. "HTTP/1.1 20 OK\r\n",
  661. "HTTP/1.1 2000 OK\r\n",
  662. "HTTP/1.1 2x0 OK\r\n",
  663. "HTTP/1.1 200 OK\r\n",
  664. "HTTP/1.1 200OK\r\n",
  665. "HTTP/1.1 200 O\rK\r\n",
  666. "HTTP/1.1 200 OK",
  667. "HTTP/1.1 200 OK\r\nX",
  668. "",
  669. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  670. "HTTP/1.1 200 OK\n",
  671. #endif
  672. };
  673. for (auto line : lines) {
  674. std::string version;
  675. int status = 0;
  676. std::string reason;
  677. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  678. << line;
  679. }
  680. }
  681. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  682. // Long enough to overflow the stack when matched with std::regex.
  683. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  684. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  685. std::string version;
  686. int status = 0;
  687. std::string reason;
  688. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  689. EXPECT_EQ(200, status);
  690. EXPECT_EQ(long_reason, reason);
  691. }
  692. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  693. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  694. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  695. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  696. EXPECT_EQ("", detail::file_extension("noext"));
  697. EXPECT_EQ("", detail::file_extension("a."));
  698. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  699. EXPECT_EQ("", detail::file_extension("a.b-c"));
  700. // Long enough to overflow the stack when matched with std::regex.
  701. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  702. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  703. }
  704. #ifdef CPPHTTPLIB_SSL_ENABLED
  705. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  706. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  707. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  708. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  709. // A wildcard needs two labels after it, in the leftmost label only
  710. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  711. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  712. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  713. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  714. EXPECT_FALSE(
  715. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  716. // No name may have an empty label
  717. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  718. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  719. }
  720. #endif
  721. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  722. detail::case_ignore::hash hash;
  723. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  724. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  725. // Long enough to overflow the stack if hashed one call per character.
  726. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  727. }
  728. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  729. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  730. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  731. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  732. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  733. // Same 26-bit hash as html, svg and js.
  734. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  735. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  736. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  737. }
  738. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  739. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  740. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  741. }
  742. }
  743. // ':' names an NTFS stream on Windows and is an ordinary character in a file
  744. // name anywhere else.
  745. TEST(IsValidPathTest, ColonIsRejectedOnlyOnWindows) {
  746. for (auto path : {"/a.txt::$DATA", "/a.txt:Zone.Identifier", "/dir:x/a"}) {
  747. #ifdef _WIN32
  748. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  749. #else
  750. EXPECT_TRUE(detail::is_valid_path(path)) << path;
  751. #endif
  752. }
  753. }
  754. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  755. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  756. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  757. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  758. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  759. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  760. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  761. // Same 26-bit hash as application/json.
  762. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  763. }
  764. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  765. Request req;
  766. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  767. EXPECT_TRUE(req.is_multipart_form_data());
  768. std::string boundary;
  769. EXPECT_TRUE(detail::parse_multipart_boundary(
  770. req.get_header_value("Content-Type"), boundary));
  771. EXPECT_EQ("x", boundary);
  772. }
  773. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  774. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  775. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  776. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  777. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  778. // Same 26-bit hash as REMOTE_ADDR.
  779. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  780. }
  781. // Forward declaration: in split builds split.py strips `inline` and moves the
  782. // definition into httplib.cc, so detail::base64_encode is not visible from the
  783. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  784. // in both header-only and split builds.
  785. namespace httplib {
  786. namespace detail {
  787. std::string base64_encode(const std::string &in);
  788. } // namespace detail
  789. } // namespace httplib
  790. TEST(Base64EncodeTest, KnownAnswers) {
  791. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  792. // where the accumulator's top bit is already set before the next shift.
  793. EXPECT_EQ("", detail::base64_encode(""));
  794. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  795. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  796. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  797. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  798. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  799. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  800. // High bytes keep the top bit set across several rounds.
  801. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  802. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  803. }
  804. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  805. string unescapedCharacters = "-_.!~*'()";
  806. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  807. }
  808. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  809. string reservedCharacters = ";,/?:@&=+$";
  810. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  811. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  812. }
  813. TEST(ClientQueryOrder, PreserveOrder) {
  814. // This test reproduces Issue #2259: client may reorder query parameters
  815. // when sending a GET request. The expected behavior is that the client
  816. // preserves the original query string order when the caller supplied it
  817. // as part of the path.
  818. Server svr;
  819. svr.Get("/", [&](const Request &req, Response &res) {
  820. // Echo back the raw target so the test can assert ordering
  821. res.set_content(req.target, "text/plain");
  822. });
  823. std::thread t{[&] { svr.listen(HOST, PORT); }};
  824. auto se = detail::scope_exit([&] {
  825. svr.stop();
  826. t.join();
  827. ASSERT_FALSE(svr.is_running());
  828. });
  829. svr.wait_until_ready();
  830. Client cli(HOST, PORT);
  831. ASSERT_TRUE(cli.is_valid());
  832. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  833. auto res = cli.Get(original);
  834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  835. // Expect the echoed target to exactly match the original path (order
  836. // preserved)
  837. EXPECT_EQ(res->body, original);
  838. }
  839. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  840. string chineseCharacters = U8("中国語");
  841. string russianCharacters = U8("дом");
  842. string brazilianCharacters = U8("óculos");
  843. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  844. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  845. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  846. "%D0%B4%D0%BE%D0%BC");
  847. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  848. }
  849. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  850. string unescapedCharacters = "-_.!~*'()";
  851. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  852. }
  853. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  854. string reservedCharacters = ";,/?:@&=+$";
  855. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  856. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  857. }
  858. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  859. string chineseCharacters = U8("中国語");
  860. string russianCharacters = U8("дом");
  861. string brazilianCharacters = U8("óculos");
  862. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  863. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  864. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  865. "%D0%B4%D0%BE%D0%BC");
  866. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  867. }
  868. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  869. // Issue #2082 use case: encoding path component with ampersand
  870. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  871. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  872. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  873. }
  874. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  875. string unescapedCharacters = "-_.!~*'()";
  876. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  877. }
  878. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  879. string reservedCharacters = ";,/?:@&=+$#";
  880. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  881. }
  882. TEST(EncodeUriTest, TestUTF8Characters) {
  883. string chineseCharacters = U8("中国語");
  884. string russianCharacters = U8("дом");
  885. string brazilianCharacters = U8("óculos");
  886. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  887. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  888. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  889. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  890. }
  891. TEST(EncodeUriTest, TestCompleteUri) {
  892. string uri =
  893. "https://example.com/path/to/resource?query=value&param=test#fragment";
  894. EXPECT_EQ(
  895. httplib::encode_uri(uri),
  896. "https://example.com/path/to/resource?query=value&param=test#fragment");
  897. }
  898. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  899. string uri =
  900. "https://example.com/path with spaces/file name.html?q=hello world";
  901. EXPECT_EQ(httplib::encode_uri(uri),
  902. "https://example.com/path%20with%20spaces/"
  903. "file%20name.html?q=hello%20world");
  904. }
  905. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  906. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  907. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  908. }
  909. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  910. string unescapedCharacters = "-_.!~*'()";
  911. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  912. }
  913. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  914. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  915. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  916. string encodedBrazilian = "%C3%B3culos";
  917. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  918. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  919. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  920. }
  921. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  922. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  923. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  924. "Piri Tommy Villiers - on & on");
  925. }
  926. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  927. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  928. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  929. }
  930. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  931. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  932. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  933. }
  934. TEST(DecodeUriTest, TestUTF8Characters) {
  935. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  936. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  937. string encodedBrazilian = "%C3%B3culos";
  938. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  939. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  940. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  941. }
  942. TEST(DecodeUriTest, TestCompleteUri) {
  943. string encodedUri = "https://example.com/path%20with%20spaces/"
  944. "file%20name.html?q=hello%20world";
  945. EXPECT_EQ(
  946. httplib::decode_uri(encodedUri),
  947. "https://example.com/path with spaces/file name.html?q=hello world");
  948. }
  949. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  950. string original =
  951. "https://example.com/path with spaces/file name.html?q=hello world";
  952. string encoded = httplib::encode_uri(original);
  953. string decoded = httplib::decode_uri(encoded);
  954. EXPECT_EQ(decoded, original);
  955. }
  956. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  957. // decode_uri is the inverse of encode_uri: an escaped reserved character
  958. // stays encoded so it is not promoted into a real delimiter, while
  959. // non-reserved escapes still decode (like JS decodeURI).
  960. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  961. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  962. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  963. "%3F%3A%40%26%3D%2B%24%2C%3B");
  964. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  965. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  966. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  967. "http://example.com/a%2Fb");
  968. // decode_uri_component still decodes the reserved character.
  969. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  970. }
  971. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  972. string original = "Piri Tommy Villiers - on & on";
  973. string encoded = httplib::encode_uri_component(original);
  974. string decoded = httplib::decode_uri_component(encoded);
  975. EXPECT_EQ(decoded, original);
  976. }
  977. TEST(TrimTests, TrimStringTests) {
  978. EXPECT_EQ("abc", detail::trim_copy("abc"));
  979. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  980. EXPECT_TRUE(detail::trim_copy("").empty());
  981. }
  982. TEST(AsciiTest, LocaleIndependentClassification) {
  983. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  984. // which consult the global C locale: std::isalnum(0xC5) can return true
  985. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  986. // helpers must classify every byte by the ASCII grammar alone.
  987. for (int i = 0; i < 256; i++) {
  988. auto c = static_cast<char>(i);
  989. auto is_digit = i >= '0' && i <= '9';
  990. auto is_upper = i >= 'A' && i <= 'Z';
  991. auto is_lower = i >= 'a' && i <= 'z';
  992. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  993. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  994. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  995. << "byte " << i;
  996. }
  997. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  998. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  999. // Non-ASCII bytes must be percent-encoded, never passed through as
  1000. // alphanumeric.
  1001. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  1002. }
  1003. TEST(FromCharsTest, Double) {
  1004. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  1005. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  1006. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  1007. auto parse = [](const std::string &s, double &v) {
  1008. return detail::from_chars(s.data(), s.data() + s.size(), v);
  1009. };
  1010. double v = -1.0;
  1011. // Representative quality values.
  1012. EXPECT_EQ(parse("0", v).ec, std::errc{});
  1013. EXPECT_DOUBLE_EQ(v, 0.0);
  1014. EXPECT_EQ(parse("1", v).ec, std::errc{});
  1015. EXPECT_DOUBLE_EQ(v, 1.0);
  1016. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  1017. EXPECT_DOUBLE_EQ(v, 0.8);
  1018. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  1019. EXPECT_DOUBLE_EQ(v, 0.001);
  1020. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  1021. EXPECT_DOUBLE_EQ(v, 1.0);
  1022. // A missing integer or fractional part is tolerated.
  1023. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  1024. EXPECT_DOUBLE_EQ(v, 0.5);
  1025. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  1026. EXPECT_DOUBLE_EQ(v, 5.0);
  1027. // Values outside [0, 1] still parse; the caller range-checks them.
  1028. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  1029. EXPECT_DOUBLE_EQ(v, 123.456);
  1030. // Stops at the first byte that is not part of the number and reports where.
  1031. std::string trailing = "0.9, text/html";
  1032. auto r = parse(trailing, v);
  1033. EXPECT_EQ(r.ec, std::errc{});
  1034. EXPECT_DOUBLE_EQ(v, 0.9);
  1035. EXPECT_EQ(*r.ptr, ',');
  1036. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  1037. // outright, and an 'e'/'E' simply ends the number.
  1038. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  1039. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  1040. std::string exp_input = "1.5e3";
  1041. r = parse(exp_input, v);
  1042. EXPECT_EQ(r.ec, std::errc{});
  1043. EXPECT_DOUBLE_EQ(v, 1.5);
  1044. EXPECT_EQ(*r.ptr, 'e');
  1045. // Invalid inputs.
  1046. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  1047. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  1048. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  1049. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  1050. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  1051. // Pathological but well-formed inputs must stay bounded (no overflow, no
  1052. // out-of-bounds table access) and stay within [0, 1] for the caller.
  1053. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  1054. std::errc{});
  1055. EXPECT_DOUBLE_EQ(v, 0.0);
  1056. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  1057. std::errc{});
  1058. EXPECT_GE(v, 0.0);
  1059. EXPECT_LE(v, 1.0);
  1060. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  1061. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  1062. }
  1063. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  1064. // Simple case without quality values
  1065. std::vector<std::string> result1;
  1066. EXPECT_TRUE(detail::parse_accept_header(
  1067. "text/html,application/json,text/plain", result1));
  1068. EXPECT_EQ(result1.size(), 3U);
  1069. EXPECT_EQ(result1[0], "text/html");
  1070. EXPECT_EQ(result1[1], "application/json");
  1071. EXPECT_EQ(result1[2], "text/plain");
  1072. // With quality values
  1073. std::vector<std::string> result2;
  1074. EXPECT_TRUE(detail::parse_accept_header(
  1075. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  1076. EXPECT_EQ(result2.size(), 3U);
  1077. EXPECT_EQ(result2[0], "application/json"); // highest q value
  1078. EXPECT_EQ(result2[1], "text/html");
  1079. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  1080. }
  1081. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  1082. // Mixed with and without quality values
  1083. std::vector<std::string> result;
  1084. EXPECT_TRUE(detail::parse_accept_header(
  1085. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  1086. EXPECT_EQ(result.size(), 3U);
  1087. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  1088. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  1089. EXPECT_EQ(result[2], "application/json"); // q=0.5
  1090. }
  1091. TEST(ParseAcceptHeaderTest, EdgeCases) {
  1092. // Empty header
  1093. std::vector<std::string> empty_result;
  1094. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  1095. EXPECT_TRUE(empty_result.empty());
  1096. // Single type
  1097. std::vector<std::string> single_result;
  1098. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  1099. EXPECT_EQ(single_result.size(), 1U);
  1100. EXPECT_EQ(single_result[0], "application/json");
  1101. // Wildcard types
  1102. std::vector<std::string> wildcard_result;
  1103. EXPECT_TRUE(detail::parse_accept_header(
  1104. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  1105. EXPECT_EQ(wildcard_result.size(), 3U);
  1106. EXPECT_EQ(wildcard_result[0], "application/json");
  1107. EXPECT_EQ(wildcard_result[1], "text/*");
  1108. EXPECT_EQ(wildcard_result[2], "*/*");
  1109. }
  1110. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  1111. // Common browser Accept header
  1112. std::vector<std::string> browser_result;
  1113. EXPECT_TRUE(
  1114. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  1115. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  1116. browser_result));
  1117. EXPECT_EQ(browser_result.size(), 6U);
  1118. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  1119. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  1120. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  1121. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  1122. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  1123. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  1124. // API client header
  1125. std::vector<std::string> api_result;
  1126. EXPECT_TRUE(detail::parse_accept_header(
  1127. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  1128. api_result));
  1129. EXPECT_EQ(api_result.size(), 3U);
  1130. EXPECT_EQ(api_result[0], "application/json");
  1131. EXPECT_EQ(api_result[1], "application/xml");
  1132. EXPECT_EQ(api_result[2], "text/plain");
  1133. }
  1134. TEST(ParseAcceptHeaderTest, SpecialCases) {
  1135. // Quality value with 3 decimal places
  1136. std::vector<std::string> decimal_result;
  1137. EXPECT_TRUE(detail::parse_accept_header(
  1138. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  1139. EXPECT_EQ(decimal_result.size(), 2U);
  1140. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  1141. EXPECT_EQ(decimal_result[1], "text/html");
  1142. // Zero quality (should still be included but with lowest priority)
  1143. std::vector<std::string> zero_q_result;
  1144. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  1145. zero_q_result));
  1146. EXPECT_EQ(zero_q_result.size(), 2U);
  1147. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1148. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1149. // No spaces around commas
  1150. std::vector<std::string> no_space_result;
  1151. EXPECT_TRUE(detail::parse_accept_header(
  1152. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1153. no_space_result));
  1154. EXPECT_EQ(no_space_result.size(), 3U);
  1155. EXPECT_EQ(no_space_result[0], "text/html");
  1156. EXPECT_EQ(no_space_result[1], "application/json");
  1157. EXPECT_EQ(no_space_result[2], "text/plain");
  1158. }
  1159. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1160. // Quality values always use '.' as the decimal separator, so parsing must
  1161. // not depend on the process locale. An embedding application may have
  1162. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1163. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1164. std::string saved = cur ? cur : "C";
  1165. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1166. "fr_FR.UTF-8"};
  1167. bool switched = false;
  1168. for (const auto loc : comma_locales) {
  1169. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1170. std::localeconv()->decimal_point[0] == ',') {
  1171. switched = true;
  1172. break;
  1173. }
  1174. }
  1175. if (!switched) {
  1176. std::setlocale(LC_NUMERIC, saved.c_str());
  1177. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1178. }
  1179. // The higher-weighted type appears later in the list, so a correct parse
  1180. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1181. // sensitive parse reads both weights as 0 and leaves the original order.
  1182. std::vector<std::string> result;
  1183. EXPECT_TRUE(detail::parse_accept_header(
  1184. "application/json;q=0.1,text/html;q=0.9", result));
  1185. ASSERT_EQ(result.size(), 2U);
  1186. EXPECT_EQ(result[0], "text/html");
  1187. EXPECT_EQ(result[1], "application/json");
  1188. std::setlocale(LC_NUMERIC, saved.c_str());
  1189. }
  1190. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1191. std::vector<std::string> result;
  1192. // Invalid quality value (> 1.0)
  1193. EXPECT_FALSE(
  1194. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1195. // Invalid quality value (< 0.0)
  1196. EXPECT_FALSE(
  1197. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1198. // Invalid quality value (not a number)
  1199. EXPECT_FALSE(detail::parse_accept_header(
  1200. "text/html;q=invalid,application/json", result));
  1201. // A valid numeric prefix does not make the entire quality value valid.
  1202. EXPECT_FALSE(detail::parse_accept_header(
  1203. "text/html;q=0.5junk,application/json", result));
  1204. // Empty quality value
  1205. EXPECT_FALSE(
  1206. detail::parse_accept_header("text/html;q=,application/json", result));
  1207. // Invalid media type format (no slash and not wildcard)
  1208. EXPECT_FALSE(
  1209. detail::parse_accept_header("invalidtype,application/json", result));
  1210. // Valid cases should still work
  1211. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1212. EXPECT_EQ(result.size(), 1U);
  1213. EXPECT_EQ(result[0], "*/*");
  1214. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1215. EXPECT_EQ(result.size(), 1U);
  1216. EXPECT_EQ(result[0], "*");
  1217. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1218. EXPECT_EQ(result.size(), 1U);
  1219. EXPECT_EQ(result[0], "text/*");
  1220. }
  1221. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1222. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1223. // and must not be answered with 400 Bad Request.
  1224. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1225. struct {
  1226. const char *value;
  1227. std::vector<std::string> expected;
  1228. } cases[] = {
  1229. {",application/json", {"application/json"}},
  1230. {"text/html,", {"text/html"}},
  1231. {"text/html,,*/*", {"text/html", "*/*"}},
  1232. // An empty element may be spelled with whitespace in it
  1233. {"text/html, , application/json", {"text/html", "application/json"}},
  1234. // Nothing but empty elements is an empty list, which means the same
  1235. // thing as no Accept header at all
  1236. {",,,", {}},
  1237. // Quality values still apply across ignored empty elements
  1238. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1239. };
  1240. for (const auto &c : cases) {
  1241. std::vector<std::string> result;
  1242. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1243. << "value: " << c.value;
  1244. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1245. }
  1246. // An invalid entry is still rejected when empty elements surround it
  1247. std::vector<std::string> result;
  1248. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1249. }
  1250. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1251. // or ';' inside one does not end the list element or the parameter. Section
  1252. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1253. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1254. struct {
  1255. const char *value;
  1256. std::vector<std::string> expected;
  1257. } cases[] = {
  1258. {"text/html;profile=\"a,b\",application/json",
  1259. {"text/html", "application/json"}},
  1260. // A "q=" inside a quoted value is not the weight
  1261. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1262. {"text/html", "application/json"}},
  1263. // The weight after a quoted value still applies
  1264. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1265. {"application/json", "text/html"}},
  1266. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1267. {"application/json", "text/html"}},
  1268. {"text/html;profile=\"a\\\"b\",application/json",
  1269. {"text/html", "application/json"}},
  1270. // An escaped backslash does not escape the '"' after it
  1271. {"text/html;profile=\"a\\\\\",application/json",
  1272. {"text/html", "application/json"}},
  1273. };
  1274. for (const auto &c : cases) {
  1275. std::vector<std::string> result;
  1276. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1277. << "value: " << c.value;
  1278. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1279. }
  1280. }
  1281. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1282. Server svr;
  1283. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1284. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1285. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1286. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1287. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1288. res.set_content("ok", "text/plain");
  1289. });
  1290. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1291. EXPECT_TRUE(false);
  1292. res.set_content("bad request", "text/plain");
  1293. });
  1294. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. listen_thread.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. Client cli("localhost", PORT);
  1302. {
  1303. auto res = cli.Get(
  1304. "/accept_ok",
  1305. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1306. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1307. EXPECT_EQ(StatusCode::OK_200, res->status);
  1308. }
  1309. {
  1310. auto res = cli.Get("/accept_bad_request",
  1311. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1313. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1314. }
  1315. }
  1316. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1317. Server svr;
  1318. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1319. res.set_content("ok", "text/plain");
  1320. });
  1321. std::atomic<int> start_count{0};
  1322. std::atomic<bool> running_when_called{false};
  1323. svr.set_start_handler([&]() {
  1324. running_when_called = svr.is_running();
  1325. start_count++;
  1326. });
  1327. auto port = svr.bind_to_any_port(HOST);
  1328. std::thread t([&]() { svr.listen_after_bind(); });
  1329. auto se = detail::scope_exit([&] {
  1330. svr.stop();
  1331. t.join();
  1332. ASSERT_FALSE(svr.is_running());
  1333. });
  1334. svr.wait_until_ready();
  1335. // A successful request proves the accept loop is running, which the start
  1336. // handler precedes; so by now the handler must have run exactly once.
  1337. Client cli(HOST, port);
  1338. cli.set_connection_timeout(std::chrono::seconds(5));
  1339. auto res = cli.Get("/");
  1340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1341. EXPECT_EQ(StatusCode::OK_200, res->status);
  1342. EXPECT_EQ(1, start_count.load());
  1343. EXPECT_TRUE(running_when_called.load());
  1344. }
  1345. TEST(DivideTest, DivideStringTests) {
  1346. auto divide = [](const std::string &str, char d) {
  1347. std::string lhs;
  1348. std::string rhs;
  1349. detail::divide(str, d,
  1350. [&](const char *lhs_data, std::size_t lhs_size,
  1351. const char *rhs_data, std::size_t rhs_size) {
  1352. lhs.assign(lhs_data, lhs_size);
  1353. rhs.assign(rhs_data, rhs_size);
  1354. });
  1355. return std::make_pair(std::move(lhs), std::move(rhs));
  1356. };
  1357. {
  1358. const auto res = divide("", '=');
  1359. EXPECT_EQ(res.first, "");
  1360. EXPECT_EQ(res.second, "");
  1361. }
  1362. {
  1363. const auto res = divide("=", '=');
  1364. EXPECT_EQ(res.first, "");
  1365. EXPECT_EQ(res.second, "");
  1366. }
  1367. {
  1368. const auto res = divide(" ", '=');
  1369. EXPECT_EQ(res.first, " ");
  1370. EXPECT_EQ(res.second, "");
  1371. }
  1372. {
  1373. const auto res = divide("a", '=');
  1374. EXPECT_EQ(res.first, "a");
  1375. EXPECT_EQ(res.second, "");
  1376. }
  1377. {
  1378. const auto res = divide("a=", '=');
  1379. EXPECT_EQ(res.first, "a");
  1380. EXPECT_EQ(res.second, "");
  1381. }
  1382. {
  1383. const auto res = divide("=b", '=');
  1384. EXPECT_EQ(res.first, "");
  1385. EXPECT_EQ(res.second, "b");
  1386. }
  1387. {
  1388. const auto res = divide("a=b", '=');
  1389. EXPECT_EQ(res.first, "a");
  1390. EXPECT_EQ(res.second, "b");
  1391. }
  1392. {
  1393. const auto res = divide("a=b=", '=');
  1394. EXPECT_EQ(res.first, "a");
  1395. EXPECT_EQ(res.second, "b=");
  1396. }
  1397. {
  1398. const auto res = divide("a=b=c", '=');
  1399. EXPECT_EQ(res.first, "a");
  1400. EXPECT_EQ(res.second, "b=c");
  1401. }
  1402. }
  1403. TEST(SplitTest, ParseQueryString) {
  1404. string s = "key1=val1&key2=val2&key3=val3";
  1405. Params dic;
  1406. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1407. [&](const char *b, const char *e) {
  1408. string key, val;
  1409. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1410. if (key.empty()) {
  1411. key.assign(b2, e2);
  1412. } else {
  1413. val.assign(b2, e2);
  1414. }
  1415. });
  1416. dic.emplace(key, val);
  1417. });
  1418. EXPECT_EQ("val1", dic.find("key1")->second);
  1419. EXPECT_EQ("val2", dic.find("key2")->second);
  1420. EXPECT_EQ("val3", dic.find("key3")->second);
  1421. }
  1422. TEST(SplitTest, ParseInvalidQueryTests) {
  1423. {
  1424. string s = " ";
  1425. Params dict;
  1426. detail::parse_query_text(s, dict);
  1427. EXPECT_TRUE(dict.empty());
  1428. }
  1429. {
  1430. string s = " = =";
  1431. Params dict;
  1432. detail::parse_query_text(s, dict);
  1433. EXPECT_TRUE(dict.empty());
  1434. }
  1435. }
  1436. TEST(ParseQueryTest, ParseQueryString) {
  1437. {
  1438. std::string s = "key1=val1&key2=val2&key3=val3";
  1439. Params dic;
  1440. detail::parse_query_text(s, dic);
  1441. EXPECT_EQ("val1", dic.find("key1")->second);
  1442. EXPECT_EQ("val2", dic.find("key2")->second);
  1443. EXPECT_EQ("val3", dic.find("key3")->second);
  1444. }
  1445. {
  1446. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1447. Params dic;
  1448. detail::parse_query_text(s, dic);
  1449. EXPECT_EQ("", dic.find("key1")->second);
  1450. EXPECT_EQ("val1", dic.find("key2")->second);
  1451. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1452. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1453. }
  1454. }
  1455. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1456. Params dic;
  1457. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1458. dic.emplace("key1", "val1");
  1459. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1460. dic.emplace("key2", "val2");
  1461. dic.emplace("key3", "val3");
  1462. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1463. }
  1464. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1465. Params params;
  1466. params.emplace("a", "1");
  1467. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1468. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1469. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1470. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1471. // Long enough to overflow the stack when matched with std::regex.
  1472. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1473. EXPECT_EQ("/p?" + long_query + "&a=1",
  1474. append_query_params("/p?" + long_query, params));
  1475. }
  1476. // Joins every entry of a Headers or Params into "key=value " so a whole
  1477. // traversal can be compared in one assertion. Both are instantiations of the
  1478. // same insertion-ordered container, so one helper serves both.
  1479. template <typename Map> static std::string entries_to_string(const Map &m) {
  1480. std::string s;
  1481. for (const auto &entry : m) {
  1482. s += entry.first + "=" + entry.second + " ";
  1483. }
  1484. return s;
  1485. }
  1486. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1487. // Params used to be a std::multimap, which sorted by name and handed the
  1488. // caller's query back alphabetised. A client signing its query string could
  1489. // not reproduce the order it asked for.
  1490. Params dic;
  1491. dic.emplace("zulu", "1");
  1492. dic.emplace("alpha", "2");
  1493. dic.emplace("mike", "3");
  1494. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1495. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1496. }
  1497. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1498. Params dic;
  1499. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1500. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1501. }
  1502. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1503. Request req;
  1504. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1505. req.params);
  1506. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1507. EXPECT_EQ("first", req.get_param_value("tag"));
  1508. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1509. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1510. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1511. EXPECT_EQ("", req.get_param_value("tag", 3));
  1512. }
  1513. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1514. // Params shares its container with Headers, which matches field names
  1515. // case-insensitively. Parameter names must not pick that up.
  1516. Params dic;
  1517. dic.emplace("Key", "upper");
  1518. dic.emplace("key", "lower");
  1519. EXPECT_EQ(2U, dic.size());
  1520. EXPECT_EQ(1U, dic.count("Key"));
  1521. EXPECT_EQ(1U, dic.count("key"));
  1522. EXPECT_EQ("upper", dic.find("Key")->second);
  1523. EXPECT_EQ("lower", dic.find("key")->second);
  1524. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1525. }
  1526. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1527. Server svr;
  1528. std::string order;
  1529. svr.Get("/order", [&](const Request &req, Response &res) {
  1530. order = entries_to_string(req.params);
  1531. res.set_content("ok", "text/plain");
  1532. });
  1533. auto port = svr.bind_to_any_port(HOST);
  1534. thread t = thread([&] { svr.listen_after_bind(); });
  1535. auto se = detail::scope_exit([&] {
  1536. svr.stop();
  1537. t.join();
  1538. ASSERT_FALSE(svr.is_running());
  1539. });
  1540. svr.wait_until_ready();
  1541. Client cli(HOST, port);
  1542. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1543. ASSERT_TRUE(res);
  1544. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1545. }
  1546. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1547. Server svr;
  1548. std::string field_order, file_order;
  1549. svr.Post("/order", [&](const Request &req, Response &res) {
  1550. for (const auto &field : req.form.fields) {
  1551. field_order += field.first + "=" + field.second.content + " ";
  1552. }
  1553. for (const auto &file : req.form.files) {
  1554. file_order += file.first + "=" + file.second.filename + " ";
  1555. }
  1556. res.set_content("ok", "text/plain");
  1557. });
  1558. auto port = svr.bind_to_any_port(HOST);
  1559. thread t = thread([&] { svr.listen_after_bind(); });
  1560. auto se = detail::scope_exit([&] {
  1561. svr.stop();
  1562. t.join();
  1563. ASSERT_FALSE(svr.is_running());
  1564. });
  1565. svr.wait_until_ready();
  1566. UploadFormDataItems items = {
  1567. {"zulu", "1", "", ""},
  1568. {"alpha", "2", "", ""},
  1569. {"mike", "3", "", ""},
  1570. {"zebra", "z", "z.txt", "text/plain"},
  1571. {"apple", "a", "a.txt", "text/plain"},
  1572. };
  1573. Client cli(HOST, port);
  1574. auto res = cli.Post("/order", items);
  1575. ASSERT_TRUE(res);
  1576. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1577. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1578. }
  1579. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1580. Server svr;
  1581. std::vector<std::string> values;
  1582. std::string first, second, out_of_range, order;
  1583. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1584. values = req.form.get_fields("tag");
  1585. first = req.form.get_field("tag", 0);
  1586. second = req.form.get_field("tag", 1);
  1587. out_of_range = req.form.get_field("tag", 2);
  1588. for (const auto &field : req.form.fields) {
  1589. order += field.first + "=" + field.second.content + " ";
  1590. }
  1591. res.set_content("ok", "text/plain");
  1592. });
  1593. auto port = svr.bind_to_any_port(HOST);
  1594. thread t = thread([&] { svr.listen_after_bind(); });
  1595. auto se = detail::scope_exit([&] {
  1596. svr.stop();
  1597. t.join();
  1598. ASSERT_FALSE(svr.is_running());
  1599. });
  1600. svr.wait_until_ready();
  1601. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1602. // not adjacent in the container.
  1603. UploadFormDataItems items = {
  1604. {"tag", "first", "", ""},
  1605. {"other", "x", "", ""},
  1606. {"tag", "second", "", ""},
  1607. };
  1608. Client cli(HOST, port);
  1609. auto res = cli.Post("/repeated", items);
  1610. ASSERT_TRUE(res);
  1611. ASSERT_EQ(2U, values.size());
  1612. EXPECT_EQ("first", values[0]);
  1613. EXPECT_EQ("second", values[1]);
  1614. EXPECT_EQ("first", first);
  1615. EXPECT_EQ("second", second);
  1616. // std::multimap already kept entries sharing a name in insertion order, so
  1617. // everything above passes without this change too. The whole traversal is
  1618. // what tells the two apart: sorting by name would hoist "other" to the front
  1619. // and the two "tag" parts would end up adjacent.
  1620. EXPECT_EQ("tag=first other=x tag=second ", order);
  1621. // Advancing past the last entry of a name used to run off the container;
  1622. // the container's saturating increment makes it return the default instead.
  1623. EXPECT_EQ("", out_of_range);
  1624. }
  1625. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1626. Server svr;
  1627. std::string file_names;
  1628. svr.Post("/upload", [&](const Request &req, Response &res) {
  1629. for (const auto &file : req.form.files) {
  1630. file_names += file.first + "|" + file.second.filename + " ";
  1631. }
  1632. res.set_content("ok", "text/plain");
  1633. });
  1634. auto port = svr.bind_to_any_port(HOST);
  1635. thread t = thread([&] { svr.listen_after_bind(); });
  1636. auto se = detail::scope_exit([&] {
  1637. svr.stop();
  1638. t.join();
  1639. ASSERT_FALSE(svr.is_running());
  1640. });
  1641. svr.wait_until_ready();
  1642. // A trailing backslash would otherwise escape the closing quote.
  1643. UploadFormDataItems items = {
  1644. {"dir\\", "x", "a.txt", "text/plain"},
  1645. {"b", "y", "a\\\\b.txt", "text/plain"},
  1646. };
  1647. Client cli(HOST, port);
  1648. auto res = cli.Post("/upload", items);
  1649. ASSERT_TRUE(res);
  1650. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1651. }
  1652. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1653. // Server::read_content() keeps a FormFields::iterator alive across the
  1654. // content callbacks that fill the part it points at. The container is
  1655. // vector-backed, so a later emplace can reallocate and invalidate an older
  1656. // iterator; 64 parts grow the vector through seven reallocations, which
  1657. // checks that every part's content still lands in its own entry.
  1658. const size_t part_count = 64;
  1659. // One formula for both the parts sent and the values expected back, so the
  1660. // two cannot drift apart.
  1661. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1662. auto content_of = [](size_t i) {
  1663. return std::string(64, static_cast<char>('a' + (i % 26)));
  1664. };
  1665. Server svr;
  1666. std::vector<std::pair<std::string, std::string>> received;
  1667. svr.Post("/many", [&](const Request &req, Response &res) {
  1668. for (const auto &field : req.form.fields) {
  1669. received.emplace_back(field.first, field.second.content);
  1670. }
  1671. res.set_content("ok", "text/plain");
  1672. });
  1673. auto port = svr.bind_to_any_port(HOST);
  1674. thread t = thread([&] { svr.listen_after_bind(); });
  1675. auto se = detail::scope_exit([&] {
  1676. svr.stop();
  1677. t.join();
  1678. ASSERT_FALSE(svr.is_running());
  1679. });
  1680. svr.wait_until_ready();
  1681. UploadFormDataItems items;
  1682. for (size_t i = 0; i < part_count; i++) {
  1683. items.push_back({name_of(i), content_of(i), "", ""});
  1684. }
  1685. Client cli(HOST, port);
  1686. auto res = cli.Post("/many", items);
  1687. ASSERT_TRUE(res);
  1688. ASSERT_EQ(part_count, received.size());
  1689. for (size_t i = 0; i < part_count; i++) {
  1690. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1691. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1692. }
  1693. }
  1694. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1695. string content_type = "multipart/form-data; boundary=something";
  1696. string boundary;
  1697. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1698. EXPECT_TRUE(ret);
  1699. EXPECT_EQ(boundary, "something");
  1700. }
  1701. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1702. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1703. string boundary;
  1704. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1705. EXPECT_TRUE(ret);
  1706. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1707. }
  1708. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1709. string content_type =
  1710. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1711. string boundary;
  1712. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1713. EXPECT_TRUE(ret);
  1714. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1715. }
  1716. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1717. string content_type =
  1718. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1719. string boundary;
  1720. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1721. EXPECT_TRUE(ret);
  1722. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1723. }
  1724. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1725. const string boundary(70, 'a');
  1726. string content_type = "multipart/form-data; boundary=" + boundary;
  1727. string parsed;
  1728. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1729. EXPECT_TRUE(ret);
  1730. EXPECT_EQ(parsed, boundary);
  1731. }
  1732. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1733. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1734. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1735. string parsed;
  1736. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1737. EXPECT_FALSE(ret);
  1738. }
  1739. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1740. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1741. // is 72 characters on the wire and still valid.
  1742. const string boundary(70, 'a');
  1743. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1744. string parsed;
  1745. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1746. EXPECT_EQ(parsed, boundary);
  1747. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1748. parsed.clear();
  1749. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1750. }
  1751. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1752. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1753. // The parameter parser must not treat that '=' as the key/value separator.
  1754. string content_type =
  1755. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1756. "charset=UTF-8";
  1757. string parsed;
  1758. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1759. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1760. }
  1761. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1762. // A ';' inside the quoted-string is part of the value, not a parameter
  1763. // separator, so it must not truncate the boundary.
  1764. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1765. string parsed;
  1766. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1767. EXPECT_EQ(parsed, "a;b");
  1768. }
  1769. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1770. string parsed;
  1771. EXPECT_TRUE(detail::parse_multipart_boundary(
  1772. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1773. EXPECT_EQ("a\\b", parsed);
  1774. EXPECT_TRUE(detail::parse_multipart_boundary(
  1775. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1776. EXPECT_EQ("a\"b", parsed);
  1777. }
  1778. TEST(ParseDispositionParamsTest, QuotedValues) {
  1779. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1780. // ';' and '=' are ordinary characters inside one.
  1781. struct {
  1782. const char *value;
  1783. std::vector<std::pair<const char *, const char *>> expected;
  1784. } cases[] = {
  1785. {"name=\"file1\"; filename=\"a.txt\"",
  1786. {{"name", "file1"}, {"filename", "a.txt"}}},
  1787. // MIME parameter names are case-insensitive, but their values are not.
  1788. {"NaMe=\"Upload\"; FiLeNaMe=\"Report.TXT\"",
  1789. {{"name", "Upload"}, {"filename", "Report.TXT"}}},
  1790. // Whitespace around '=' and ';' is still trimmed
  1791. {"name=\"file2\" ;filename = \"a.html\"",
  1792. {{"name", "file2"}, {"filename", "a.html"}}},
  1793. // '=' inside the value used to leave only the text after the last one
  1794. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1795. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1796. {"name=\"x=y\"", {{"name", "x=y"}}},
  1797. // ';' inside the value used to truncate the pair and leave a bogus one
  1798. {"name=\"file3\"; filename=\"a;b.txt\"",
  1799. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1800. // An unquoted value keeps working, and so does filename*
  1801. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1802. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1803. // A parameter with no key is dropped rather than turned into one whose
  1804. // key is the value
  1805. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1806. // An escaped quote does not end the value
  1807. {"name=\"a\\\"; filename=evil.php\"",
  1808. {{"name", "a\"; filename=evil.php"}}},
  1809. // Other backslashes, as in a Windows path, are kept
  1810. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1811. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1812. };
  1813. for (const auto &c : cases) {
  1814. Params params;
  1815. detail::parse_disposition_params(c.value, params);
  1816. for (const auto &kv : c.expected) {
  1817. auto it = params.find(kv.first);
  1818. ASSERT_NE(it, params.end())
  1819. << "value: " << c.value << ", key: " << kv.first;
  1820. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1821. }
  1822. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1823. }
  1824. }
  1825. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1826. Server svr;
  1827. std::string filename;
  1828. std::string content;
  1829. svr.Post("/upload", [&](const Request &req, Response &) {
  1830. const auto &file = req.form.get_file("file");
  1831. filename = file.filename;
  1832. content = file.content;
  1833. });
  1834. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1835. auto se = detail::scope_exit([&] {
  1836. svr.stop();
  1837. thread.join();
  1838. ASSERT_FALSE(svr.is_running());
  1839. });
  1840. svr.wait_until_ready();
  1841. std::string body = "--B\r\n"
  1842. "Content-Disposition: form-data; name=\"file\"; "
  1843. "filename=\"a.txt\"\r\n"
  1844. "Content-Type: text/plain\r\n"
  1845. "\r\n"
  1846. "hello\r\n"
  1847. "--B--\r\n";
  1848. Client cli(HOST, PORT);
  1849. auto res = cli.Post(
  1850. "/upload",
  1851. [&](size_t offset, DataSink &sink) {
  1852. if (offset < body.size()) {
  1853. sink.write(&body[offset], 1);
  1854. } else {
  1855. sink.done();
  1856. }
  1857. return true;
  1858. },
  1859. "multipart/form-data; boundary=B");
  1860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1861. EXPECT_EQ(StatusCode::OK_200, res->status);
  1862. EXPECT_EQ("a.txt", filename);
  1863. EXPECT_EQ("hello", content);
  1864. }
  1865. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1866. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1867. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1868. Server svr;
  1869. std::string field_value, file_name, file_filename;
  1870. bool has_field = false, has_file = false;
  1871. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1872. has_field = req.form.has_field("x=y");
  1873. field_value = req.form.get_field("x=y");
  1874. has_file = req.form.has_file("file1");
  1875. const auto &file = req.form.get_file("file1");
  1876. file_name = file.name;
  1877. file_filename = file.filename;
  1878. res.set_content("ok", "text/plain");
  1879. });
  1880. auto port = svr.bind_to_any_port(HOST);
  1881. thread t = thread([&] { svr.listen_after_bind(); });
  1882. auto se = detail::scope_exit([&] {
  1883. svr.stop();
  1884. t.join();
  1885. ASSERT_FALSE(svr.is_running());
  1886. });
  1887. svr.wait_until_ready();
  1888. UploadFormDataItems items = {
  1889. {"x=y", "field-value", "", ""},
  1890. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1891. };
  1892. Client cli(HOST, port);
  1893. auto res = cli.Post("/quoted", items);
  1894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1895. ASSERT_EQ(StatusCode::OK_200, res->status);
  1896. EXPECT_TRUE(has_field);
  1897. EXPECT_EQ("field-value", field_value);
  1898. EXPECT_TRUE(has_file);
  1899. EXPECT_EQ("file1", file_name);
  1900. EXPECT_EQ("a;b=report.pdf", file_filename);
  1901. }
  1902. TEST(GetHeaderValueTest, DefaultValue) {
  1903. Headers headers = {{"Dummy", "Dummy"}};
  1904. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1905. EXPECT_STREQ("text/plain", val);
  1906. }
  1907. TEST(GetHeaderValueTest, DefaultValueInt) {
  1908. Headers headers = {{"Dummy", "Dummy"}};
  1909. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1910. EXPECT_EQ(100ull, val);
  1911. }
  1912. TEST(GetHeaderValueTest, RegularValue) {
  1913. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1914. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1915. EXPECT_STREQ("text/html", val);
  1916. }
  1917. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1918. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1919. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1920. EXPECT_STREQ("text/html", val);
  1921. }
  1922. TEST(GetHeaderValueTest, SetContent) {
  1923. Response res;
  1924. res.set_content("html", "text/html");
  1925. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1926. res.set_content("text", "text/plain");
  1927. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1928. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1929. }
  1930. TEST(GetHeaderValueTest, RegularValueInt) {
  1931. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1932. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1933. EXPECT_EQ(100ull, val);
  1934. }
  1935. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1936. Headers headers = {{"Content-Length", "x"}};
  1937. auto is_invalid_value = false;
  1938. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1939. is_invalid_value);
  1940. EXPECT_EQ(0ull, val);
  1941. EXPECT_TRUE(is_invalid_value);
  1942. }
  1943. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1944. // An all-digit value that overflows size_t must be reported as invalid, not
  1945. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1946. // a large length to a small one on 32-bit builds, leaving the framing length
  1947. // wrong while is_invalid_value stayed false.
  1948. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1949. auto is_invalid_value = false;
  1950. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1951. is_invalid_value);
  1952. EXPECT_TRUE(is_invalid_value);
  1953. // A well-formed length is unaffected.
  1954. Headers ok = {{"Content-Length", "1234"}};
  1955. is_invalid_value = false;
  1956. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1957. is_invalid_value);
  1958. EXPECT_EQ(1234ull, val);
  1959. EXPECT_FALSE(is_invalid_value);
  1960. }
  1961. TEST(GetHeaderValueTest, Range) {
  1962. {
  1963. Headers headers = {make_range_header({{1, -1}})};
  1964. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1965. EXPECT_STREQ("bytes=1-", val);
  1966. }
  1967. {
  1968. Headers headers = {make_range_header({{-1, 1}})};
  1969. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1970. EXPECT_STREQ("bytes=-1", val);
  1971. }
  1972. {
  1973. Headers headers = {make_range_header({{1, 10}})};
  1974. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1975. EXPECT_STREQ("bytes=1-10", val);
  1976. }
  1977. {
  1978. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1979. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1980. EXPECT_STREQ("bytes=1-10, 100-", val);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1984. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1985. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1986. }
  1987. {
  1988. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1989. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1990. EXPECT_STREQ("bytes=0-0, -1", val);
  1991. }
  1992. }
  1993. TEST(BearerTokenAuthTest, SchemeValidation) {
  1994. // A value shorter than "Bearer " must not throw from the fixed-length
  1995. // substr, and a non-Bearer scheme must not be reported as a token.
  1996. struct {
  1997. const char *value;
  1998. const char *expected;
  1999. } cases[] = {
  2000. {"x", ""},
  2001. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  2002. {"Bearer abc123", "abc123"},
  2003. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  2004. };
  2005. for (const auto &c : cases) {
  2006. Request req;
  2007. req.set_header("Authorization", c.value);
  2008. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  2009. }
  2010. }
  2011. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  2012. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  2013. // to depend on the standard library (libstdc++ handed back duplicates in
  2014. // reverse insertion order, libc++ in insertion order).
  2015. Request req;
  2016. req.set_header("Accept-Encoding", "gzip");
  2017. req.set_header("Accept-Encoding", "deflate");
  2018. req.set_header("Accept-Encoding", "br");
  2019. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  2020. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  2021. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  2022. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  2023. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  2024. }
  2025. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  2026. Request req;
  2027. req.set_header("X-Test", "only");
  2028. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  2029. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  2030. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  2031. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  2032. }
  2033. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  2034. Request req;
  2035. req.set_header("X-First", "1");
  2036. req.set_header("X-Test", "2");
  2037. req.params.emplace("first", "1");
  2038. req.params.emplace("test", "2");
  2039. req.form.fields.emplace("first", FormField{"first", "1", {}});
  2040. req.form.fields.emplace("test", FormField{"test", "2", {}});
  2041. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  2042. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  2043. // The second one is negative when read as a signed value
  2044. const auto max_id = (std::numeric_limits<size_t>::max)();
  2045. for (auto id : {max_id / 2, max_id}) {
  2046. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  2047. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  2048. EXPECT_EQ("", req.get_param_value("test", id));
  2049. EXPECT_EQ("", req.form.get_field("test", id));
  2050. EXPECT_EQ("", req.form.get_file("test", id).content);
  2051. }
  2052. }
  2053. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  2054. Headers headers;
  2055. headers.emplace("Host", "example.com");
  2056. headers.emplace("Accept-Encoding", "gzip");
  2057. headers.emplace("User-Agent", "test");
  2058. headers.emplace("Accept-Encoding", "deflate");
  2059. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  2060. "Accept-Encoding=deflate ",
  2061. entries_to_string(headers));
  2062. }
  2063. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  2064. Headers headers = {{"Content-Type", "text/html"},
  2065. {"CONTENT-TYPE", "text/xml"}};
  2066. EXPECT_EQ(2U, headers.count("content-type"));
  2067. auto it = headers.find("content-type");
  2068. ASSERT_TRUE(it != headers.end());
  2069. EXPECT_EQ("text/html", it->second);
  2070. }
  2071. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  2072. // The fields sharing a name are not adjacent, so an equal_range() erase must
  2073. // drop only those fields and leave everything positioned between them.
  2074. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  2075. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  2076. auto rng = headers.equal_range("a");
  2077. headers.erase(rng.first, rng.second);
  2078. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  2079. }
  2080. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  2081. Headers headers = {
  2082. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  2083. EXPECT_EQ(3U, headers.erase("A"));
  2084. EXPECT_EQ(0U, headers.count("A"));
  2085. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  2086. }
  2087. TEST(HeadersOrderTest, ErasingAnAliasedNameKeepsTheRemainingOrder) {
  2088. Headers headers = {{"A", "1"}, {"B", "2"}, {"a", "3"}, {"B", "4"}};
  2089. EXPECT_EQ(2U, headers.erase(headers.begin()->first));
  2090. EXPECT_EQ("B=2 B=4 ", entries_to_string(headers));
  2091. }
  2092. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  2093. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  2094. headers.emplace_front("Host", "example.com");
  2095. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  2096. entries_to_string(headers));
  2097. }
  2098. TEST(ParseHeaderValueTest, Range) {
  2099. {
  2100. Ranges ranges;
  2101. auto ret = detail::parse_range_header("bytes=1-", ranges);
  2102. EXPECT_TRUE(ret);
  2103. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  2104. }
  2105. {
  2106. Ranges ranges;
  2107. auto ret = detail::parse_range_header("bytes=-1", ranges);
  2108. EXPECT_TRUE(ret);
  2109. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  2110. }
  2111. {
  2112. Ranges ranges;
  2113. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  2114. EXPECT_TRUE(ret);
  2115. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  2116. }
  2117. {
  2118. Ranges ranges;
  2119. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  2120. EXPECT_FALSE(ret);
  2121. }
  2122. {
  2123. Ranges ranges;
  2124. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  2125. EXPECT_TRUE(ret);
  2126. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  2127. }
  2128. {
  2129. Ranges ranges;
  2130. auto ret =
  2131. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  2132. EXPECT_TRUE(ret);
  2133. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  2134. }
  2135. {
  2136. Ranges ranges;
  2137. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  2138. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  2139. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  2140. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  2141. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  2142. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  2143. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  2144. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  2145. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  2146. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  2147. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  2148. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  2149. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  2150. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  2151. EXPECT_FALSE(
  2152. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  2153. EXPECT_TRUE(ranges.empty());
  2154. }
  2155. {
  2156. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2157. // remainder of the representation, so it stays accepted.
  2158. Ranges ranges;
  2159. auto ret =
  2160. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2161. EXPECT_TRUE(ret);
  2162. ASSERT_EQ(1u, ranges.size());
  2163. EXPECT_EQ(0, ranges[0].first);
  2164. EXPECT_EQ(-1, ranges[0].second);
  2165. }
  2166. // RFC 9110 14.1: range unit names are case-insensitive.
  2167. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2168. Ranges ranges;
  2169. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2170. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2171. }
  2172. }
  2173. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2174. Request req;
  2175. req.set_header("Accept-Encoding", "gzip");
  2176. Response res;
  2177. res.set_header("Content-Type", "text/plain");
  2178. auto ret = detail::encoding_type(req, res);
  2179. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2180. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2181. #else
  2182. EXPECT_TRUE(ret == detail::EncodingType::None);
  2183. #endif
  2184. }
  2185. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2186. Request req;
  2187. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2188. Response res;
  2189. res.set_header("Content-Type", "text/plain");
  2190. auto ret = detail::encoding_type(req, res);
  2191. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2192. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2193. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2194. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2195. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2196. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2197. #else
  2198. EXPECT_TRUE(ret == detail::EncodingType::None);
  2199. #endif
  2200. }
  2201. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2202. Request req;
  2203. req.set_header("Accept-Encoding",
  2204. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2205. Response res;
  2206. res.set_header("Content-Type", "text/plain");
  2207. auto ret = detail::encoding_type(req, res);
  2208. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2209. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2210. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2211. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2212. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2213. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2214. #else
  2215. EXPECT_TRUE(ret == detail::EncodingType::None);
  2216. #endif
  2217. }
  2218. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2219. // All supported encodings rejected with q=0 should return None
  2220. Request req;
  2221. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2222. Response res;
  2223. res.set_header("Content-Type", "text/plain");
  2224. auto ret = detail::encoding_type(req, res);
  2225. EXPECT_TRUE(ret == detail::EncodingType::None);
  2226. }
  2227. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2228. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2229. Request req;
  2230. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2231. Response res;
  2232. res.set_header("Content-Type", "text/plain");
  2233. auto ret = detail::encoding_type(req, res);
  2234. EXPECT_TRUE(ret == detail::EncodingType::None);
  2235. }
  2236. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2237. Request req;
  2238. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2239. Response res;
  2240. res.set_header("Content-Type", "text/plain");
  2241. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2242. }
  2243. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2244. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2245. Request req;
  2246. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2247. Response res;
  2248. res.set_header("Content-Type", "text/plain");
  2249. auto ret = detail::encoding_type(req, res);
  2250. EXPECT_TRUE(ret == detail::EncodingType::None);
  2251. }
  2252. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2253. // RFC 7231: Accept-Encoding values are case-insensitive
  2254. Request req;
  2255. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2256. Response res;
  2257. res.set_header("Content-Type", "text/plain");
  2258. auto ret = detail::encoding_type(req, res);
  2259. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2260. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2261. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2262. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2263. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2264. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2265. #else
  2266. EXPECT_TRUE(ret == detail::EncodingType::None);
  2267. #endif
  2268. }
  2269. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2270. // q value should determine priority, not hardcoded order
  2271. Request req;
  2272. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2273. Response res;
  2274. res.set_header("Content-Type", "text/plain");
  2275. auto ret = detail::encoding_type(req, res);
  2276. // gzip has highest q=1.0, so it should be selected even though
  2277. // br and zstd are also supported
  2278. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2279. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2280. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2281. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2282. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2283. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2284. #else
  2285. EXPECT_TRUE(ret == detail::EncodingType::None);
  2286. #endif
  2287. }
  2288. TEST(BufferStreamTest, read) {
  2289. detail::BufferStream strm1;
  2290. Stream &strm = strm1;
  2291. EXPECT_EQ(5, strm.write("hello"));
  2292. char buf[512];
  2293. EXPECT_EQ(2, strm.read(buf, 2));
  2294. EXPECT_EQ('h', buf[0]);
  2295. EXPECT_EQ('e', buf[1]);
  2296. EXPECT_EQ(2, strm.read(buf, 2));
  2297. EXPECT_EQ('l', buf[0]);
  2298. EXPECT_EQ('l', buf[1]);
  2299. EXPECT_EQ(1, strm.read(buf, 1));
  2300. EXPECT_EQ('o', buf[0]);
  2301. EXPECT_EQ(0, strm.read(buf, 1));
  2302. }
  2303. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2304. auto host = "www.httpwatch.com";
  2305. auto ip = hosted_at(host);
  2306. EXPECT_EQ("23.96.13.243", ip);
  2307. std::vector<std::string> addrs;
  2308. hosted_at(host, addrs);
  2309. EXPECT_EQ(1u, addrs.size());
  2310. }
  2311. #if 0 // It depends on each test environment...
  2312. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2313. auto host = "www.youtube.com";
  2314. std::vector<std::string> addrs;
  2315. hosted_at(host, addrs);
  2316. EXPECT_EQ(20u, addrs.size());
  2317. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2318. EXPECT_TRUE(it != addrs.end());
  2319. }
  2320. #endif
  2321. class ChunkedEncodingTest : public ::testing::Test {
  2322. protected:
  2323. ChunkedEncodingTest()
  2324. : cli_(HOST, PORT)
  2325. #ifdef CPPHTTPLIB_SSL_ENABLED
  2326. ,
  2327. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2328. #endif
  2329. {
  2330. cli_.set_connection_timeout(2);
  2331. #ifdef CPPHTTPLIB_SSL_ENABLED
  2332. cli_.enable_server_certificate_verification(false);
  2333. #endif
  2334. }
  2335. virtual void SetUp() {
  2336. read_file("./image.jpg", image_data_);
  2337. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2338. res.set_content("Hello World!", "text/plain");
  2339. });
  2340. svr_.Get(
  2341. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2342. res.set_chunked_content_provider(
  2343. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2344. size_t remaining = image_data_.size() - offset;
  2345. if (remaining == 0) {
  2346. sink.done();
  2347. } else {
  2348. constexpr size_t CHUNK_SIZE = 1024;
  2349. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2350. sink.write(&image_data_[offset], send_size);
  2351. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2352. }
  2353. return true;
  2354. });
  2355. });
  2356. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2357. svr_.wait_until_ready();
  2358. }
  2359. virtual void TearDown() {
  2360. svr_.stop();
  2361. if (!request_threads_.empty()) {
  2362. std::this_thread::sleep_for(std::chrono::seconds(1));
  2363. for (auto &t : request_threads_) {
  2364. t.join();
  2365. }
  2366. }
  2367. t_.join();
  2368. }
  2369. #ifdef CPPHTTPLIB_SSL_ENABLED
  2370. SSLClient cli_;
  2371. SSLServer svr_;
  2372. #else
  2373. Client cli_;
  2374. Server svr_;
  2375. #endif
  2376. thread t_;
  2377. std::vector<thread> request_threads_;
  2378. std::string image_data_;
  2379. };
  2380. TEST_F(ChunkedEncodingTest, NormalGet) {
  2381. auto res = cli_.Get("/chunked");
  2382. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2383. std::string out;
  2384. read_file("./image.jpg", out);
  2385. EXPECT_EQ(StatusCode::OK_200, res->status);
  2386. EXPECT_EQ(out, res->body);
  2387. }
  2388. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2389. std::string body;
  2390. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2391. body.append(data, data_length);
  2392. return true;
  2393. });
  2394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2395. std::string out;
  2396. read_file("./image.jpg", out);
  2397. EXPECT_EQ(StatusCode::OK_200, res->status);
  2398. EXPECT_EQ(out, body);
  2399. }
  2400. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2401. std::string body;
  2402. auto res = cli_.Get(
  2403. "/chunked",
  2404. [&](const Response &response) {
  2405. EXPECT_EQ(StatusCode::OK_200, response.status);
  2406. return true;
  2407. },
  2408. [&](const char *data, size_t data_length) {
  2409. body.append(data, data_length);
  2410. return true;
  2411. });
  2412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2413. std::string out;
  2414. read_file("./image.jpg", out);
  2415. EXPECT_EQ(StatusCode::OK_200, res->status);
  2416. EXPECT_EQ(out, body);
  2417. }
  2418. TEST(RangeTest, FromHTTPBin_Online) {
  2419. auto host = "httpbingo.org";
  2420. auto path = std::string{"/range/32"};
  2421. #ifdef CPPHTTPLIB_SSL_ENABLED
  2422. auto port = 443;
  2423. SSLClient cli(host, port);
  2424. #else
  2425. auto port = 80;
  2426. Client cli(host, port);
  2427. #endif
  2428. cli.set_connection_timeout(5);
  2429. {
  2430. auto res = retry_service_failures([&] { return cli.Get(path); });
  2431. SKIP_ON_SERVICE_FAILURE(res);
  2432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2433. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2434. EXPECT_EQ(StatusCode::OK_200, res->status);
  2435. }
  2436. {
  2437. Headers headers = {make_range_header({{1, -1}})};
  2438. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2439. SKIP_ON_SERVICE_FAILURE(res);
  2440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2441. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2442. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2443. }
  2444. {
  2445. Headers headers = {make_range_header({{1, 10}})};
  2446. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2447. SKIP_ON_SERVICE_FAILURE(res);
  2448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2449. EXPECT_EQ("bcdefghijk", res->body);
  2450. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2451. }
  2452. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2453. // entire resource, while the original httpbin returned 200. Both are
  2454. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2455. {
  2456. Headers headers = {make_range_header({{0, 31}})};
  2457. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2458. SKIP_ON_SERVICE_FAILURE(res);
  2459. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2460. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2461. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2462. res->status == StatusCode::PartialContent_206);
  2463. }
  2464. {
  2465. Headers headers = {make_range_header({{0, -1}})};
  2466. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2467. SKIP_ON_SERVICE_FAILURE(res);
  2468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2469. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2470. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2471. res->status == StatusCode::PartialContent_206);
  2472. }
  2473. // go-httpbin returns 206 with clamped range for over-range requests,
  2474. // while the original httpbin returned 416. Both behaviors are observed
  2475. // in real servers, so we only verify the request succeeds.
  2476. {
  2477. Headers headers = {make_range_header({{0, 32}})};
  2478. auto res = retry_service_failures([&] { return cli.Get(path, headers); });
  2479. SKIP_ON_SERVICE_FAILURE(res);
  2480. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2481. }
  2482. }
  2483. TEST(RangeTest, IgnoredForPost) {
  2484. Server svr;
  2485. svr.Post("/", [](const Request &, Response &res) {
  2486. res.set_content("abcdefg", "text/plain");
  2487. });
  2488. auto port = svr.bind_to_any_port(HOST);
  2489. ASSERT_GT(port, 0);
  2490. thread t = thread([&] { svr.listen_after_bind(); });
  2491. auto se = detail::scope_exit([&] {
  2492. svr.stop();
  2493. t.join();
  2494. ASSERT_FALSE(svr.is_running());
  2495. });
  2496. svr.wait_until_ready();
  2497. Client cli(HOST, port);
  2498. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2499. auto res = cli.Post("/", Headers{{"Range", range}});
  2500. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2501. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2502. EXPECT_EQ("abcdefg", res->body) << range;
  2503. }
  2504. }
  2505. TEST(RangeTest, IgnoredForUnknownUnit) {
  2506. Server svr;
  2507. svr.Get("/", [](const Request &, Response &res) {
  2508. res.set_content("abcdefg", "text/plain");
  2509. });
  2510. auto port = svr.bind_to_any_port(HOST);
  2511. ASSERT_GT(port, 0);
  2512. thread t = thread([&] { svr.listen_after_bind(); });
  2513. auto se = detail::scope_exit([&] {
  2514. svr.stop();
  2515. t.join();
  2516. ASSERT_FALSE(svr.is_running());
  2517. });
  2518. svr.wait_until_ready();
  2519. Client cli(HOST, port);
  2520. for (auto range : {"items=1-2", "none=x"}) {
  2521. auto res = cli.Get("/", Headers{{"Range", range}});
  2522. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2523. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2524. EXPECT_EQ("abcdefg", res->body) << range;
  2525. }
  2526. auto res = cli.Get("/", Headers{{"Range", "bytes=x"}});
  2527. ASSERT_TRUE(res) << to_string(res.error());
  2528. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  2529. }
  2530. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2531. auto host = "unresolvableaddress.local";
  2532. auto path = std::string{"/"};
  2533. #ifdef CPPHTTPLIB_SSL_ENABLED
  2534. auto port = 443;
  2535. SSLClient cli(host, port);
  2536. #else
  2537. auto port = 80;
  2538. Client cli(host, port);
  2539. #endif
  2540. cli.set_connection_timeout(1);
  2541. {
  2542. auto res = cli.Get(path);
  2543. ASSERT_FALSE(res);
  2544. }
  2545. std::this_thread::sleep_for(std::chrono::seconds(8));
  2546. }
  2547. #if defined(__linux__) && defined(__GLIBC__) && \
  2548. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2549. // Forward declaration: in split builds split.py strips `inline` and moves the
  2550. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2551. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2552. // against the symbol in both header-only and split builds.
  2553. namespace httplib {
  2554. namespace detail {
  2555. int getaddrinfo_with_timeout(const char *node, const char *service,
  2556. const struct addrinfo *hints,
  2557. struct addrinfo **res, time_t timeout_sec);
  2558. } // namespace detail
  2559. } // namespace httplib
  2560. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2561. //
  2562. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2563. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2564. // gai_suspend() call hits the connection timeout the function calls
  2565. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2566. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2567. // still alive and still references the now-destroyed stack frame.
  2568. //
  2569. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2570. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2571. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2572. // and runs them in a container.
  2573. namespace {
  2574. bool should_run_issue_2431_tests() {
  2575. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2576. return v && *v && std::string(v) != "0";
  2577. }
  2578. std::string unique_unresolvable_host(int n) {
  2579. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2580. // glibc still asks the configured nameserver — which is exactly the path
  2581. // we want to exercise. A unique label per call avoids the resolver cache.
  2582. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2583. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2584. std::to_string(n) + ".invalid";
  2585. }
  2586. } // namespace
  2587. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2588. if (!should_run_issue_2431_tests()) {
  2589. GTEST_SKIP()
  2590. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2591. }
  2592. for (int i = 0; i < 8; ++i) {
  2593. struct addrinfo hints;
  2594. memset(&hints, 0, sizeof(hints));
  2595. hints.ai_family = AF_UNSPEC;
  2596. hints.ai_socktype = SOCK_STREAM;
  2597. auto host = unique_unresolvable_host(i);
  2598. struct addrinfo *result = nullptr;
  2599. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2600. &result, /*timeout_sec=*/1);
  2601. if (rc == 0 && result) { freeaddrinfo(result); }
  2602. }
  2603. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2604. // stack region they still believe holds their gaicb.
  2605. std::this_thread::sleep_for(std::chrono::seconds(3));
  2606. }
  2607. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2608. if (!should_run_issue_2431_tests()) {
  2609. GTEST_SKIP()
  2610. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2611. }
  2612. std::atomic<bool> stop{false};
  2613. std::vector<std::thread> threads;
  2614. for (int t = 0; t < 8; ++t) {
  2615. threads.emplace_back([t, &stop] {
  2616. int i = 0;
  2617. while (!stop.load(std::memory_order_relaxed)) {
  2618. struct addrinfo hints;
  2619. memset(&hints, 0, sizeof(hints));
  2620. hints.ai_family = AF_UNSPEC;
  2621. hints.ai_socktype = SOCK_STREAM;
  2622. auto host = unique_unresolvable_host(t * 100000 + i++);
  2623. struct addrinfo *result = nullptr;
  2624. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2625. &result, /*timeout_sec=*/1);
  2626. if (rc == 0 && result) { freeaddrinfo(result); }
  2627. }
  2628. });
  2629. }
  2630. std::this_thread::sleep_for(std::chrono::seconds(8));
  2631. stop.store(true, std::memory_order_relaxed);
  2632. for (auto &th : threads) {
  2633. th.join();
  2634. }
  2635. std::this_thread::sleep_for(std::chrono::seconds(3));
  2636. }
  2637. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2638. if (!should_run_issue_2431_tests()) {
  2639. GTEST_SKIP()
  2640. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2641. }
  2642. std::atomic<bool> stop{false};
  2643. std::vector<std::thread> threads;
  2644. for (int t = 0; t < 8; ++t) {
  2645. threads.emplace_back([t, &stop] {
  2646. int i = 0;
  2647. while (!stop.load(std::memory_order_relaxed)) {
  2648. auto host = unique_unresolvable_host(t * 100000 + i++);
  2649. Client cli(host, 80);
  2650. cli.set_connection_timeout(1, 0);
  2651. cli.set_read_timeout(1, 0);
  2652. cli.set_write_timeout(1, 0);
  2653. (void)cli.Get("/");
  2654. }
  2655. });
  2656. }
  2657. std::this_thread::sleep_for(std::chrono::seconds(8));
  2658. stop.store(true, std::memory_order_relaxed);
  2659. for (auto &th : threads) {
  2660. th.join();
  2661. }
  2662. std::this_thread::sleep_for(std::chrono::seconds(3));
  2663. }
  2664. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2665. TEST(ConnectionErrorTest, InvalidHost) {
  2666. auto host = "-abcde.com";
  2667. #ifdef CPPHTTPLIB_SSL_ENABLED
  2668. auto port = 443;
  2669. SSLClient cli(host, port);
  2670. #else
  2671. auto port = 80;
  2672. Client cli(host, port);
  2673. #endif
  2674. cli.set_connection_timeout(std::chrono::seconds(2));
  2675. auto res = cli.Get("/");
  2676. ASSERT_TRUE(!res);
  2677. EXPECT_EQ(Error::Connection, res.error());
  2678. }
  2679. TEST(ConnectionErrorTest, InvalidHost2) {
  2680. auto host = "httpcan.org/";
  2681. #ifdef CPPHTTPLIB_SSL_ENABLED
  2682. SSLClient cli(host);
  2683. #else
  2684. Client cli(host);
  2685. #endif
  2686. cli.set_connection_timeout(std::chrono::seconds(2));
  2687. auto res = cli.Get("/");
  2688. ASSERT_TRUE(!res);
  2689. EXPECT_EQ(Error::Connection, res.error());
  2690. }
  2691. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2692. auto host = "httpcan.org/";
  2693. #ifdef CPPHTTPLIB_SSL_ENABLED
  2694. SSLClient cli(host);
  2695. #else
  2696. Client cli(host);
  2697. #endif
  2698. cli.set_connection_timeout(std::chrono::seconds(2));
  2699. auto res = cli.Get("/");
  2700. ASSERT_TRUE(!res);
  2701. stringstream s;
  2702. s << "error code: " << res.error();
  2703. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2704. }
  2705. TEST(ConnectionErrorTest, InvalidPort) {
  2706. auto host = "localhost";
  2707. auto port = 44380;
  2708. #ifdef CPPHTTPLIB_SSL_ENABLED
  2709. SSLClient cli(host, port);
  2710. #else
  2711. Client cli(host, port);
  2712. #endif
  2713. cli.set_connection_timeout(std::chrono::seconds(2));
  2714. auto res = cli.Get("/");
  2715. ASSERT_TRUE(!res);
  2716. EXPECT_TRUE(Error::Connection == res.error() ||
  2717. Error::ConnectionTimeout == res.error());
  2718. }
  2719. TEST(ConnectionErrorTest, Timeout_Online) {
  2720. auto host = "google.com";
  2721. #ifdef CPPHTTPLIB_SSL_ENABLED
  2722. auto port = 44380;
  2723. SSLClient cli(host, port);
  2724. #else
  2725. auto port = 8080;
  2726. Client cli(host, port);
  2727. #endif
  2728. cli.set_connection_timeout(std::chrono::seconds(2));
  2729. // only probe one address type so that the error reason
  2730. // correlates to the timed-out IPv4, not the unsupported
  2731. // IPv6 connection attempt
  2732. cli.set_address_family(AF_INET);
  2733. auto res = cli.Get("/");
  2734. ASSERT_TRUE(!res);
  2735. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2736. }
  2737. TEST(CancelTest, NoCancel_Online) {
  2738. auto host = "httpbingo.org";
  2739. auto path = std::string{"/range/32"};
  2740. #ifdef CPPHTTPLIB_SSL_ENABLED
  2741. auto port = 443;
  2742. SSLClient cli(host, port);
  2743. #else
  2744. auto port = 80;
  2745. Client cli(host, port);
  2746. #endif
  2747. cli.set_connection_timeout(std::chrono::seconds(5));
  2748. auto res = retry_service_failures(
  2749. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return true; }); });
  2750. SKIP_ON_SERVICE_FAILURE(res);
  2751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2752. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2753. EXPECT_EQ(StatusCode::OK_200, res->status);
  2754. }
  2755. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2756. // Use /bytes with a large payload so that the DownloadProgress callback
  2757. // (which only fires for Content-Length responses) is invoked before the
  2758. // entire body is received, giving cancellation a chance to fire.
  2759. auto host = "httpbingo.org";
  2760. auto path = std::string{"/bytes/524288"};
  2761. #ifdef CPPHTTPLIB_SSL_ENABLED
  2762. auto port = 443;
  2763. SSLClient cli(host, port);
  2764. #else
  2765. auto port = 80;
  2766. Client cli(host, port);
  2767. #endif
  2768. auto res = retry_service_failures(
  2769. [&] { return cli.Get(path, [](uint64_t, uint64_t) { return false; }); });
  2770. SKIP_ON_SERVICE_FAILURE(res);
  2771. cli.set_connection_timeout(std::chrono::seconds(5));
  2772. ASSERT_TRUE(!res);
  2773. EXPECT_EQ(Error::Canceled, res.error());
  2774. }
  2775. TEST(CancelTest, WithCancelLargePayload_Online) {
  2776. auto host = "httpbingo.org";
  2777. auto path = std::string{"/bytes/524288"};
  2778. #ifdef CPPHTTPLIB_SSL_ENABLED
  2779. auto port = 443;
  2780. SSLClient cli(host, port);
  2781. #else
  2782. auto port = 80;
  2783. Client cli(host, port);
  2784. #endif
  2785. cli.set_connection_timeout(std::chrono::seconds(5));
  2786. auto res = retry_service_failures([&] {
  2787. auto count = 0;
  2788. return cli.Get(path,
  2789. [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2790. });
  2791. SKIP_ON_SERVICE_FAILURE(res);
  2792. ASSERT_TRUE(!res);
  2793. EXPECT_EQ(Error::Canceled, res.error());
  2794. }
  2795. TEST(CancelTest, NoCancelPost) {
  2796. Server svr;
  2797. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2798. res.set_content("Hello World!", "text/plain");
  2799. });
  2800. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2801. auto se = detail::scope_exit([&] {
  2802. svr.stop();
  2803. thread.join();
  2804. ASSERT_FALSE(svr.is_running());
  2805. });
  2806. svr.wait_until_ready();
  2807. Client cli(HOST, PORT);
  2808. cli.set_connection_timeout(std::chrono::seconds(5));
  2809. auto res =
  2810. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2811. "application/json", [](uint64_t, uint64_t) { return true; });
  2812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2813. EXPECT_EQ("Hello World!", res->body);
  2814. EXPECT_EQ(StatusCode::OK_200, res->status);
  2815. }
  2816. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2817. Server svr;
  2818. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2819. res.set_content("Hello World!", "text/plain");
  2820. });
  2821. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2822. auto se = detail::scope_exit([&] {
  2823. svr.stop();
  2824. thread.join();
  2825. ASSERT_FALSE(svr.is_running());
  2826. });
  2827. svr.wait_until_ready();
  2828. Client cli(HOST, PORT);
  2829. cli.set_connection_timeout(std::chrono::seconds(5));
  2830. auto res =
  2831. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2832. "application/json", [](uint64_t, uint64_t) { return false; });
  2833. ASSERT_TRUE(!res);
  2834. EXPECT_EQ(Error::Canceled, res.error());
  2835. }
  2836. TEST(CancelTest, WithCancelLargePayloadPost) {
  2837. Server svr;
  2838. svr.set_payload_max_length(200 * 1024 * 1024);
  2839. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2840. res.set_content(LARGE_DATA, "text/plain");
  2841. });
  2842. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2843. auto se = detail::scope_exit([&] {
  2844. svr.stop();
  2845. thread.join();
  2846. ASSERT_FALSE(svr.is_running());
  2847. });
  2848. svr.wait_until_ready();
  2849. Client cli(HOST, PORT);
  2850. cli.set_payload_max_length(200 * 1024 * 1024);
  2851. cli.set_connection_timeout(std::chrono::seconds(5));
  2852. auto res =
  2853. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2854. "application/json", [](uint64_t, uint64_t) { return false; });
  2855. ASSERT_TRUE(!res);
  2856. EXPECT_EQ(Error::Canceled, res.error());
  2857. }
  2858. TEST(CancelTest, NoCancelPut) {
  2859. Server svr;
  2860. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2861. res.set_content("Hello World!", "text/plain");
  2862. });
  2863. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2864. auto se = detail::scope_exit([&] {
  2865. svr.stop();
  2866. thread.join();
  2867. ASSERT_FALSE(svr.is_running());
  2868. });
  2869. svr.wait_until_ready();
  2870. Client cli(HOST, PORT);
  2871. cli.set_connection_timeout(std::chrono::seconds(5));
  2872. auto res =
  2873. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2874. "application/json", [](uint64_t, uint64_t) { return true; });
  2875. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2876. EXPECT_EQ("Hello World!", res->body);
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. }
  2879. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2880. Server svr;
  2881. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2882. res.set_content("Hello World!", "text/plain");
  2883. });
  2884. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2885. auto se = detail::scope_exit([&] {
  2886. svr.stop();
  2887. thread.join();
  2888. ASSERT_FALSE(svr.is_running());
  2889. });
  2890. svr.wait_until_ready();
  2891. Client cli(HOST, PORT);
  2892. cli.set_connection_timeout(std::chrono::seconds(5));
  2893. auto res =
  2894. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2895. "application/json", [](uint64_t, uint64_t) { return false; });
  2896. ASSERT_TRUE(!res);
  2897. EXPECT_EQ(Error::Canceled, res.error());
  2898. }
  2899. TEST(CancelTest, WithCancelLargePayloadPut) {
  2900. Server svr;
  2901. svr.set_payload_max_length(200 * 1024 * 1024);
  2902. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2903. res.set_content(LARGE_DATA, "text/plain");
  2904. });
  2905. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2906. auto se = detail::scope_exit([&] {
  2907. svr.stop();
  2908. thread.join();
  2909. ASSERT_FALSE(svr.is_running());
  2910. });
  2911. svr.wait_until_ready();
  2912. Client cli(HOST, PORT);
  2913. cli.set_payload_max_length(200 * 1024 * 1024);
  2914. cli.set_connection_timeout(std::chrono::seconds(5));
  2915. auto res =
  2916. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2917. "application/json", [](uint64_t, uint64_t) { return false; });
  2918. ASSERT_TRUE(!res);
  2919. EXPECT_EQ(Error::Canceled, res.error());
  2920. }
  2921. TEST(CancelTest, NoCancelPatch) {
  2922. Server svr;
  2923. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2924. res.set_content("Hello World!", "text/plain");
  2925. });
  2926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2927. auto se = detail::scope_exit([&] {
  2928. svr.stop();
  2929. thread.join();
  2930. ASSERT_FALSE(svr.is_running());
  2931. });
  2932. svr.wait_until_ready();
  2933. Client cli(HOST, PORT);
  2934. cli.set_connection_timeout(std::chrono::seconds(5));
  2935. auto res =
  2936. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2937. "application/json", [](uint64_t, uint64_t) { return true; });
  2938. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2939. EXPECT_EQ("Hello World!", res->body);
  2940. EXPECT_EQ(StatusCode::OK_200, res->status);
  2941. }
  2942. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2943. Server svr;
  2944. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2945. res.set_content("Hello World!", "text/plain");
  2946. });
  2947. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2948. auto se = detail::scope_exit([&] {
  2949. svr.stop();
  2950. thread.join();
  2951. ASSERT_FALSE(svr.is_running());
  2952. });
  2953. svr.wait_until_ready();
  2954. Client cli(HOST, PORT);
  2955. cli.set_connection_timeout(std::chrono::seconds(5));
  2956. auto res =
  2957. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2958. "application/json", [](uint64_t, uint64_t) { return false; });
  2959. ASSERT_TRUE(!res);
  2960. EXPECT_EQ(Error::Canceled, res.error());
  2961. }
  2962. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2963. Server svr;
  2964. svr.set_payload_max_length(200 * 1024 * 1024);
  2965. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2966. res.set_content(LARGE_DATA, "text/plain");
  2967. });
  2968. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2969. auto se = detail::scope_exit([&] {
  2970. svr.stop();
  2971. thread.join();
  2972. ASSERT_FALSE(svr.is_running());
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, PORT);
  2976. cli.set_payload_max_length(200 * 1024 * 1024);
  2977. cli.set_connection_timeout(std::chrono::seconds(5));
  2978. auto res =
  2979. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2980. "application/json", [](uint64_t, uint64_t) { return false; });
  2981. ASSERT_TRUE(!res);
  2982. EXPECT_EQ(Error::Canceled, res.error());
  2983. }
  2984. TEST(CancelTest, NoCancelDelete) {
  2985. Server svr;
  2986. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2987. res.set_content("Hello World!", "text/plain");
  2988. });
  2989. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2990. auto se = detail::scope_exit([&] {
  2991. svr.stop();
  2992. thread.join();
  2993. ASSERT_FALSE(svr.is_running());
  2994. });
  2995. svr.wait_until_ready();
  2996. Client cli(HOST, PORT);
  2997. cli.set_connection_timeout(std::chrono::seconds(5));
  2998. auto res =
  2999. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3000. "application/json", [](uint64_t, uint64_t) { return true; });
  3001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3002. EXPECT_EQ("Hello World!", res->body);
  3003. EXPECT_EQ(StatusCode::OK_200, res->status);
  3004. }
  3005. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  3006. Server svr;
  3007. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3008. res.set_content("Hello World!", "text/plain");
  3009. });
  3010. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3011. auto se = detail::scope_exit([&] {
  3012. svr.stop();
  3013. thread.join();
  3014. ASSERT_FALSE(svr.is_running());
  3015. });
  3016. svr.wait_until_ready();
  3017. Client cli(HOST, PORT);
  3018. cli.set_connection_timeout(std::chrono::seconds(5));
  3019. auto res =
  3020. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3021. "application/json", [](uint64_t, uint64_t) { return false; });
  3022. ASSERT_TRUE(!res);
  3023. EXPECT_EQ(Error::Canceled, res.error());
  3024. }
  3025. TEST(CancelTest, WithCancelLargePayloadDelete) {
  3026. Server svr;
  3027. svr.set_payload_max_length(200 * 1024 * 1024);
  3028. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  3029. res.set_content(LARGE_DATA, "text/plain");
  3030. });
  3031. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3032. auto se = detail::scope_exit([&] {
  3033. svr.stop();
  3034. thread.join();
  3035. ASSERT_FALSE(svr.is_running());
  3036. });
  3037. svr.wait_until_ready();
  3038. Client cli(HOST, PORT);
  3039. cli.set_payload_max_length(200 * 1024 * 1024);
  3040. cli.set_connection_timeout(std::chrono::seconds(5));
  3041. auto res =
  3042. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  3043. "application/json", [](uint64_t, uint64_t) { return false; });
  3044. ASSERT_TRUE(!res);
  3045. EXPECT_EQ(Error::Canceled, res.error());
  3046. }
  3047. // One stop() from another thread ends a request that waits for the response
  3048. TEST(ClientStopTest, StopEndsWaitForResponse) {
  3049. Server svr;
  3050. std::atomic<bool> received{false};
  3051. std::atomic<bool> done{false};
  3052. svr.Get("/wait", [&](const Request & /*req*/, Response &res) {
  3053. received.store(true);
  3054. while (!done.load()) {
  3055. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3056. }
  3057. res.set_content("Hello World!", "text/plain");
  3058. });
  3059. auto port = svr.bind_to_any_port(HOST);
  3060. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3061. Client cli(HOST, port);
  3062. cli.set_read_timeout(std::chrono::seconds(30));
  3063. std::future<Result> request;
  3064. auto se = detail::scope_exit([&] {
  3065. done.store(true);
  3066. svr.stop();
  3067. thread.join();
  3068. ASSERT_FALSE(svr.is_running());
  3069. });
  3070. svr.wait_until_ready();
  3071. request = std::async(std::launch::async, [&]() { return cli.Get("/wait"); });
  3072. for (int i = 0; i < 500 && !received.load(); ++i) {
  3073. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3074. }
  3075. ASSERT_TRUE(received.load());
  3076. // Let the client block in the wait for the response
  3077. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3078. auto start = std::chrono::steady_clock::now();
  3079. cli.stop();
  3080. ASSERT_EQ(std::future_status::ready,
  3081. request.wait_for(std::chrono::seconds(5)));
  3082. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(2));
  3083. auto res = request.get();
  3084. ASSERT_TRUE(!res);
  3085. EXPECT_EQ(Error::Read, res.error());
  3086. }
  3087. // A listener whose backlog completes the TCP connections of clients, and that
  3088. // never answers them
  3089. struct SilentListener {
  3090. socket_t sock = INVALID_SOCKET;
  3091. sockaddr_in addr{};
  3092. int port = 0;
  3093. explicit SilentListener(int backlog = 1) {
  3094. sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3095. addr.sin_family = AF_INET;
  3096. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  3097. socklen_t len = sizeof(addr);
  3098. if (::bind(sock, reinterpret_cast<sockaddr *>(&addr), len) != 0 ||
  3099. ::listen(sock, backlog) != 0 ||
  3100. ::getsockname(sock, reinterpret_cast<sockaddr *>(&addr), &len) != 0) {
  3101. detail::close_socket(sock);
  3102. sock = INVALID_SOCKET;
  3103. }
  3104. port = ntohs(addr.sin_port);
  3105. }
  3106. ~SilentListener() { detail::close_socket(sock); }
  3107. // The next connection, whose reads give up after 5 seconds
  3108. socket_t accept() const {
  3109. auto peer = ::accept(sock, nullptr, nullptr);
  3110. if (peer != INVALID_SOCKET) {
  3111. detail::set_socket_opt_time(peer, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  3112. }
  3113. return peer;
  3114. }
  3115. };
  3116. static bool receives_a_byte(socket_t peer) {
  3117. char c = 0;
  3118. return detail::read_socket(peer, &c, 1, 0) == 1;
  3119. }
  3120. // Runs op, stops cli once the listener receives the first byte op sends, and
  3121. // expects op to end with error soon after
  3122. template <typename ClientType, typename Op>
  3123. static void expect_stop_ends(ClientType &cli, const SilentListener &listener,
  3124. Op op, Error error = Error::Canceled) {
  3125. auto ended = std::async(std::launch::async, op);
  3126. auto peer = listener.accept();
  3127. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3128. ASSERT_NE(INVALID_SOCKET, peer);
  3129. ASSERT_TRUE(receives_a_byte(peer));
  3130. cli.stop();
  3131. EXPECT_EQ(std::future_status::ready, ended.wait_for(std::chrono::seconds(2)));
  3132. EXPECT_EQ(error, ended.get());
  3133. }
  3134. // Stops itself from another thread as the connection opens, the last moment a
  3135. // stop() cancels it. It waits for stop() at most a second, so a stop() that
  3136. // waits for the connection fails the test instead of hanging it.
  3137. class StoppedAsConnectedClient : public ClientImpl {
  3138. public:
  3139. using ClientImpl::ClientImpl;
  3140. protected:
  3141. bool ensure_socket_connection(Socket &socket, Error &error) override {
  3142. if (!ClientImpl::ensure_socket_connection(socket, error)) { return false; }
  3143. stopper_ = std::async(std::launch::async, [this] { stop(); });
  3144. stopper_.wait_for(std::chrono::seconds(1));
  3145. return true;
  3146. }
  3147. private:
  3148. std::future<void> stopper_;
  3149. };
  3150. TEST(ClientStopTest, StopAsTheConnectionOpensEndsTheRequest) {
  3151. SilentListener listener;
  3152. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3153. StoppedAsConnectedClient cli("127.0.0.1", listener.port);
  3154. cli.set_read_timeout(std::chrono::seconds(3));
  3155. EXPECT_EQ(Error::Canceled, cli.Get("/").error());
  3156. auto peer = listener.accept();
  3157. EXPECT_FALSE(receives_a_byte(peer));
  3158. detail::close_socket(peer);
  3159. auto handle = cli.open_stream("GET", "/");
  3160. EXPECT_FALSE(handle.is_valid());
  3161. EXPECT_EQ(Error::Canceled, handle.error);
  3162. peer = listener.accept();
  3163. EXPECT_FALSE(receives_a_byte(peer));
  3164. detail::close_socket(peer);
  3165. }
  3166. #ifdef __linux__
  3167. // A connect that a listener with a full backlog never completes
  3168. TEST(ClientStopTest, StopEndsAConnect) {
  3169. SilentListener listener(0);
  3170. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3171. std::vector<socket_t> backlog;
  3172. auto close_backlog = detail::scope_exit([&] {
  3173. for (auto sock : backlog) {
  3174. detail::close_socket(sock);
  3175. }
  3176. });
  3177. for (int i = 0; i < 8; i++) {
  3178. auto sock = ::socket(AF_INET, SOCK_STREAM | SOCK_NONBLOCK, 0);
  3179. ::connect(sock, reinterpret_cast<const sockaddr *>(&listener.addr),
  3180. sizeof(listener.addr));
  3181. backlog.push_back(sock);
  3182. }
  3183. Client cli("127.0.0.1", listener.port);
  3184. cli.set_connection_timeout(std::chrono::seconds(3));
  3185. auto ended =
  3186. std::async(std::launch::async, [&] { return cli.Get("/").error(); });
  3187. // A stop() before the request starts does not apply to it, so it repeats
  3188. auto status = std::future_status::timeout;
  3189. for (auto i = 0; i < 200 && status != std::future_status::ready; i++) {
  3190. cli.stop();
  3191. status = ended.wait_for(std::chrono::milliseconds(10));
  3192. }
  3193. EXPECT_EQ(std::future_status::ready, status);
  3194. EXPECT_EQ(Error::Canceled, ended.get());
  3195. }
  3196. #endif
  3197. // The stream holds the socket while it waits for the head, out of the reach
  3198. // of shutdown()
  3199. TEST(ClientStopTest, StopEndsTheWaitForTheHeadOfAStream) {
  3200. SilentListener listener;
  3201. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3202. Client cli("127.0.0.1", listener.port);
  3203. cli.set_read_timeout(std::chrono::seconds(3));
  3204. expect_stop_ends(
  3205. cli, listener, [&] { return cli.open_stream("GET", "/").error; },
  3206. Error::Read);
  3207. }
  3208. #ifdef CPPHTTPLIB_SSL_ENABLED
  3209. // A server that never answers the ClientHello
  3210. TEST(ClientStopTest, StopEndsATlsHandshake) {
  3211. SilentListener listener;
  3212. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3213. SSLClient cli("127.0.0.1", listener.port);
  3214. cli.enable_server_certificate_verification(false);
  3215. cli.set_connection_timeout(std::chrono::seconds(3));
  3216. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3217. expect_stop_ends(cli, listener,
  3218. [&] { return cli.open_stream("GET", "/").error; });
  3219. }
  3220. // A proxy that takes the CONNECT and never answers it
  3221. TEST(ClientStopTest, StopEndsAProxyTunnel) {
  3222. SilentListener listener;
  3223. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3224. SSLClient cli("example.com", 443);
  3225. cli.set_proxy("127.0.0.1", listener.port);
  3226. cli.set_read_timeout(std::chrono::seconds(3));
  3227. expect_stop_ends(cli, listener, [&] { return cli.Get("/").error(); });
  3228. }
  3229. #endif
  3230. // A read timeout past what the clock reaches waits for the response
  3231. TEST(ClientReadTimeoutTest, PastTheClockWaitsForTheResponse) {
  3232. SilentListener listener;
  3233. ASSERT_NE(INVALID_SOCKET, listener.sock);
  3234. Client cli("127.0.0.1", listener.port);
  3235. cli.set_read_timeout(
  3236. static_cast<time_t>((std::min)(static_cast<long long>(
  3237. (std::numeric_limits<time_t>::max)()),
  3238. 10000000000LL)),
  3239. 0);
  3240. auto res = std::async(std::launch::async, [&] { return cli.Get("/"); });
  3241. auto peer = listener.accept();
  3242. auto close_peer = detail::scope_exit([&] { detail::close_socket(peer); });
  3243. ASSERT_NE(INVALID_SOCKET, peer);
  3244. ASSERT_TRUE(receives_a_byte(peer));
  3245. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  3246. std::string answer = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  3247. "Connection: close\r\n\r\nok";
  3248. detail::send_socket(peer, answer.data(), answer.size(), 0);
  3249. auto result = res.get();
  3250. ASSERT_TRUE(result);
  3251. EXPECT_EQ("ok", result->body);
  3252. }
  3253. static std::string remove_whitespace(const std::string &input) {
  3254. std::string output;
  3255. output.reserve(input.size());
  3256. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  3257. [](unsigned char c) { return !std::isspace(c); });
  3258. return output;
  3259. }
  3260. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  3261. auto host = "httpbingo.org";
  3262. auto path = std::string{"/basic-auth/hello/world"};
  3263. #ifdef CPPHTTPLIB_SSL_ENABLED
  3264. auto port = 443;
  3265. SSLClient cli(host, port);
  3266. #else
  3267. auto port = 80;
  3268. Client cli(host, port);
  3269. #endif
  3270. {
  3271. auto res = retry_service_failures([&] { return cli.Get(path); });
  3272. SKIP_ON_SERVICE_FAILURE(res);
  3273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3274. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3275. }
  3276. {
  3277. auto res = retry_service_failures([&] {
  3278. return cli.Get(
  3279. path, Headers{make_basic_authentication_header("hello", "world")});
  3280. });
  3281. SKIP_ON_SERVICE_FAILURE(res);
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. auto body = remove_whitespace(res->body);
  3284. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3285. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3286. EXPECT_EQ(StatusCode::OK_200, res->status);
  3287. }
  3288. {
  3289. cli.set_basic_auth("hello", "world");
  3290. auto res = retry_service_failures([&] { return cli.Get(path); });
  3291. SKIP_ON_SERVICE_FAILURE(res);
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. auto body = remove_whitespace(res->body);
  3294. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3295. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3296. EXPECT_EQ(StatusCode::OK_200, res->status);
  3297. }
  3298. {
  3299. cli.set_basic_auth("hello", "bad");
  3300. auto res = retry_service_failures([&] { return cli.Get(path); });
  3301. SKIP_ON_SERVICE_FAILURE(res);
  3302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3303. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3304. }
  3305. {
  3306. cli.set_basic_auth("bad", "world");
  3307. auto res = retry_service_failures([&] { return cli.Get(path); });
  3308. SKIP_ON_SERVICE_FAILURE(res);
  3309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3310. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3311. }
  3312. }
  3313. #ifdef CPPHTTPLIB_SSL_ENABLED
  3314. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  3315. auto host = "httpbingo.org";
  3316. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  3317. auto paths = std::vector<std::string>{
  3318. "/digest-auth/auth/hello/world/MD5",
  3319. "/digest-auth/auth/hello/world/SHA-256",
  3320. };
  3321. auto port = 443;
  3322. SSLClient cli(host, port);
  3323. {
  3324. auto res = retry_service_failures([&] { return cli.Get(unauth_path); });
  3325. SKIP_ON_SERVICE_FAILURE(res);
  3326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3327. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3328. }
  3329. {
  3330. cli.set_digest_auth("hello", "world");
  3331. for (const auto &path : paths) {
  3332. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3333. SKIP_ON_SERVICE_FAILURE(res);
  3334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3335. auto body = remove_whitespace(res->body);
  3336. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  3337. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  3338. EXPECT_EQ(StatusCode::OK_200, res->status);
  3339. }
  3340. cli.set_digest_auth("hello", "bad");
  3341. for (const auto &path : paths) {
  3342. auto res = retry_service_failures([&] { return cli.Get(path.c_str()); });
  3343. SKIP_ON_SERVICE_FAILURE(res);
  3344. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3345. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3346. }
  3347. }
  3348. }
  3349. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  3350. // comma-separated list of challenges, and each challenge may itself carry a
  3351. // comma-separated auth-param list, so a server can legally offer Basic
  3352. // before Digest, either as two field lines or packed into one. Runs one 401
  3353. // -> Digest-retry round trip with the given field lines (get_combined_header_
  3354. // value() joins them in receipt order) and checks that the retry carries a
  3355. // well-formed Digest Authorization header naming expected_realm.
  3356. static void
  3357. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  3358. const std::string &expected_realm) {
  3359. std::atomic<int> hits{0};
  3360. Server svr;
  3361. svr.Get("/x", [&](const Request &req, Response &res) {
  3362. if (++hits == 1) {
  3363. res.status = StatusCode::Unauthorized_401;
  3364. for (const auto &challenge : challenges) {
  3365. res.set_header("WWW-Authenticate", challenge);
  3366. }
  3367. } else {
  3368. auto authorization = req.get_header_value("Authorization");
  3369. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3370. EXPECT_NE(std::string::npos,
  3371. authorization.find("realm=\"" + expected_realm + "\""));
  3372. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  3373. res.set_content("ok", "text/plain");
  3374. }
  3375. });
  3376. auto port = svr.bind_to_any_port(HOST);
  3377. std::thread t([&]() { svr.listen_after_bind(); });
  3378. auto se = detail::scope_exit([&] {
  3379. svr.stop();
  3380. t.join();
  3381. });
  3382. svr.wait_until_ready();
  3383. Client cli(HOST, port);
  3384. cli.set_digest_auth("hello", "world");
  3385. auto res = cli.Get("/x");
  3386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3387. EXPECT_EQ(2, hits.load());
  3388. }
  3389. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  3390. static const char *kDigestChallenge =
  3391. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  3392. "algorithm=MD5";
  3393. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  3394. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  3395. "testrealm");
  3396. }
  3397. // Same challenge list with the schemes in the opposite order, to make sure
  3398. // the fix above didn't just special-case "Basic first".
  3399. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  3400. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  3401. "testrealm");
  3402. }
  3403. // A comma inside a quoted auth-param value must not be mistaken for the
  3404. // separator between two challenges (or two auth-params).
  3405. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  3406. run_digest_challenge_list_test(
  3407. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3408. "algorithm=MD5"},
  3409. "test,realm");
  3410. }
  3411. // RFC 9110 11.2: auth-param names are matched case-insensitively.
  3412. TEST(DigestAuthTest, ParamNamesAreCaseInsensitive) {
  3413. std::atomic<int> hits{0};
  3414. std::string authorization;
  3415. Server svr;
  3416. svr.Get("/x", [&](const Request &req, Response &res) {
  3417. if (++hits == 1) {
  3418. res.status = StatusCode::Unauthorized_401;
  3419. res.set_header("WWW-Authenticate",
  3420. "Digest Realm=\"testrealm\", QOP=\"auth\", "
  3421. "Nonce=\"abc123\", Algorithm=SHA-256, OPAQUE=\"op\"");
  3422. } else {
  3423. authorization = req.get_header_value("Authorization");
  3424. res.set_content("ok", "text/plain");
  3425. }
  3426. });
  3427. auto port = svr.bind_to_any_port(HOST);
  3428. std::thread t([&]() { svr.listen_after_bind(); });
  3429. auto se = detail::scope_exit([&] {
  3430. svr.stop();
  3431. t.join();
  3432. });
  3433. svr.wait_until_ready();
  3434. Client cli(HOST, port);
  3435. cli.set_digest_auth("hello", "world");
  3436. auto res = cli.Get("/x");
  3437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3438. EXPECT_EQ(2, hits.load());
  3439. EXPECT_NE(std::string::npos, authorization.find("realm=\"testrealm\""));
  3440. EXPECT_NE(std::string::npos, authorization.find("nonce=\"abc123\""));
  3441. EXPECT_NE(std::string::npos, authorization.find("algorithm=SHA-256"));
  3442. EXPECT_NE(std::string::npos, authorization.find("qop=auth"));
  3443. EXPECT_NE(std::string::npos, authorization.find("opaque=\"op\""));
  3444. }
  3445. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3446. // the params and leaves out the fragment.
  3447. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3448. Server svr;
  3449. std::string uri, target;
  3450. svr.Get("/a b", [&](const Request &req, Response &res) {
  3451. auto auth = req.get_header_value("Authorization");
  3452. if (auth.empty()) {
  3453. res.status = StatusCode::Unauthorized_401;
  3454. res.set_header("WWW-Authenticate",
  3455. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3456. return;
  3457. }
  3458. auto b = auth.find("uri=\"") + 5;
  3459. uri = auth.substr(b, auth.find('"', b) - b);
  3460. target = req.target;
  3461. });
  3462. auto port = svr.bind_to_any_port(HOST);
  3463. std::thread t([&]() { svr.listen_after_bind(); });
  3464. auto se = detail::scope_exit([&] {
  3465. svr.stop();
  3466. t.join();
  3467. });
  3468. svr.wait_until_ready();
  3469. Client cli(HOST, port);
  3470. cli.set_digest_auth("hello", "world");
  3471. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3473. EXPECT_EQ("/a%20b?x=1", target);
  3474. EXPECT_EQ(target, uri);
  3475. }
  3476. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3477. // make_digest_authentication_header() dereferences both unconditionally, so
  3478. // a server sending a challenge missing either one must not be treated as
  3479. // usable -- doing so used to crash the client with std::out_of_range.
  3480. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3481. Server svr;
  3482. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3483. res.status = StatusCode::Unauthorized_401;
  3484. res.set_header("WWW-Authenticate", challenge);
  3485. });
  3486. auto port = svr.bind_to_any_port(HOST);
  3487. std::thread t([&]() { svr.listen_after_bind(); });
  3488. auto se = detail::scope_exit([&] {
  3489. svr.stop();
  3490. t.join();
  3491. });
  3492. svr.wait_until_ready();
  3493. Client cli(HOST, port);
  3494. cli.set_digest_auth("hello", "world");
  3495. auto res = cli.Get("/x");
  3496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3497. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3498. }
  3499. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3500. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3501. }
  3502. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3503. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3504. }
  3505. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3506. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3507. }
  3508. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3509. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3510. // when storing the values, so the header builder has to re-escape them (and
  3511. // keep algorithm a bare token); otherwise the value breaks out of its
  3512. // quoted-string and injects extra auth-params into the client's Authorization.
  3513. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3514. std::atomic<int> hits{0};
  3515. std::string authorization;
  3516. Server svr;
  3517. svr.Get("/x", [&](const Request &req, Response &res) {
  3518. if (++hits == 1) {
  3519. res.status = StatusCode::Unauthorized_401;
  3520. // On the wire the quotes embedded in the values are backslash-escaped.
  3521. res.set_header("WWW-Authenticate",
  3522. "Digest realm=\"testrealm\", "
  3523. "nonce=\"n\\\"; injected=\\\"x\", "
  3524. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3525. } else {
  3526. authorization = req.get_header_value("Authorization");
  3527. res.set_content("ok", "text/plain");
  3528. }
  3529. });
  3530. auto port = svr.bind_to_any_port(HOST);
  3531. std::thread t([&]() { svr.listen_after_bind(); });
  3532. auto se = detail::scope_exit([&] {
  3533. svr.stop();
  3534. t.join();
  3535. });
  3536. svr.wait_until_ready();
  3537. Client cli(HOST, port);
  3538. cli.set_digest_auth("hello", "world");
  3539. auto res = cli.Get("/x");
  3540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3541. EXPECT_EQ(2, hits.load());
  3542. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3543. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3544. // inside its quoted-string rather than starting an "injected" auth-param.
  3545. EXPECT_NE(std::string::npos,
  3546. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3547. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3548. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3549. }
  3550. #endif
  3551. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3552. auto host = "google.com";
  3553. auto another_host = "example.com";
  3554. auto wrong_ip = "0.0.0.0";
  3555. #ifdef CPPHTTPLIB_SSL_ENABLED
  3556. SSLClient cli(host);
  3557. #else
  3558. Client cli(host);
  3559. #endif
  3560. cli.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  3561. auto res = cli.Get("/");
  3562. // Any status: Google may redirect or rate-limit CI runners.
  3563. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3564. }
  3565. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3566. auto host = "google.com";
  3567. auto wrong_ip = "0.0.0.0";
  3568. #ifdef CPPHTTPLIB_SSL_ENABLED
  3569. SSLClient cli(host);
  3570. #else
  3571. Client cli(host);
  3572. #endif
  3573. cli.set_direct_hostname_addr_map({{host, wrong_ip}});
  3574. auto res = cli.Get("/");
  3575. ASSERT_TRUE(!res);
  3576. EXPECT_EQ(Error::Connection, res.error());
  3577. }
  3578. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3579. // A mapped value that is not an IP literal must be resolved. "localhost"
  3580. // resolves from the hosts file, so this test needs no external DNS.
  3581. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3582. auto host = "target.invalid";
  3583. Server svr;
  3584. std::string received_host;
  3585. svr.Get("/hi", [&](const Request &req, Response &res) {
  3586. received_host = req.get_header_value("Host");
  3587. res.set_content("Hello World!", "text/plain");
  3588. });
  3589. auto port = svr.bind_to_any_port(HOST);
  3590. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3591. auto se = detail::scope_exit([&] {
  3592. svr.stop();
  3593. thread.join();
  3594. ASSERT_FALSE(svr.is_running());
  3595. });
  3596. svr.wait_until_ready();
  3597. Client cli(host, port);
  3598. cli.set_direct_hostname_addr_map({{host, HOST}});
  3599. auto res = cli.Get("/hi");
  3600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3601. EXPECT_EQ(StatusCode::OK_200, res->status);
  3602. // The mapping only redirects the connection; the identity stays host_.
  3603. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3604. }
  3605. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3606. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3607. auto host = "target.invalid";
  3608. Server svr;
  3609. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3610. res.set_content("Hello World!", "text/plain");
  3611. });
  3612. auto port = svr.bind_to_any_port("127.0.0.1");
  3613. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3614. auto se = detail::scope_exit([&] {
  3615. svr.stop();
  3616. thread.join();
  3617. ASSERT_FALSE(svr.is_running());
  3618. });
  3619. svr.wait_until_ready();
  3620. Client cli(host, port);
  3621. cli.set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  3622. auto res = cli.Get("/hi");
  3623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3624. EXPECT_EQ(StatusCode::OK_200, res->status);
  3625. }
  3626. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3627. // An empty mapped value must leave host_ as the connection target. Without
  3628. // that guard the empty value would become the host argument, getaddrinfo
  3629. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3630. // loopback - silently connecting somewhere the caller never asked for.
  3631. // The server listens on loopback, so such a fallback would succeed and is
  3632. // therefore observable as a failure of this test.
  3633. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3634. Server svr;
  3635. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3636. res.set_content("Hello World!", "text/plain");
  3637. });
  3638. auto port = svr.bind_to_any_port(HOST);
  3639. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3640. auto se = detail::scope_exit([&] {
  3641. svr.stop();
  3642. thread.join();
  3643. ASSERT_FALSE(svr.is_running());
  3644. });
  3645. svr.wait_until_ready();
  3646. Client cli(blackhole, port);
  3647. cli.set_direct_hostname_addr_map({{blackhole, ""}});
  3648. cli.set_connection_timeout(1);
  3649. auto res = cli.Get("/hi");
  3650. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3651. }
  3652. TEST(SpecifyServerIPAddressTest, DeprecatedSetHostnameAddrMapStillWorks) {
  3653. auto host = "target.invalid";
  3654. Server svr;
  3655. std::string received_host;
  3656. svr.Get("/hi", [&](const Request &req, Response &res) {
  3657. received_host = req.get_header_value("Host");
  3658. res.set_content("Hello World!", "text/plain");
  3659. });
  3660. auto port = svr.bind_to_any_port("127.0.0.1");
  3661. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3662. auto se = detail::scope_exit([&] {
  3663. svr.stop();
  3664. thread.join();
  3665. ASSERT_FALSE(svr.is_running());
  3666. });
  3667. svr.wait_until_ready();
  3668. Client cli(host, port);
  3669. #pragma GCC diagnostic push
  3670. #pragma GCC diagnostic ignored "-Wdeprecated-declarations"
  3671. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3672. #pragma GCC diagnostic pop
  3673. auto res = cli.Get("/hi");
  3674. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3675. EXPECT_EQ(StatusCode::OK_200, res->status);
  3676. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3677. }
  3678. TEST(TunnelHostnameAddrMapTest, IgnoredOnDirectConnection) {
  3679. // 192.0.2.1 is TEST-NET-1: applying the map would fail to connect.
  3680. Server svr;
  3681. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3682. res.set_content("Hello World!", "text/plain");
  3683. });
  3684. auto port = svr.bind_to_any_port("127.0.0.1");
  3685. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3686. auto se = detail::scope_exit([&] {
  3687. svr.stop();
  3688. thread.join();
  3689. ASSERT_FALSE(svr.is_running());
  3690. });
  3691. svr.wait_until_ready();
  3692. Client cli("127.0.0.1", port);
  3693. cli.set_tunnel_hostname_addr_map({{"127.0.0.1", "192.0.2.1"}});
  3694. cli.set_connection_timeout(1);
  3695. auto res = cli.Get("/hi");
  3696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3697. EXPECT_EQ(StatusCode::OK_200, res->status);
  3698. }
  3699. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3700. auto host = "httpbingo.org";
  3701. auto path = std::string{"/absolute-redirect/3"};
  3702. #ifdef CPPHTTPLIB_SSL_ENABLED
  3703. SSLClient cli(host);
  3704. #else
  3705. Client cli(host);
  3706. #endif
  3707. cli.set_follow_location(true);
  3708. auto res = retry_service_failures([&] { return cli.Get(path); });
  3709. SKIP_ON_SERVICE_FAILURE(res);
  3710. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3711. EXPECT_EQ(StatusCode::OK_200, res->status);
  3712. }
  3713. TEST(RedirectTest, Redirect_Online) {
  3714. auto host = "httpbingo.org";
  3715. auto path = std::string{"/redirect/3"};
  3716. #ifdef CPPHTTPLIB_SSL_ENABLED
  3717. SSLClient cli(host);
  3718. #else
  3719. Client cli(host);
  3720. #endif
  3721. cli.set_follow_location(true);
  3722. auto res = retry_service_failures([&] { return cli.Get(path); });
  3723. SKIP_ON_SERVICE_FAILURE(res);
  3724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3725. EXPECT_EQ(StatusCode::OK_200, res->status);
  3726. }
  3727. TEST(RelativeRedirectTest, Redirect_Online) {
  3728. auto host = "httpbingo.org";
  3729. auto path = std::string{"/relative-redirect/3"};
  3730. #ifdef CPPHTTPLIB_SSL_ENABLED
  3731. SSLClient cli(host);
  3732. #else
  3733. Client cli(host);
  3734. #endif
  3735. cli.set_follow_location(true);
  3736. auto res = retry_service_failures([&] { return cli.Get(path); });
  3737. SKIP_ON_SERVICE_FAILURE(res);
  3738. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3739. EXPECT_EQ(StatusCode::OK_200, res->status);
  3740. }
  3741. TEST(TooManyRedirectTest, Redirect_Online) {
  3742. auto host = "httpbingo.org";
  3743. auto path = std::string{"/redirect/21"};
  3744. #ifdef CPPHTTPLIB_SSL_ENABLED
  3745. SSLClient cli(host);
  3746. #else
  3747. Client cli(host);
  3748. #endif
  3749. cli.set_follow_location(true);
  3750. auto res = retry_service_failures([&] { return cli.Get(path); });
  3751. SKIP_ON_SERVICE_FAILURE(res);
  3752. ASSERT_TRUE(!res);
  3753. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3754. }
  3755. #ifdef CPPHTTPLIB_SSL_ENABLED
  3756. TEST(YahooRedirectTest, Redirect_Online) {
  3757. Client cli("yahoo.com");
  3758. auto res = cli.Get("/");
  3759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3760. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3761. cli.set_follow_location(true);
  3762. res = cli.Get("/");
  3763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3764. EXPECT_EQ(StatusCode::OK_200, res->status);
  3765. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3766. }
  3767. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3768. #define REDIR_HOST "httpbingo.org"
  3769. #define REDIR_PATH "/redirect-to"
  3770. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3771. SSLClient cli(REDIR_HOST);
  3772. cli.set_follow_location(true);
  3773. auto res = retry_service_failures([&] {
  3774. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3775. });
  3776. SKIP_ON_SERVICE_FAILURE(res);
  3777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3778. EXPECT_EQ(StatusCode::OK_200, res->status);
  3779. }
  3780. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3781. SSLClient cli(REDIR_HOST);
  3782. cli.set_follow_location(true);
  3783. Params params;
  3784. params.emplace("url", "http://example.com");
  3785. params.emplace("status_code", "302");
  3786. auto res = retry_service_failures(
  3787. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  3788. SKIP_ON_SERVICE_FAILURE(res);
  3789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3790. EXPECT_EQ(StatusCode::OK_200, res->status);
  3791. }
  3792. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3793. SSLClient cli(REDIR_HOST);
  3794. cli.set_follow_location(true);
  3795. Params params;
  3796. params.emplace("url", "http://example.com");
  3797. auto res = retry_service_failures([&] {
  3798. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3799. });
  3800. SKIP_ON_SERVICE_FAILURE(res);
  3801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3802. EXPECT_EQ(StatusCode::OK_200, res->status);
  3803. }
  3804. TEST(UrlWithSpace, Redirect_Online) {
  3805. SSLClient cli("edge.forgecdn.net");
  3806. cli.set_follow_location(true);
  3807. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3809. EXPECT_EQ(StatusCode::OK_200, res->status);
  3810. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3811. }
  3812. #endif
  3813. #if !defined(_WIN32) && !defined(_WIN64)
  3814. TEST(ReceiveSignals, Signal) {
  3815. auto setupSignalHandlers = []() {
  3816. struct sigaction act;
  3817. sigemptyset(&act.sa_mask);
  3818. act.sa_flags = SA_SIGINFO;
  3819. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3820. switch (sig) {
  3821. case SIGINT:
  3822. default: break;
  3823. }
  3824. };
  3825. ::sigaction(SIGINT, &act, nullptr);
  3826. };
  3827. Server svr;
  3828. int port = 0;
  3829. auto thread = std::thread([&]() {
  3830. setupSignalHandlers();
  3831. port = svr.bind_to_any_port(HOST);
  3832. svr.listen_after_bind();
  3833. });
  3834. auto se = detail::scope_exit([&] {
  3835. svr.stop();
  3836. thread.join();
  3837. ASSERT_FALSE(svr.is_running());
  3838. });
  3839. svr.wait_until_ready();
  3840. ASSERT_TRUE(svr.is_running());
  3841. pthread_kill(thread.native_handle(), SIGINT);
  3842. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3843. ASSERT_TRUE(svr.is_running());
  3844. }
  3845. #endif
  3846. TEST(RedirectToDifferentPort, Redirect) {
  3847. Server svr1;
  3848. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3849. res.set_content("Hello World!", "text/plain");
  3850. });
  3851. int svr1_port = 0;
  3852. auto thread1 = std::thread([&]() {
  3853. svr1_port = svr1.bind_to_any_port(HOST);
  3854. svr1.listen_after_bind();
  3855. });
  3856. Server svr2;
  3857. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3858. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3859. });
  3860. int svr2_port = 0;
  3861. auto thread2 = std::thread([&]() {
  3862. svr2_port = svr2.bind_to_any_port(HOST);
  3863. svr2.listen_after_bind();
  3864. });
  3865. auto se = detail::scope_exit([&] {
  3866. svr2.stop();
  3867. thread2.join();
  3868. svr1.stop();
  3869. thread1.join();
  3870. ASSERT_FALSE(svr2.is_running());
  3871. ASSERT_FALSE(svr1.is_running());
  3872. });
  3873. svr1.wait_until_ready();
  3874. svr2.wait_until_ready();
  3875. Client cli("localhost", svr2_port);
  3876. cli.set_follow_location(true);
  3877. auto res = cli.Get("/2");
  3878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3879. EXPECT_EQ(StatusCode::OK_200, res->status);
  3880. EXPECT_EQ("Hello World!", res->body);
  3881. }
  3882. // GET /redir on one server redirects to /target on another port, so the
  3883. // client follows it with a new client.
  3884. static Result
  3885. GetThroughRedirectToDifferentPort(Server::Handler target,
  3886. const std::function<void(Client &)> &setup,
  3887. const Headers &headers = Headers()) {
  3888. Server target_svr;
  3889. target_svr.Get("/target", target);
  3890. int target_port = 0;
  3891. auto target_thread = std::thread([&]() {
  3892. target_port = target_svr.bind_to_any_port(HOST);
  3893. target_svr.listen_after_bind();
  3894. });
  3895. Server origin_svr;
  3896. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3897. res.set_redirect(
  3898. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3899. });
  3900. int origin_port = 0;
  3901. auto origin_thread = std::thread([&]() {
  3902. origin_port = origin_svr.bind_to_any_port(HOST);
  3903. origin_svr.listen_after_bind();
  3904. });
  3905. auto se = detail::scope_exit([&] {
  3906. origin_svr.stop();
  3907. origin_thread.join();
  3908. target_svr.stop();
  3909. target_thread.join();
  3910. });
  3911. target_svr.wait_until_ready();
  3912. origin_svr.wait_until_ready();
  3913. Client cli("localhost", origin_port);
  3914. cli.set_follow_location(true);
  3915. setup(cli);
  3916. return cli.Get("/redir", headers);
  3917. }
  3918. static void
  3919. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3920. std::string captured_authorization;
  3921. auto result = GetThroughRedirectToDifferentPort(
  3922. [&](const Request &req, Response &res) {
  3923. captured_authorization = req.get_header_value("Authorization");
  3924. res.set_content("OK", "text/plain");
  3925. },
  3926. set_auth);
  3927. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3928. EXPECT_EQ(StatusCode::OK_200, result->status);
  3929. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3930. EXPECT_TRUE(captured_authorization.empty());
  3931. }
  3932. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3933. TestDoNotForwardCredentialsOnRedirect(
  3934. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3935. }
  3936. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3937. TestDoNotForwardCredentialsOnRedirect(
  3938. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3939. }
  3940. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3941. std::string captured_cookie;
  3942. auto result = GetThroughRedirectToDifferentPort(
  3943. [&](const Request &req, Response &res) {
  3944. captured_cookie = req.get_header_value("Cookie");
  3945. res.set_content("OK", "text/plain");
  3946. },
  3947. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3948. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3949. EXPECT_EQ(StatusCode::OK_200, result->status);
  3950. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3951. EXPECT_TRUE(captured_cookie.empty());
  3952. }
  3953. TEST(RedirectToSamePort, ForwardCookie) {
  3954. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3955. // header so that ordinary session flows keep working.
  3956. Server svr;
  3957. std::string captured_cookie;
  3958. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3959. res.set_redirect("/target", 302);
  3960. });
  3961. svr.Get("/target", [&](const Request &req, Response &res) {
  3962. captured_cookie = req.get_header_value("Cookie");
  3963. res.set_content("OK", "text/plain");
  3964. });
  3965. auto port = svr.bind_to_any_port(HOST);
  3966. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3967. auto se = detail::scope_exit([&] {
  3968. svr.stop();
  3969. thread.join();
  3970. ASSERT_FALSE(svr.is_running());
  3971. });
  3972. svr.wait_until_ready();
  3973. Client cli(HOST, port);
  3974. cli.set_follow_location(true);
  3975. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3976. auto res = cli.Get("/redir", headers);
  3977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3978. EXPECT_EQ(StatusCode::OK_200, res->status);
  3979. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3980. }
  3981. TEST(RedirectTest, DoNotCarryRequestParamsToLocation) {
  3982. // The Location alone names the next target, on any origin.
  3983. Server target_svr;
  3984. std::string cross_target;
  3985. target_svr.Get("/landing", [&](const Request &req, Response &res) {
  3986. cross_target = req.target;
  3987. res.set_content("OK", "text/plain");
  3988. });
  3989. auto target_port = target_svr.bind_to_any_port(HOST);
  3990. auto target_thread = std::thread([&]() { target_svr.listen_after_bind(); });
  3991. Server origin_svr;
  3992. std::string same_target;
  3993. origin_svr.Get("/cross", [&](const Request &, Response &res) {
  3994. res.set_redirect(
  3995. "http://localhost:" + std::to_string(target_port) + "/landing", 302);
  3996. });
  3997. origin_svr.Get("/same", [&](const Request &, Response &res) {
  3998. res.set_redirect("/landing", 302);
  3999. });
  4000. origin_svr.Get("/landing", [&](const Request &req, Response &res) {
  4001. same_target = req.target;
  4002. res.set_content("OK", "text/plain");
  4003. });
  4004. auto origin_port = origin_svr.bind_to_any_port(HOST);
  4005. auto origin_thread = std::thread([&]() { origin_svr.listen_after_bind(); });
  4006. auto se = detail::scope_exit([&] {
  4007. origin_svr.stop();
  4008. origin_thread.join();
  4009. target_svr.stop();
  4010. target_thread.join();
  4011. });
  4012. target_svr.wait_until_ready();
  4013. origin_svr.wait_until_ready();
  4014. Client cli("localhost", origin_port);
  4015. cli.set_follow_location(true);
  4016. Request req;
  4017. req.method = "GET";
  4018. req.params = {{"api_key", "SECRET"}};
  4019. req.path = "/cross";
  4020. auto res = cli.send(req);
  4021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4022. EXPECT_EQ("/landing", cross_target);
  4023. req.path = "/same";
  4024. res = cli.send(req);
  4025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4026. EXPECT_EQ("/landing", same_target);
  4027. }
  4028. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  4029. std::string authorization;
  4030. std::string trace_id;
  4031. auto result = GetThroughRedirectToDifferentPort(
  4032. [&](const Request &req, Response &res) {
  4033. authorization = req.get_header_value("Authorization");
  4034. trace_id = req.get_header_value("X-Trace-Id");
  4035. res.set_content("OK", "text/plain");
  4036. },
  4037. [](Client &cli) {
  4038. cli.set_default_headers(
  4039. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  4040. });
  4041. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4042. EXPECT_EQ(StatusCode::OK_200, result->status);
  4043. // Like a header given with the request, a default one goes along unless it
  4044. // carries credentials (RFC 9110 15.4).
  4045. EXPECT_TRUE(authorization.empty());
  4046. EXPECT_EQ("42", trace_id);
  4047. }
  4048. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  4049. auto result = GetThroughRedirectToDifferentPort(
  4050. [](const Request &, Response &res) {
  4051. res.set_content(std::string(2048, 'x'), "text/plain");
  4052. },
  4053. [](Client &cli) { cli.set_payload_max_length(1024); });
  4054. EXPECT_FALSE(result);
  4055. }
  4056. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  4057. auto result = GetThroughRedirectToDifferentPort(
  4058. [](const Request &req, Response &res) {
  4059. // Answer after a second, or once the client gives up.
  4060. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  4061. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  4062. }
  4063. res.set_content("late", "text/plain");
  4064. },
  4065. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  4066. ASSERT_FALSE(result);
  4067. EXPECT_EQ(Error::Read, result.error());
  4068. }
  4069. #ifdef CPPHTTPLIB_SSL_ENABLED
  4070. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  4071. auto result = GetThroughRedirectToDifferentPort(
  4072. [](const Request &, Response &res) {
  4073. res.status = StatusCode::Unauthorized_401;
  4074. res.set_header("WWW-Authenticate",
  4075. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  4076. },
  4077. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  4078. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  4079. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  4080. }
  4081. #endif
  4082. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  4083. Server svr;
  4084. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4085. // Port number that overflows int — should not crash
  4086. res.set_redirect("http://localhost:99999999999999999999/target");
  4087. });
  4088. auto port = svr.bind_to_any_port(HOST);
  4089. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4090. auto se = detail::scope_exit([&] {
  4091. svr.stop();
  4092. thread.join();
  4093. ASSERT_FALSE(svr.is_running());
  4094. });
  4095. svr.wait_until_ready();
  4096. Client cli(HOST, port);
  4097. cli.set_follow_location(true);
  4098. auto res = cli.Get("/redir");
  4099. // Should fail gracefully, not crash (no valid response due to bad port)
  4100. EXPECT_FALSE(res);
  4101. }
  4102. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  4103. Server svr;
  4104. auto port = svr.bind_to_any_port(HOST);
  4105. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  4106. // The server's own port followed by junk must not be followed
  4107. res.set_redirect("http://" + std::string(HOST) + ":" +
  4108. std::to_string(port) + "junk/target");
  4109. });
  4110. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4111. res.set_content("target", "text/plain");
  4112. });
  4113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4114. auto se = detail::scope_exit([&] {
  4115. svr.stop();
  4116. thread.join();
  4117. ASSERT_FALSE(svr.is_running());
  4118. });
  4119. svr.wait_until_ready();
  4120. Client cli(HOST, port);
  4121. cli.set_follow_location(true);
  4122. auto res = cli.Get("/redir");
  4123. EXPECT_FALSE(res);
  4124. }
  4125. TEST(RedirectToDifferentPort, BareHostAndPortIsNotFollowed) {
  4126. Server target_svr;
  4127. std::atomic<int> target_hits{0};
  4128. target_svr.Get("/", [&](const Request & /*req*/, Response &res) {
  4129. target_hits++;
  4130. res.set_content("target", "text/plain");
  4131. });
  4132. target_svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4133. res.set_content("target", "text/plain");
  4134. });
  4135. int target_port = 0;
  4136. auto target_thread = std::thread([&]() {
  4137. target_port = target_svr.bind_to_any_port("127.0.0.1");
  4138. target_svr.listen_after_bind();
  4139. });
  4140. Server origin_svr;
  4141. origin_svr.Get("/redir", [&](const Request &req, Response &res) {
  4142. res.set_redirect(req.get_param_value("to"));
  4143. });
  4144. int origin_port = 0;
  4145. auto origin_thread = std::thread([&]() {
  4146. origin_port = origin_svr.bind_to_any_port(HOST);
  4147. origin_svr.listen_after_bind();
  4148. });
  4149. auto se = detail::scope_exit([&] {
  4150. origin_svr.stop();
  4151. origin_thread.join();
  4152. target_svr.stop();
  4153. target_thread.join();
  4154. ASSERT_FALSE(origin_svr.is_running());
  4155. ASSERT_FALSE(target_svr.is_running());
  4156. });
  4157. target_svr.wait_until_ready();
  4158. origin_svr.wait_until_ready();
  4159. auto port = std::to_string(target_port);
  4160. for (const auto &to :
  4161. {"localhost:" + port, "127.0.0.1:" + port, "localhost:" + port + "/"}) {
  4162. Client cli(HOST, origin_port);
  4163. cli.set_follow_location(true);
  4164. auto res = cli.Get("/redir?to=" + encode_query_component(to));
  4165. EXPECT_FALSE(res) << to;
  4166. }
  4167. EXPECT_EQ(0, target_hits);
  4168. Client cli(HOST, origin_port);
  4169. cli.set_follow_location(true);
  4170. auto res = cli.Get("/redir?to=" +
  4171. encode_query_component("//127.0.0.1:" + port + "/target"));
  4172. ASSERT_TRUE(res) << to_string(res.error());
  4173. EXPECT_EQ(StatusCode::OK_200, res->status);
  4174. EXPECT_EQ("target", res->body);
  4175. }
  4176. TEST(RedirectTest, OtherStatusesWithLocationAreNotFollowed) {
  4177. Server svr;
  4178. std::atomic<bool> followed{false};
  4179. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  4180. res.status = StatusCode::NotModified_304;
  4181. res.set_header("Location", "/target");
  4182. });
  4183. svr.Get("/305", [](const Request & /*req*/, Response &res) {
  4184. res.status = StatusCode::UseProxy_305;
  4185. res.set_header("Location", "/target");
  4186. });
  4187. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  4188. followed = true;
  4189. res.set_content("target", "text/plain");
  4190. });
  4191. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4192. auto se = detail::scope_exit([&] {
  4193. svr.stop();
  4194. th.join();
  4195. ASSERT_FALSE(svr.is_running());
  4196. });
  4197. svr.wait_until_ready();
  4198. Client cli("localhost", PORT);
  4199. cli.set_follow_location(true);
  4200. auto res = cli.Get("/304");
  4201. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4202. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  4203. res = cli.Get("/305");
  4204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4205. EXPECT_EQ(StatusCode::UseProxy_305, res->status);
  4206. EXPECT_FALSE(followed);
  4207. }
  4208. TEST(RedirectFromPageWithContent, Redirect) {
  4209. Server svr;
  4210. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4211. res.set_content("___", "text/plain");
  4212. res.set_redirect("/2");
  4213. });
  4214. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  4215. res.set_content("Hello World!", "text/plain");
  4216. });
  4217. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  4218. auto se = detail::scope_exit([&] {
  4219. svr.stop();
  4220. th.join();
  4221. ASSERT_FALSE(svr.is_running());
  4222. });
  4223. svr.wait_until_ready();
  4224. {
  4225. Client cli("localhost", PORT);
  4226. cli.set_follow_location(true);
  4227. std::string body;
  4228. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4229. body.append(data, data_length);
  4230. return true;
  4231. });
  4232. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4233. EXPECT_EQ(StatusCode::OK_200, res->status);
  4234. EXPECT_EQ("Hello World!", body);
  4235. }
  4236. {
  4237. Client cli("localhost", PORT);
  4238. std::string body;
  4239. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4240. body.append(data, data_length);
  4241. return true;
  4242. });
  4243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4244. EXPECT_EQ(StatusCode::Found_302, res->status);
  4245. EXPECT_EQ("___", body);
  4246. }
  4247. }
  4248. // A server can close the connection after a request with "Connection: close"
  4249. // without repeating the option in its response (RFC 9112 Section 9.6), so the
  4250. // redirected request must go out on a new connection.
  4251. TEST(RedirectTest, NewConnectionAfterConnectionClose) {
  4252. #ifndef _WIN32
  4253. signal(SIGPIPE, SIG_IGN);
  4254. #endif
  4255. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  4256. default_socket_options(srv);
  4257. sockaddr_in addr{};
  4258. addr.sin_family = AF_INET;
  4259. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  4260. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  4261. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  4262. ASSERT_EQ(0, ::listen(srv, 2));
  4263. auto send_text = [](socket_t sock, const std::string &text) {
  4264. ::send(sock,
  4265. #ifdef _WIN32
  4266. static_cast<const char *>(text.c_str()),
  4267. static_cast<int>(text.size()),
  4268. #else
  4269. text.c_str(), text.size(),
  4270. #endif
  4271. 0);
  4272. };
  4273. auto reused = false;
  4274. auto server_thread = std::thread([&] {
  4275. char buf[4096];
  4276. auto first = ::accept(srv, nullptr, nullptr);
  4277. if (first == INVALID_SOCKET) { return; }
  4278. detail::set_socket_opt_time(first, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4279. ::recv(first, buf, sizeof(buf), 0);
  4280. send_text(
  4281. first,
  4282. "HTTP/1.1 302 Found\r\nLocation: /2\r\nContent-Length: 0\r\n\r\n");
  4283. auto next = first;
  4284. if (::recv(first, buf, sizeof(buf), 0) > 0) {
  4285. reused = true;
  4286. } else {
  4287. detail::close_socket(first);
  4288. next = ::accept(srv, nullptr, nullptr);
  4289. if (next == INVALID_SOCKET) { return; }
  4290. detail::set_socket_opt_time(next, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  4291. ::recv(next, buf, sizeof(buf), 0);
  4292. }
  4293. send_text(next, "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n"
  4294. "Connection: close\r\n\r\nok");
  4295. detail::close_socket(next);
  4296. });
  4297. Client cli("127.0.0.1", PORT + 2);
  4298. cli.set_follow_location(true);
  4299. cli.set_read_timeout(5, 0);
  4300. auto res = cli.Get("/1");
  4301. server_thread.join();
  4302. detail::close_socket(srv);
  4303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4304. EXPECT_EQ(StatusCode::OK_200, res->status);
  4305. EXPECT_EQ("ok", res->body);
  4306. EXPECT_FALSE(reused);
  4307. }
  4308. TEST(RedirectFromPageWithContentIP6, Redirect) {
  4309. Server svr;
  4310. auto port_str = std::to_string(PORT);
  4311. auto redirect_url = "http://[::1]:" + port_str + "/2";
  4312. auto expected_host = "[::1]:" + port_str;
  4313. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4314. res.set_content("___", "text/plain");
  4315. // res.set_redirect("/2");
  4316. res.set_redirect(redirect_url);
  4317. });
  4318. svr.Get("/2", [&](const Request &req, Response &res) {
  4319. auto host_header = req.headers.find("Host");
  4320. ASSERT_TRUE(host_header != req.headers.end());
  4321. EXPECT_EQ(expected_host, host_header->second);
  4322. res.set_content("Hello World!", "text/plain");
  4323. });
  4324. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  4325. auto se = detail::scope_exit([&] {
  4326. svr.stop();
  4327. th.join();
  4328. ASSERT_FALSE(svr.is_running());
  4329. });
  4330. // When IPV6 support isn't available svr.listen("::1", PORT) never
  4331. // actually starts anything, so the condition !svr.is_running() will
  4332. // always remain true, and the loop never stops.
  4333. // This basically counts how many milliseconds have passed since the
  4334. // call to svr.listen(), and if after 5 seconds nothing started yet
  4335. // aborts the test.
  4336. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  4337. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  4338. ASSERT_LT(milliseconds, 5000U);
  4339. }
  4340. {
  4341. Client cli("::1", PORT);
  4342. cli.set_follow_location(true);
  4343. std::string body;
  4344. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4345. body.append(data, data_length);
  4346. return true;
  4347. });
  4348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4349. EXPECT_EQ(StatusCode::OK_200, res->status);
  4350. EXPECT_EQ("Hello World!", body);
  4351. }
  4352. {
  4353. Client cli("::1", PORT);
  4354. std::string body;
  4355. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  4356. body.append(data, data_length);
  4357. return true;
  4358. });
  4359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4360. EXPECT_EQ(StatusCode::Found_302, res->status);
  4361. EXPECT_EQ("___", body);
  4362. }
  4363. }
  4364. TEST(PathUrlEncodeTest, PathUrlEncode) {
  4365. Server svr;
  4366. svr.Get("/foo", [](const Request &req, Response &res) {
  4367. auto a = req.params.find("a");
  4368. if (a != req.params.end()) {
  4369. res.set_content((*a).second, "text/plain");
  4370. res.status = StatusCode::OK_200;
  4371. } else {
  4372. res.status = StatusCode::BadRequest_400;
  4373. }
  4374. });
  4375. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4376. auto se = detail::scope_exit([&] {
  4377. svr.stop();
  4378. thread.join();
  4379. ASSERT_FALSE(svr.is_running());
  4380. });
  4381. svr.wait_until_ready();
  4382. {
  4383. Client cli(HOST, PORT);
  4384. cli.set_path_encode(false);
  4385. auto res = cli.Get("/foo?a=explicitly+encoded");
  4386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4387. EXPECT_EQ(StatusCode::OK_200, res->status);
  4388. // This expects it back with a space, as the `+` won't have been
  4389. // url-encoded, and server-side the params get decoded turning `+`
  4390. // into spaces.
  4391. EXPECT_EQ("explicitly encoded", res->body);
  4392. }
  4393. }
  4394. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  4395. // When path encoding is disabled the client must transmit the supplied
  4396. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  4397. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  4398. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  4399. // than a space (0x20). Assert on the raw wire target to catch this.
  4400. Server svr;
  4401. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4402. svr.Get("/foo", [&](const Request &req, Response &res) {
  4403. EXPECT_EQ(expected_target, req.target);
  4404. res.status = StatusCode::OK_200;
  4405. });
  4406. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4407. auto se = detail::scope_exit([&] {
  4408. svr.stop();
  4409. thread.join();
  4410. ASSERT_FALSE(svr.is_running());
  4411. });
  4412. svr.wait_until_ready();
  4413. {
  4414. Client cli(HOST, PORT);
  4415. cli.set_path_encode(false);
  4416. auto res = cli.Get(expected_target.c_str());
  4417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4418. EXPECT_EQ(StatusCode::OK_200, res->status);
  4419. }
  4420. }
  4421. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  4422. // `open_stream()` used to skip the path encoding that the buffered send
  4423. // path applies, so the same `path` produced different bytes in the request
  4424. // line depending on which API was used. Assert the two agree.
  4425. Server svr;
  4426. std::string target;
  4427. svr.Get(".*", [&](const Request &req, Response &res) {
  4428. target = req.target;
  4429. res.status = StatusCode::OK_200;
  4430. });
  4431. auto port = svr.bind_to_any_port(HOST);
  4432. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4433. auto se = detail::scope_exit([&] {
  4434. svr.stop();
  4435. thread.join();
  4436. ASSERT_FALSE(svr.is_running());
  4437. });
  4438. svr.wait_until_ready();
  4439. struct {
  4440. const char *path;
  4441. const char *expected;
  4442. } cases[] = {
  4443. {"/a b?x=1", "/a%20b?x=1"},
  4444. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  4445. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  4446. };
  4447. for (const auto &c : cases) {
  4448. Client cli(HOST, port);
  4449. target.clear();
  4450. auto res = cli.Get(c.path);
  4451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4452. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  4453. auto buffered_target = target;
  4454. target.clear();
  4455. auto handle = cli.open_stream("GET", c.path);
  4456. EXPECT_TRUE(handle.is_valid())
  4457. << "streaming path: " << c.path << ", " << to_string(handle.error);
  4458. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  4459. }
  4460. }
  4461. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  4462. // The `set_path_encode(false)` contract — transmit the supplied target
  4463. // verbatim — must hold for the streaming API too.
  4464. Server svr;
  4465. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  4466. std::string target;
  4467. svr.Get("/foo", [&](const Request &req, Response &res) {
  4468. target = req.target;
  4469. res.status = StatusCode::OK_200;
  4470. });
  4471. auto port = svr.bind_to_any_port(HOST);
  4472. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4473. auto se = detail::scope_exit([&] {
  4474. svr.stop();
  4475. thread.join();
  4476. ASSERT_FALSE(svr.is_running());
  4477. });
  4478. svr.wait_until_ready();
  4479. {
  4480. Client cli(HOST, port);
  4481. cli.set_path_encode(false);
  4482. auto handle = cli.open_stream("GET", expected_target);
  4483. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4484. EXPECT_EQ(expected_target, target);
  4485. }
  4486. }
  4487. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  4488. // With path encoding enabled a CR/LF in the target is percent-encoded
  4489. // rather than rejected, matching the buffered send path. The CR/LF guard in
  4490. // write_request_line still backstops `set_path_encode(false)`, which is
  4491. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  4492. Server svr;
  4493. // Captured before routing: the decoded path contains a newline, which a
  4494. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  4495. std::string target;
  4496. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4497. target = req.target;
  4498. res.status = StatusCode::OK_200;
  4499. return Server::HandlerResponse::Handled;
  4500. });
  4501. auto port = svr.bind_to_any_port(HOST);
  4502. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4503. auto se = detail::scope_exit([&] {
  4504. svr.stop();
  4505. thread.join();
  4506. ASSERT_FALSE(svr.is_running());
  4507. });
  4508. svr.wait_until_ready();
  4509. {
  4510. Client cli(HOST, port);
  4511. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4512. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  4513. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  4514. }
  4515. }
  4516. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  4517. // Every control character is percent-encoded, not just CR/LF, so the target
  4518. // passes the request-target check in write_request_line.
  4519. Server svr;
  4520. std::string target;
  4521. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  4522. target = req.target;
  4523. res.status = StatusCode::OK_200;
  4524. return Server::HandlerResponse::Handled;
  4525. });
  4526. auto port = svr.bind_to_any_port(HOST);
  4527. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4528. auto se = detail::scope_exit([&] {
  4529. svr.stop();
  4530. thread.join();
  4531. ASSERT_FALSE(svr.is_running());
  4532. });
  4533. svr.wait_until_ready();
  4534. {
  4535. Client cli(HOST, port);
  4536. auto res = cli.Get("/a\tb\x1b\x7f");
  4537. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4538. EXPECT_EQ("/a%09b%1B%7F", target);
  4539. }
  4540. }
  4541. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  4542. // Nothing may reach the wire: a raw CR/LF target would split the request
  4543. // line and inject headers.
  4544. Server svr;
  4545. // Pre-routing so that "not called" means nothing reached the server at all,
  4546. // rather than merely failing to match a handler pattern.
  4547. auto handler_called = false;
  4548. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  4549. handler_called = true;
  4550. res.status = StatusCode::OK_200;
  4551. return Server::HandlerResponse::Handled;
  4552. });
  4553. auto port = svr.bind_to_any_port(HOST);
  4554. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4555. auto se = detail::scope_exit([&] {
  4556. svr.stop();
  4557. thread.join();
  4558. ASSERT_FALSE(svr.is_running());
  4559. });
  4560. svr.wait_until_ready();
  4561. {
  4562. Client cli(HOST, port);
  4563. cli.set_path_encode(false);
  4564. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  4565. EXPECT_FALSE(handle.is_valid());
  4566. EXPECT_EQ(Error::Write, handle.error);
  4567. EXPECT_FALSE(handler_called);
  4568. }
  4569. }
  4570. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  4571. // Which of the two branches runs is decided by whether the query component
  4572. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  4573. // an empty query and must still fall back to building one from
  4574. // `req.params`, while a non-empty query must win over `req.params`.
  4575. Server svr;
  4576. std::string target;
  4577. svr.Get("/foo", [&](const Request &req, Response &res) {
  4578. target = req.target;
  4579. res.status = StatusCode::OK_200;
  4580. });
  4581. auto port = svr.bind_to_any_port(HOST);
  4582. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  4583. auto se = detail::scope_exit([&] {
  4584. svr.stop();
  4585. thread.join();
  4586. ASSERT_FALSE(svr.is_running());
  4587. });
  4588. svr.wait_until_ready();
  4589. {
  4590. // Trailing `?` -> empty query component -> `req.params` is used.
  4591. Client cli(HOST, port);
  4592. Request req;
  4593. req.method = "GET";
  4594. req.path = "/foo?";
  4595. req.params.emplace("a", "1");
  4596. target.clear();
  4597. auto res = cli.send(req);
  4598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4599. EXPECT_EQ("/foo?a=1", target);
  4600. }
  4601. {
  4602. // Non-empty query in `req.path` -> `req.params` is not appended.
  4603. Client cli(HOST, port);
  4604. Request req;
  4605. req.method = "GET";
  4606. req.path = "/foo?b=2";
  4607. req.params.emplace("a", "1");
  4608. target.clear();
  4609. auto res = cli.send(req);
  4610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4611. EXPECT_EQ("/foo?b=2", target);
  4612. }
  4613. }
  4614. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  4615. Server svr;
  4616. svr.Get("/", [](const Request &req, Response &) {
  4617. EXPECT_EQ("\x0A", req.get_param_value("something"));
  4618. });
  4619. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4620. auto se = detail::scope_exit([&] {
  4621. svr.stop();
  4622. thread.join();
  4623. ASSERT_FALSE(svr.is_running());
  4624. });
  4625. svr.wait_until_ready();
  4626. {
  4627. Client cli(HOST, PORT);
  4628. cli.set_path_encode(false);
  4629. auto res = cli.Get("/?something=%0A");
  4630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4631. EXPECT_EQ(StatusCode::OK_200, res->status);
  4632. }
  4633. }
  4634. TEST(BindServerTest, BindDualStack) {
  4635. Server svr;
  4636. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  4637. res.set_content("Hello World!", "text/plain");
  4638. });
  4639. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  4640. auto se = detail::scope_exit([&] {
  4641. svr.stop();
  4642. thread.join();
  4643. ASSERT_FALSE(svr.is_running());
  4644. });
  4645. svr.wait_until_ready();
  4646. {
  4647. Client cli("127.0.0.1", PORT);
  4648. auto res = cli.Get("/1");
  4649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4650. EXPECT_EQ(StatusCode::OK_200, res->status);
  4651. EXPECT_EQ("Hello World!", res->body);
  4652. }
  4653. {
  4654. Client cli("::1", PORT);
  4655. auto res = cli.Get("/1");
  4656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4657. EXPECT_EQ(StatusCode::OK_200, res->status);
  4658. EXPECT_EQ("Hello World!", res->body);
  4659. }
  4660. }
  4661. TEST(BindServerTest, BindAndListenSeparately) {
  4662. Server svr;
  4663. int port = svr.bind_to_any_port("0.0.0.0");
  4664. ASSERT_TRUE(svr.is_valid());
  4665. ASSERT_TRUE(port > 0);
  4666. svr.stop();
  4667. }
  4668. // Reports whether anything is still listening on a loopback port. A plain
  4669. // connect() is used instead of a Client request because a socket left bound by
  4670. // mistake accepts the connection into its backlog and never answers, which
  4671. // would hang the test instead of failing it.
  4672. static bool is_loopback_port_accepting(int port) {
  4673. sockaddr_in addr{};
  4674. addr.sin_family = AF_INET;
  4675. addr.sin_port = htons(static_cast<uint16_t>(port));
  4676. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  4677. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  4678. EXPECT_NE(sock, INVALID_SOCKET);
  4679. if (sock == INVALID_SOCKET) { return false; }
  4680. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  4681. static_cast<socklen_t>(sizeof(addr)));
  4682. detail::close_socket(sock);
  4683. return ret == 0;
  4684. }
  4685. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  4686. Server svr;
  4687. auto port = svr.bind_to_any_port("127.0.0.1");
  4688. ASSERT_TRUE(port > 0);
  4689. svr.stop();
  4690. // bind_to_any_port() already called listen(2), so until stop() closed the
  4691. // descriptor the port kept accepting connections into the backlog. ASSERT
  4692. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4693. // below blocks forever in the accept loop.
  4694. ASSERT_FALSE(is_loopback_port_accepting(port));
  4695. // Nothing is left to accept on, so listen_after_bind() must report failure
  4696. // instead of returning success without ever serving.
  4697. EXPECT_FALSE(svr.listen_after_bind());
  4698. // The failed listen marks the server decommissioned, so a waiter returns
  4699. // instead of spinning forever.
  4700. svr.wait_until_ready();
  4701. }
  4702. #ifdef CPPHTTPLIB_SSL_ENABLED
  4703. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4704. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4705. CLIENT_CA_CERT_DIR);
  4706. int port = svr.bind_to_any_port("0.0.0.0");
  4707. ASSERT_TRUE(svr.is_valid());
  4708. ASSERT_TRUE(port > 0);
  4709. svr.stop();
  4710. }
  4711. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4712. // or a rejected CustomRoute() registration would not stop the server binding.
  4713. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4714. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4715. CLIENT_CA_CERT_DIR);
  4716. ASSERT_TRUE(svr.is_valid());
  4717. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4718. EXPECT_FALSE(svr.is_valid());
  4719. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4720. }
  4721. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4722. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4723. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4724. int port = svr.bind_to_any_port("0.0.0.0");
  4725. ASSERT_TRUE(svr.is_valid());
  4726. ASSERT_TRUE(port > 0);
  4727. svr.stop();
  4728. }
  4729. TEST(BindServerTest, UpdateCertsPem) {
  4730. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4731. int port = svr.bind_to_any_port("0.0.0.0");
  4732. ASSERT_TRUE(svr.is_valid());
  4733. ASSERT_TRUE(port > 0);
  4734. // Read PEM files
  4735. std::string cert_pem, key_pem, ca_pem;
  4736. read_file(SERVER_CERT_FILE, cert_pem);
  4737. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4738. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4739. // Update server certificates using PEM API
  4740. ASSERT_TRUE(
  4741. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4742. ASSERT_TRUE(svr.is_valid());
  4743. svr.stop();
  4744. }
  4745. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4746. // Start server with client CA (enables client auth)
  4747. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4748. ASSERT_TRUE(svr.is_valid());
  4749. bool handler_called = false;
  4750. svr.Get("/test", [&](const Request &req, Response &res) {
  4751. handler_called = true;
  4752. // Verify client certificate is present
  4753. auto cert = req.peer_cert();
  4754. EXPECT_TRUE(static_cast<bool>(cert));
  4755. res.set_content("ok", "text/plain");
  4756. });
  4757. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4758. auto se = detail::scope_exit([&] {
  4759. svr.stop();
  4760. t.join();
  4761. ASSERT_FALSE(svr.is_running());
  4762. });
  4763. svr.wait_until_ready();
  4764. // Read PEM files
  4765. std::string cert_pem, key_pem, ca_pem;
  4766. read_file(SERVER_CERT_FILE, cert_pem);
  4767. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4768. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4769. // Update server certificates and client CA using PEM API while server running
  4770. ASSERT_TRUE(
  4771. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4772. // Connect with client certificate
  4773. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4774. cli.enable_server_certificate_verification(false);
  4775. cli.set_connection_timeout(30);
  4776. auto res = cli.Get("/test");
  4777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4778. ASSERT_EQ(StatusCode::OK_200, res->status);
  4779. ASSERT_TRUE(handler_called);
  4780. EXPECT_EQ("ok", res->body);
  4781. }
  4782. // Puts a CA that did not sign the client's certificate in the old one's place.
  4783. static bool replace_client_ca(SSLServer &svr) {
  4784. std::string cert_pem, key_pem, ca_pem;
  4785. read_file(SERVER_CERT_FILE, cert_pem);
  4786. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4787. read_file(SERVER_CERT2_FILE, ca_pem);
  4788. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4789. ca_pem.c_str());
  4790. }
  4791. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4792. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4793. ASSERT_TRUE(svr.is_valid());
  4794. svr.Get("/test", [](const Request &, Response &res) {
  4795. res.set_content("ok", "text/plain");
  4796. });
  4797. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4798. auto se = detail::scope_exit([&] {
  4799. svr.stop();
  4800. t.join();
  4801. ASSERT_FALSE(svr.is_running());
  4802. });
  4803. svr.wait_until_ready();
  4804. auto get = [] {
  4805. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4806. cli.enable_server_certificate_verification(false);
  4807. return cli.Get("/test");
  4808. };
  4809. ASSERT_TRUE(get());
  4810. ASSERT_TRUE(replace_client_ca(svr));
  4811. EXPECT_FALSE(get());
  4812. }
  4813. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4814. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4815. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4816. ASSERT_TRUE(svr.is_valid());
  4817. tls::set_verify_callback(svr.tls_context(),
  4818. [](const tls::VerifyContext &) -> bool {
  4819. throw std::runtime_error("verify");
  4820. });
  4821. svr.Get("/test", [](const Request &, Response &res) {
  4822. res.set_content("ok", "text/plain");
  4823. });
  4824. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4825. auto se = detail::scope_exit([&] {
  4826. svr.stop();
  4827. t.join();
  4828. ASSERT_FALSE(svr.is_running());
  4829. });
  4830. svr.wait_until_ready();
  4831. auto get = [] {
  4832. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4833. cli.enable_server_certificate_verification(false);
  4834. return cli.Get("/test");
  4835. };
  4836. EXPECT_FALSE(get());
  4837. // The handshake is over, so an update does not wait for it.
  4838. std::string cert_pem, key_pem;
  4839. read_file(SERVER_CERT_FILE, cert_pem);
  4840. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4841. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4842. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4843. return v.preverify_ok;
  4844. });
  4845. auto res = get();
  4846. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4847. EXPECT_EQ("ok", res->body);
  4848. }
  4849. #endif
  4850. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4851. // Sends each request over a new connection with a client certificate,
  4852. // resuming the session of the one before when there is one.
  4853. class ResumingClient {
  4854. public:
  4855. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4856. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4857. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4858. SSL_FILETYPE_PEM);
  4859. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4860. // callback, not through SSL_get1_session().
  4861. SSL_CTX_set_app_data(ctx_, this);
  4862. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4863. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4864. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4865. auto self = static_cast<ResumingClient *>(
  4866. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4867. SSL_SESSION_free(self->session_);
  4868. self->session_ = session;
  4869. return 1; // Keeps the reference
  4870. });
  4871. }
  4872. ~ResumingClient() {
  4873. SSL_SESSION_free(session_);
  4874. SSL_CTX_free(ctx_);
  4875. }
  4876. // Tells whether the request was answered.
  4877. bool get() {
  4878. auto error = Error::Success;
  4879. auto sock = detail::create_client_socket(
  4880. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4881. /*connection_timeout_sec=*/5, 0,
  4882. /*read_timeout_sec=*/5, 0,
  4883. /*write_timeout_sec=*/5, 0, std::string(), error);
  4884. if (sock == INVALID_SOCKET) { return false; }
  4885. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4886. auto ssl = SSL_new(ctx_);
  4887. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4888. SSL_set_fd(ssl, static_cast<int>(sock));
  4889. if (session_) { SSL_set_session(ssl, session_); }
  4890. if (SSL_connect(ssl) != 1) { return false; }
  4891. reused_ = SSL_session_reused(ssl) == 1;
  4892. // Reading the response also takes in a TLS 1.3 session ticket.
  4893. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4894. "Connection: close\r\n\r\n";
  4895. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4896. std::string res;
  4897. char buf[256];
  4898. int n;
  4899. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4900. res.append(buf, static_cast<size_t>(n));
  4901. }
  4902. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4903. SSL_shutdown(ssl);
  4904. return res.find("200 OK") != std::string::npos;
  4905. }
  4906. // Whether the last connection resumed a session
  4907. bool reused() const { return reused_; }
  4908. private:
  4909. SSL_CTX *ctx_;
  4910. SSL_SESSION *session_ = nullptr;
  4911. bool reused_ = false;
  4912. };
  4913. // A client that resumes its session gets through, but not once the client CA
  4914. // has changed, as a resumed session does not show the certificate again.
  4915. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4916. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4917. ASSERT_TRUE(svr.is_valid());
  4918. svr.Get("/test", [](const Request &, Response &res) {
  4919. res.set_content("ok", "text/plain");
  4920. });
  4921. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4922. auto se = detail::scope_exit([&] {
  4923. svr.stop();
  4924. t.join();
  4925. ASSERT_FALSE(svr.is_running());
  4926. });
  4927. svr.wait_until_ready();
  4928. ResumingClient cli;
  4929. ASSERT_TRUE(cli.get());
  4930. ASSERT_TRUE(cli.get());
  4931. EXPECT_TRUE(cli.reused());
  4932. ASSERT_TRUE(replace_client_ca(svr));
  4933. EXPECT_FALSE(cli.get());
  4934. }
  4935. // A resumed session does not show the certificate again, so the server does
  4936. // not resume one with a verify callback to run on it.
  4937. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4938. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4939. ASSERT_TRUE(svr.is_valid());
  4940. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4941. return v.preverify_ok;
  4942. });
  4943. svr.Get("/test", [](const Request &, Response &res) {
  4944. res.set_content("ok", "text/plain");
  4945. });
  4946. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4947. auto se = detail::scope_exit([&] {
  4948. svr.stop();
  4949. t.join();
  4950. ASSERT_FALSE(svr.is_running());
  4951. });
  4952. svr.wait_until_ready();
  4953. ResumingClient cli;
  4954. ASSERT_TRUE(cli.get());
  4955. ASSERT_TRUE(cli.get());
  4956. EXPECT_FALSE(cli.reused());
  4957. }
  4958. #endif
  4959. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4960. // wolfSSL shares its session cache between contexts, so a resumed session
  4961. // could carry a client certificate checked against another server's CA, or
  4962. // against a client CA since replaced.
  4963. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4964. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4965. ASSERT_TRUE(svr.is_valid());
  4966. // Trusts a CA that did not sign the client's certificate.
  4967. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4968. ASSERT_TRUE(other.is_valid());
  4969. for (auto s : {&svr, &other}) {
  4970. s->Get("/test", [](const Request &, Response &res) {
  4971. res.set_content("ok", "text/plain");
  4972. });
  4973. }
  4974. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4975. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4976. auto se = detail::scope_exit([&] {
  4977. other.stop();
  4978. svr.stop();
  4979. t2.join();
  4980. t.join();
  4981. });
  4982. svr.wait_until_ready();
  4983. other.wait_until_ready();
  4984. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4985. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4986. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4987. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4988. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4989. ASSERT_EQ(WOLFSSL_SUCCESS,
  4990. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4991. WOLFSSL_FILETYPE_PEM));
  4992. WOLFSSL_SESSION *session = nullptr;
  4993. auto session_se = detail::scope_exit([&] {
  4994. if (session) { wolfSSL_SESSION_free(session); }
  4995. });
  4996. // A request over a new connection, resuming `session` when there is one and
  4997. // keeping the connection's own in its place. Tells whether it was answered.
  4998. auto get = [&](int port) {
  4999. auto error = Error::Success;
  5000. auto sock = detail::create_client_socket(
  5001. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  5002. /*connection_timeout_sec=*/5, 0,
  5003. /*read_timeout_sec=*/5, 0,
  5004. /*write_timeout_sec=*/5, 0, std::string(), error);
  5005. if (sock == INVALID_SOCKET) { return false; }
  5006. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  5007. auto ssl = wolfSSL_new(ctx);
  5008. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  5009. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  5010. if (session) { wolfSSL_set_session(ssl, session); }
  5011. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  5012. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  5013. "Connection: close\r\n\r\n";
  5014. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  5015. std::string res;
  5016. char buf[256];
  5017. int n;
  5018. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  5019. res.append(buf, static_cast<size_t>(n));
  5020. }
  5021. wolfSSL_shutdown(ssl);
  5022. if (session) { wolfSSL_SESSION_free(session); }
  5023. session = wolfSSL_get1_session(ssl);
  5024. return res.find("200 OK") != std::string::npos;
  5025. };
  5026. ASSERT_TRUE(get(PORT));
  5027. EXPECT_FALSE(get(PORT + 1));
  5028. ASSERT_TRUE(get(PORT));
  5029. ASSERT_TRUE(replace_client_ca(svr));
  5030. EXPECT_FALSE(get(PORT));
  5031. }
  5032. #endif
  5033. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  5034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5035. ASSERT_TRUE(svr.is_valid());
  5036. // Keep-alive parking would wait for the ClientHello without a handshake.
  5037. svr.set_keep_alive_parking(false);
  5038. svr.Get("/test", [](const Request &, Response &res) {
  5039. res.set_content("ok", "text/plain");
  5040. });
  5041. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5042. auto se = detail::scope_exit([&] {
  5043. svr.stop();
  5044. t.join();
  5045. ASSERT_FALSE(svr.is_running());
  5046. });
  5047. svr.wait_until_ready();
  5048. // A connection that sends no ClientHello keeps its handshake in progress,
  5049. // once the server has had a moment to start it.
  5050. auto error = Error::Success;
  5051. auto sock = detail::create_client_socket(
  5052. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5053. /*connection_timeout_sec=*/5, 0,
  5054. /*read_timeout_sec=*/5, 0,
  5055. /*write_timeout_sec=*/5, 0, std::string(), error);
  5056. ASSERT_NE(INVALID_SOCKET, sock);
  5057. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  5058. std::string cert_pem, key_pem;
  5059. read_file(SERVER_CERT_FILE, cert_pem);
  5060. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  5061. auto update = std::async(std::launch::async, [&]() {
  5062. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  5063. });
  5064. EXPECT_EQ(std::future_status::timeout,
  5065. update.wait_for(std::chrono::milliseconds(200)));
  5066. detail::close_socket(sock);
  5067. EXPECT_TRUE(update.get());
  5068. SSLClient cli(HOST, PORT);
  5069. cli.enable_server_certificate_verification(false);
  5070. auto res = cli.Get("/test");
  5071. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5072. EXPECT_EQ(StatusCode::OK_200, res->status);
  5073. }
  5074. TEST(SSLClientServerTest, StopDoesNotWaitForHandshakeInProgress) {
  5075. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5076. ASSERT_TRUE(svr.is_valid());
  5077. // Keep-alive parking would wait for the ClientHello without a handshake.
  5078. svr.set_keep_alive_parking(false);
  5079. svr.set_read_timeout(10, 0);
  5080. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  5081. auto se = detail::scope_exit([&] {
  5082. svr.stop();
  5083. if (t.joinable()) { t.join(); }
  5084. });
  5085. svr.wait_until_ready();
  5086. // A connection that sends no ClientHello keeps its handshake in progress,
  5087. // once the server has had a moment to start it.
  5088. auto error = Error::Success;
  5089. auto sock = detail::create_client_socket(
  5090. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  5091. /*connection_timeout_sec=*/5, 0,
  5092. /*read_timeout_sec=*/5, 0,
  5093. /*write_timeout_sec=*/5, 0, std::string(), error);
  5094. ASSERT_NE(INVALID_SOCKET, sock);
  5095. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  5096. auto start = std::chrono::steady_clock::now();
  5097. svr.stop();
  5098. t.join();
  5099. auto elapsed = std::chrono::steady_clock::now() - start;
  5100. detail::close_socket(sock);
  5101. EXPECT_LT(elapsed, std::chrono::seconds(3));
  5102. }
  5103. #endif
  5104. TEST(ErrorHandlerTest, ContentLength) {
  5105. Server svr;
  5106. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5107. res.status = StatusCode::OK_200;
  5108. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5109. "text/html"); // <= Content-Length still 13
  5110. });
  5111. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5112. res.set_content("Hello World!\n", "text/plain");
  5113. res.status = 524;
  5114. });
  5115. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5116. auto se = detail::scope_exit([&] {
  5117. svr.stop();
  5118. thread.join();
  5119. ASSERT_FALSE(svr.is_running());
  5120. });
  5121. svr.wait_until_ready();
  5122. {
  5123. Client cli(HOST, PORT);
  5124. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5126. EXPECT_EQ(StatusCode::OK_200, res->status);
  5127. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5128. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5129. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5130. }
  5131. }
  5132. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5133. TEST(ExceptionTest, WithoutExceptionHandler) {
  5134. Server svr;
  5135. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  5136. throw std::runtime_error("exception...");
  5137. });
  5138. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  5139. throw std::runtime_error("exception\r\n...");
  5140. });
  5141. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  5142. auto se = detail::scope_exit([&] {
  5143. svr.stop();
  5144. listen_thread.join();
  5145. ASSERT_FALSE(svr.is_running());
  5146. });
  5147. svr.wait_until_ready();
  5148. Client cli("localhost", PORT);
  5149. {
  5150. auto res = cli.Get("/exception");
  5151. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5152. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5153. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  5154. }
  5155. {
  5156. auto res = cli.Get("/unknown");
  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. TEST(ExceptionTest, WithExceptionHandler) {
  5163. Server svr;
  5164. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  5165. std::exception_ptr ep) {
  5166. EXPECT_FALSE(ep == nullptr);
  5167. try {
  5168. std::rethrow_exception(ep);
  5169. } catch (std::exception &e) {
  5170. EXPECT_EQ("abc", std::string(e.what()));
  5171. } catch (...) {}
  5172. res.status = StatusCode::InternalServerError_500;
  5173. res.set_content("abcdefghijklmnopqrstuvwxyz",
  5174. "text/html"); // <= Content-Length still 13 at this point
  5175. });
  5176. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5177. res.set_content("Hello World!\n", "text/plain");
  5178. throw std::runtime_error("abc");
  5179. });
  5180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5181. auto se = detail::scope_exit([&] {
  5182. svr.stop();
  5183. thread.join();
  5184. ASSERT_FALSE(svr.is_running());
  5185. });
  5186. svr.wait_until_ready();
  5187. for (size_t i = 0; i < 10; i++) {
  5188. Client cli(HOST, PORT);
  5189. for (size_t j = 0; j < 100; j++) {
  5190. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5192. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5193. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5194. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5195. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5196. }
  5197. cli.set_keep_alive(true);
  5198. for (size_t j = 0; j < 100; j++) {
  5199. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5202. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5203. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  5204. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  5205. }
  5206. }
  5207. }
  5208. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  5209. Server svr;
  5210. svr.set_exception_handler(
  5211. [](const Request &, Response &res, std::exception_ptr) {
  5212. res.set_content("oops", "text/plain");
  5213. });
  5214. svr.Get("/throw", [](const Request &, Response &) {
  5215. throw std::runtime_error("throw");
  5216. });
  5217. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  5218. res.status = StatusCode::Created_201;
  5219. throw std::runtime_error("created-then-throw");
  5220. });
  5221. auto port = svr.bind_to_any_port(HOST);
  5222. ASSERT_GT(port, 0);
  5223. thread t = thread([&] { svr.listen_after_bind(); });
  5224. auto se = detail::scope_exit([&] {
  5225. svr.stop();
  5226. t.join();
  5227. ASSERT_FALSE(svr.is_running());
  5228. });
  5229. svr.wait_until_ready();
  5230. Client cli(HOST, port);
  5231. for (auto path : {"/throw", "/created-then-throw"}) {
  5232. auto res = cli.Get(path);
  5233. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  5234. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  5235. }
  5236. }
  5237. TEST(ExceptionTest, AndErrorHandler) {
  5238. Server svr;
  5239. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5240. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  5241. });
  5242. svr.set_exception_handler(
  5243. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  5244. EXPECT_FALSE(ep == nullptr);
  5245. try {
  5246. std::rethrow_exception(ep);
  5247. } catch (std::exception &e) {
  5248. res.set_content(e.what(), "text/html");
  5249. } catch (...) {}
  5250. res.status = StatusCode::InternalServerError_500;
  5251. });
  5252. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  5253. throw std::runtime_error("EXCEPTION");
  5254. });
  5255. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  5256. res.set_content("ERROR", "text/html");
  5257. res.status = StatusCode::InternalServerError_500;
  5258. });
  5259. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5260. auto se = detail::scope_exit([&] {
  5261. svr.stop();
  5262. thread.join();
  5263. ASSERT_FALSE(svr.is_running());
  5264. });
  5265. svr.wait_until_ready();
  5266. Client cli(HOST, PORT);
  5267. {
  5268. auto res = cli.Get("/exception");
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5271. EXPECT_EQ("EXCEPTION", res->body);
  5272. }
  5273. {
  5274. auto res = cli.Get("/error");
  5275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5276. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  5277. EXPECT_EQ("ERROR", res->body);
  5278. }
  5279. {
  5280. auto res = cli.Get("/invalid");
  5281. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5282. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5283. EXPECT_EQ("NOT_FOUND", res->body);
  5284. }
  5285. }
  5286. #endif
  5287. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5288. // An exception from a user callback outside process_request()'s try/catch
  5289. // used to unwind into the task queue - which does not catch - and terminate
  5290. // the process. Each test below runs the server on a single worker thread: a
  5291. // guard that catches the exception but still loses the thread would otherwise
  5292. // be hidden by a spare worker serving the follow-up request. Note that a
  5293. // regression here aborts the whole test binary rather than failing one test.
  5294. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  5295. Server svr;
  5296. svr.new_task_queue = [] { return new ThreadPool(1); };
  5297. std::atomic<int> reported{0};
  5298. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5299. if (err == Error::UserCallbackException) { reported++; }
  5300. });
  5301. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5302. res.set_content_provider(
  5303. 1024, "text/plain",
  5304. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5305. sink.write("hello", 5);
  5306. throw std::runtime_error("from the content provider");
  5307. });
  5308. });
  5309. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5310. res.set_content("ok", "text/plain");
  5311. });
  5312. auto port = svr.bind_to_any_port(HOST);
  5313. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5314. auto se = detail::scope_exit([&] {
  5315. svr.stop();
  5316. listen_thread.join();
  5317. ASSERT_FALSE(svr.is_running());
  5318. });
  5319. svr.wait_until_ready();
  5320. {
  5321. Client cli(HOST, port);
  5322. cli.set_read_timeout(5, 0);
  5323. EXPECT_FALSE(cli.Get("/throw"));
  5324. }
  5325. EXPECT_TRUE(svr.is_running());
  5326. EXPECT_EQ(1, reported.load());
  5327. // A request on a fresh connection is still served.
  5328. {
  5329. Client cli(HOST, port);
  5330. auto res = cli.Get("/ok");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. EXPECT_EQ(StatusCode::OK_200, res->status);
  5333. EXPECT_EQ("ok", res->body);
  5334. }
  5335. }
  5336. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  5337. Server svr;
  5338. svr.new_task_queue = [] { return new ThreadPool(1); };
  5339. std::atomic<bool> should_throw{true};
  5340. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5341. res.set_content("hi", "text/plain");
  5342. });
  5343. svr.set_post_routing_handler(
  5344. [&](const Request & /*req*/, Response & /*res*/) {
  5345. if (should_throw) {
  5346. throw std::runtime_error("from the post-routing handler");
  5347. }
  5348. });
  5349. auto port = svr.bind_to_any_port(HOST);
  5350. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5351. auto se = detail::scope_exit([&] {
  5352. svr.stop();
  5353. listen_thread.join();
  5354. ASSERT_FALSE(svr.is_running());
  5355. });
  5356. svr.wait_until_ready();
  5357. {
  5358. Client cli(HOST, port);
  5359. cli.set_read_timeout(5, 0);
  5360. EXPECT_FALSE(cli.Get("/hi"));
  5361. }
  5362. EXPECT_TRUE(svr.is_running());
  5363. should_throw = false;
  5364. {
  5365. Client cli(HOST, port);
  5366. auto res = cli.Get("/hi");
  5367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5368. EXPECT_EQ(StatusCode::OK_200, res->status);
  5369. EXPECT_EQ("hi", res->body);
  5370. }
  5371. }
  5372. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  5373. // The guard reports the caught exception through the error logger, which is
  5374. // a user callback too. A logger that throws has to be contained as well, or
  5375. // the process would terminate from inside the catch.
  5376. Server svr;
  5377. svr.new_task_queue = [] { return new ThreadPool(1); };
  5378. std::atomic<int> reported{0};
  5379. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5380. if (err == Error::UserCallbackException) {
  5381. reported++;
  5382. throw std::runtime_error("from the error logger");
  5383. }
  5384. });
  5385. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5386. res.set_content_provider(
  5387. 1024, "text/plain",
  5388. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5389. sink.write("hello", 5);
  5390. throw std::runtime_error("from the content provider");
  5391. });
  5392. });
  5393. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5394. res.set_content("ok", "text/plain");
  5395. });
  5396. auto port = svr.bind_to_any_port(HOST);
  5397. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5398. auto se = detail::scope_exit([&] {
  5399. svr.stop();
  5400. listen_thread.join();
  5401. ASSERT_FALSE(svr.is_running());
  5402. });
  5403. svr.wait_until_ready();
  5404. {
  5405. Client cli(HOST, port);
  5406. cli.set_read_timeout(5, 0);
  5407. EXPECT_FALSE(cli.Get("/throw"));
  5408. }
  5409. EXPECT_TRUE(svr.is_running());
  5410. EXPECT_EQ(1, reported.load());
  5411. {
  5412. Client cli(HOST, port);
  5413. auto res = cli.Get("/ok");
  5414. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5415. EXPECT_EQ(StatusCode::OK_200, res->status);
  5416. EXPECT_EQ("ok", res->body);
  5417. }
  5418. }
  5419. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  5420. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  5421. // so the exception unwinds through the ws::WebSocket object on its way to
  5422. // the guard. None of the HTTP cases above cross that.
  5423. Server svr;
  5424. svr.new_task_queue = [] { return new ThreadPool(1); };
  5425. std::atomic<int> reported{0};
  5426. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5427. if (err == Error::UserCallbackException) { reported++; }
  5428. });
  5429. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  5430. throw std::runtime_error("from the WebSocket handler");
  5431. });
  5432. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5433. res.set_content("ok", "text/plain");
  5434. });
  5435. auto port = svr.bind_to_any_port(HOST);
  5436. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5437. auto se = detail::scope_exit([&] {
  5438. svr.stop();
  5439. listen_thread.join();
  5440. ASSERT_FALSE(svr.is_running());
  5441. });
  5442. svr.wait_until_ready();
  5443. {
  5444. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  5445. "/ws");
  5446. auto res = client.connect();
  5447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5448. // The server dropped the connection instead of dying.
  5449. std::string msg;
  5450. EXPECT_FALSE(client.read(msg));
  5451. client.close();
  5452. }
  5453. EXPECT_TRUE(svr.is_running());
  5454. EXPECT_EQ(1, reported.load());
  5455. {
  5456. Client cli(HOST, port);
  5457. auto res = cli.Get("/ok");
  5458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5459. EXPECT_EQ(StatusCode::OK_200, res->status);
  5460. EXPECT_EQ("ok", res->body);
  5461. }
  5462. }
  5463. #ifdef CPPHTTPLIB_SSL_ENABLED
  5464. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  5465. // SSLServer::process_and_close_socket() is a separate overload with its own
  5466. // guard, so it is exercised on its own.
  5467. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5468. ASSERT_TRUE(svr.is_valid());
  5469. svr.new_task_queue = [] { return new ThreadPool(1); };
  5470. std::atomic<int> reported{0};
  5471. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  5472. if (err == Error::UserCallbackException) { reported++; }
  5473. });
  5474. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  5475. res.set_content_provider(
  5476. 1024, "text/plain",
  5477. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  5478. sink.write("hello", 5);
  5479. throw std::runtime_error("from the content provider");
  5480. });
  5481. });
  5482. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  5483. res.set_content("ok", "text/plain");
  5484. });
  5485. auto port = svr.bind_to_any_port(HOST);
  5486. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  5487. auto se = detail::scope_exit([&] {
  5488. svr.stop();
  5489. listen_thread.join();
  5490. ASSERT_FALSE(svr.is_running());
  5491. });
  5492. svr.wait_until_ready();
  5493. {
  5494. SSLClient cli(HOST, port);
  5495. cli.enable_server_certificate_verification(false);
  5496. cli.set_read_timeout(5, 0);
  5497. EXPECT_FALSE(cli.Get("/throw"));
  5498. }
  5499. EXPECT_TRUE(svr.is_running());
  5500. EXPECT_EQ(1, reported.load());
  5501. {
  5502. SSLClient cli(HOST, port);
  5503. cli.enable_server_certificate_verification(false);
  5504. auto res = cli.Get("/ok");
  5505. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5506. EXPECT_EQ(StatusCode::OK_200, res->status);
  5507. EXPECT_EQ("ok", res->body);
  5508. }
  5509. }
  5510. #endif
  5511. #endif
  5512. TEST(NoContentTest, ContentLength) {
  5513. Server svr;
  5514. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5515. res.status = StatusCode::NoContent_204;
  5516. });
  5517. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5518. auto se = detail::scope_exit([&] {
  5519. svr.stop();
  5520. thread.join();
  5521. ASSERT_FALSE(svr.is_running());
  5522. });
  5523. svr.wait_until_ready();
  5524. {
  5525. Client cli(HOST, PORT);
  5526. auto res = cli.Get("/hi");
  5527. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5528. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  5529. // RFC 9110 8.6: none in a 204 response
  5530. EXPECT_FALSE(res->has_header("Content-Length"));
  5531. }
  5532. }
  5533. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  5534. Server svr;
  5535. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  5536. res.set_header("Content-Length", "5");
  5537. res.set_content("hello world", "text/plain");
  5538. });
  5539. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  5540. // A body that reads as the last chunk, were it taken as chunked
  5541. res.set_header("Transfer-Encoding", "chunked");
  5542. res.set_content("0\r\n\r\n", "text/plain");
  5543. });
  5544. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  5545. res.set_header("Content-Length", "2");
  5546. res.set_content_provider(5, "text/plain",
  5547. [](size_t offset, size_t length, DataSink &sink) {
  5548. sink.write(&"hello"[offset], length);
  5549. return true;
  5550. });
  5551. });
  5552. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  5553. res.set_header("Content-Length", "1234");
  5554. });
  5555. thread t = thread([&] { svr.listen(HOST, PORT); });
  5556. auto se = detail::scope_exit([&] {
  5557. svr.stop();
  5558. t.join();
  5559. ASSERT_FALSE(svr.is_running());
  5560. });
  5561. svr.wait_until_ready();
  5562. Client cli(HOST, PORT);
  5563. cli.set_read_timeout(1, 0);
  5564. auto expect_body = [&](const Result &res, const std::string &body) {
  5565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5566. EXPECT_EQ(body, res->body);
  5567. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  5568. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5569. };
  5570. Headers identity{{"Accept-Encoding", ""}};
  5571. expect_body(cli.Get("/body", identity), "hello world");
  5572. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  5573. expect_body(cli.Get("/body",
  5574. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  5575. "he");
  5576. expect_body(cli.Get("/provider", identity), "hello");
  5577. expect_body(cli.Get("/empty", identity), "");
  5578. // A HEAD response may give the length of the body a GET would get.
  5579. auto res = cli.Head("/empty");
  5580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5581. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  5582. }
  5583. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  5584. Server svr;
  5585. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5586. res.set_content("short", "text/plain");
  5587. });
  5588. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  5589. res.body += " with a footer";
  5590. res.set_header("Transfer-Encoding", "chunked");
  5591. });
  5592. thread t = thread([&] { svr.listen(HOST, PORT); });
  5593. auto se = detail::scope_exit([&] {
  5594. svr.stop();
  5595. t.join();
  5596. ASSERT_FALSE(svr.is_running());
  5597. });
  5598. svr.wait_until_ready();
  5599. Client cli(HOST, PORT);
  5600. cli.set_read_timeout(1, 0);
  5601. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  5602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5603. EXPECT_EQ("short with a footer", res->body);
  5604. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  5605. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  5606. }
  5607. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  5608. Server svr;
  5609. svr.Get("/", [](const Request & /*req*/, Response &res) {
  5610. res.set_header("Content-Length", "3");
  5611. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  5612. sink.write("abc", 3);
  5613. sink.done();
  5614. return true;
  5615. });
  5616. });
  5617. thread t = thread([&] { svr.listen(HOST, PORT); });
  5618. auto se = detail::scope_exit([&] {
  5619. svr.stop();
  5620. t.join();
  5621. ASSERT_FALSE(svr.is_running());
  5622. });
  5623. svr.wait_until_ready();
  5624. Client cli(HOST, PORT);
  5625. cli.set_keep_alive(true);
  5626. auto res = cli.Get("/");
  5627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5628. EXPECT_EQ("abc", res->body);
  5629. EXPECT_FALSE(res->has_header("Content-Length"));
  5630. EXPECT_EQ("close", res->get_header_value("Connection"));
  5631. EXPECT_FALSE(res->has_header("Keep-Alive"));
  5632. // No body to delimit
  5633. auto head = cli.Head("/");
  5634. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  5635. EXPECT_FALSE(head->has_header("Connection"));
  5636. }
  5637. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  5638. #ifdef CPPHTTPLIB_SSL_ENABLED
  5639. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  5640. ASSERT_TRUE(svr.is_valid());
  5641. #else
  5642. Server svr;
  5643. #endif
  5644. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  5645. if (req.path == "/routing_handler") {
  5646. res.set_header("PRE_ROUTING", "on");
  5647. res.set_content("Routing Handler", "text/plain");
  5648. return httplib::Server::HandlerResponse::Handled;
  5649. }
  5650. return httplib::Server::HandlerResponse::Unhandled;
  5651. });
  5652. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  5653. res.set_content("Error", "text/html");
  5654. });
  5655. svr.set_post_routing_handler([](const Request &req, Response &res) {
  5656. if (req.path == "/routing_handler") {
  5657. res.set_header("POST_ROUTING", "on");
  5658. }
  5659. });
  5660. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5661. res.set_content("Hello World!\n", "text/plain");
  5662. });
  5663. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5664. auto se = detail::scope_exit([&] {
  5665. svr.stop();
  5666. thread.join();
  5667. ASSERT_FALSE(svr.is_running());
  5668. });
  5669. svr.wait_until_ready();
  5670. {
  5671. #ifdef CPPHTTPLIB_SSL_ENABLED
  5672. SSLClient cli(HOST, PORT);
  5673. cli.enable_server_certificate_verification(false);
  5674. #else
  5675. Client cli(HOST, PORT);
  5676. #endif
  5677. auto res = cli.Get("/routing_handler");
  5678. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5679. EXPECT_EQ(StatusCode::OK_200, res->status);
  5680. EXPECT_EQ("Routing Handler", res->body);
  5681. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  5682. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  5683. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  5684. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  5685. }
  5686. {
  5687. #ifdef CPPHTTPLIB_SSL_ENABLED
  5688. SSLClient cli(HOST, PORT);
  5689. cli.enable_server_certificate_verification(false);
  5690. #else
  5691. Client cli(HOST, PORT);
  5692. #endif
  5693. auto res = cli.Get("/hi");
  5694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5695. EXPECT_EQ(StatusCode::OK_200, res->status);
  5696. EXPECT_EQ("Hello World!\n", res->body);
  5697. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5698. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5699. }
  5700. {
  5701. #ifdef CPPHTTPLIB_SSL_ENABLED
  5702. SSLClient cli(HOST, PORT);
  5703. cli.enable_server_certificate_verification(false);
  5704. #else
  5705. Client cli(HOST, PORT);
  5706. #endif
  5707. auto res = cli.Get("/aaa");
  5708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5709. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5710. EXPECT_EQ("Error", res->body);
  5711. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  5712. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  5713. }
  5714. }
  5715. TEST(RequestHandlerTest, PreRequestHandler) {
  5716. auto route_path = "/user/:user";
  5717. Server svr;
  5718. svr.Get("/hi", [](const Request &, Response &res) {
  5719. res.set_content("hi", "text/plain");
  5720. });
  5721. svr.Get(route_path, [](const Request &req, Response &res) {
  5722. res.set_content(req.path_params.at("user"), "text/plain");
  5723. });
  5724. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5725. if (req.matched_route == route_path) {
  5726. auto user = req.path_params.at("user");
  5727. if (user != "john") {
  5728. res.status = StatusCode::Forbidden_403;
  5729. res.set_content("error", "text/html");
  5730. return Server::HandlerResponse::Handled;
  5731. }
  5732. }
  5733. return Server::HandlerResponse::Unhandled;
  5734. });
  5735. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5736. auto se = detail::scope_exit([&] {
  5737. svr.stop();
  5738. thread.join();
  5739. ASSERT_FALSE(svr.is_running());
  5740. });
  5741. svr.wait_until_ready();
  5742. Client cli(HOST, PORT);
  5743. {
  5744. auto res = cli.Get("/hi");
  5745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5746. EXPECT_EQ(StatusCode::OK_200, res->status);
  5747. EXPECT_EQ("hi", res->body);
  5748. }
  5749. {
  5750. auto res = cli.Get("/user/john");
  5751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5752. EXPECT_EQ(StatusCode::OK_200, res->status);
  5753. EXPECT_EQ("john", res->body);
  5754. }
  5755. {
  5756. auto res = cli.Get("/user/invalid-user");
  5757. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5758. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5759. EXPECT_EQ("error", res->body);
  5760. }
  5761. }
  5762. // The pre-request handler must run before the request body is read, so a
  5763. // rejected request never forces the server to buffer a (potentially large)
  5764. // body. Here the posted body is larger than the payload limit: if the body
  5765. // were read first the server would answer 413, but because the pre-request
  5766. // handler runs first it answers 403 and the body is never read.
  5767. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5768. Server svr;
  5769. svr.set_payload_max_length(8);
  5770. auto handler_ran = false;
  5771. svr.Post("/reject", [&](const Request &req, Response &res) {
  5772. handler_ran = true;
  5773. res.set_content(req.body, "text/plain");
  5774. });
  5775. svr.Post("/accept", [](const Request &req, Response &res) {
  5776. res.set_content(req.body, "text/plain");
  5777. });
  5778. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5779. if (req.matched_route == "/reject") {
  5780. res.status = StatusCode::Forbidden_403;
  5781. res.set_content("denied", "text/plain");
  5782. return Server::HandlerResponse::Handled;
  5783. }
  5784. return Server::HandlerResponse::Unhandled;
  5785. });
  5786. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5787. auto se = detail::scope_exit([&] {
  5788. svr.stop();
  5789. thread.join();
  5790. ASSERT_FALSE(svr.is_running());
  5791. });
  5792. svr.wait_until_ready();
  5793. Client cli(HOST, PORT);
  5794. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5795. // rejects with 403 before the body is read, so 413 is never reached.
  5796. {
  5797. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5800. EXPECT_EQ("denied", res->body);
  5801. EXPECT_FALSE(handler_ran);
  5802. }
  5803. // An approved route still reads the body and enforces the payload limit.
  5804. {
  5805. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5807. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5808. }
  5809. }
  5810. TEST(UserDataTest, BasicOperations) {
  5811. httplib::UserData ud;
  5812. // Initially empty
  5813. EXPECT_FALSE(ud.has("key"));
  5814. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5815. // set and get
  5816. ud.set("key", 42);
  5817. EXPECT_TRUE(ud.has("key"));
  5818. auto *p = ud.get<int>("key");
  5819. ASSERT_NE(nullptr, p);
  5820. EXPECT_EQ(42, *p);
  5821. // Type mismatch → nullptr
  5822. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5823. // Overwrite with different type
  5824. ud.set("key", std::string("hello"));
  5825. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5826. auto *s = ud.get<std::string>("key");
  5827. ASSERT_NE(nullptr, s);
  5828. EXPECT_EQ("hello", *s);
  5829. // erase
  5830. ud.erase("key");
  5831. EXPECT_FALSE(ud.has("key"));
  5832. // clear
  5833. ud.set("a", 1);
  5834. ud.set("b", 2);
  5835. ud.clear();
  5836. EXPECT_FALSE(ud.has("a"));
  5837. EXPECT_FALSE(ud.has("b"));
  5838. }
  5839. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5840. struct AuthCtx {
  5841. std::string user_id;
  5842. };
  5843. Server svr;
  5844. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5845. res.user_data.set("auth", AuthCtx{"alice"});
  5846. return Server::HandlerResponse::Unhandled;
  5847. });
  5848. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5849. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5850. ASSERT_NE(nullptr, ctx);
  5851. res.set_content("Hello " + ctx->user_id, "text/plain");
  5852. });
  5853. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5854. auto se = detail::scope_exit([&] {
  5855. svr.stop();
  5856. thread.join();
  5857. ASSERT_FALSE(svr.is_running());
  5858. });
  5859. svr.wait_until_ready();
  5860. Client cli(HOST, PORT);
  5861. auto res = cli.Get("/me");
  5862. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5863. EXPECT_EQ(StatusCode::OK_200, res->status);
  5864. EXPECT_EQ("Hello alice", res->body);
  5865. }
  5866. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5867. struct RoleCtx {
  5868. std::string role;
  5869. };
  5870. Server svr;
  5871. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5872. res.user_data.set("role", RoleCtx{"admin"});
  5873. return Server::HandlerResponse::Unhandled;
  5874. });
  5875. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5876. auto *ctx = res.user_data.get<RoleCtx>("role");
  5877. ASSERT_NE(nullptr, ctx);
  5878. res.set_content(ctx->role, "text/plain");
  5879. });
  5880. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5881. auto se = detail::scope_exit([&] {
  5882. svr.stop();
  5883. thread.join();
  5884. ASSERT_FALSE(svr.is_running());
  5885. });
  5886. svr.wait_until_ready();
  5887. Client cli(HOST, PORT);
  5888. auto res = cli.Get("/role");
  5889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5890. EXPECT_EQ(StatusCode::OK_200, res->status);
  5891. EXPECT_EQ("admin", res->body);
  5892. }
  5893. TEST(InvalidFormatTest, StatusCode) {
  5894. Server svr;
  5895. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5896. res.set_content("Hello World!\n", "text/plain");
  5897. res.status = 9999; // Status should be a three-digit code...
  5898. });
  5899. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5900. auto se = detail::scope_exit([&] {
  5901. svr.stop();
  5902. thread.join();
  5903. ASSERT_FALSE(svr.is_running());
  5904. });
  5905. svr.wait_until_ready();
  5906. {
  5907. Client cli(HOST, PORT);
  5908. auto res = cli.Get("/hi");
  5909. ASSERT_FALSE(res);
  5910. }
  5911. }
  5912. TEST(URLFragmentTest, WithFragment) {
  5913. Server svr;
  5914. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5915. EXPECT_TRUE(req.target == "/hi");
  5916. });
  5917. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5918. auto se = detail::scope_exit([&] {
  5919. svr.stop();
  5920. thread.join();
  5921. ASSERT_FALSE(svr.is_running());
  5922. });
  5923. svr.wait_until_ready();
  5924. {
  5925. Client cli(HOST, PORT);
  5926. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5927. EXPECT_TRUE(res);
  5928. EXPECT_EQ(StatusCode::OK_200, res->status);
  5929. res = cli.Get("/hi%23key1=val1=key2=val2");
  5930. EXPECT_TRUE(res);
  5931. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5932. }
  5933. }
  5934. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5935. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5936. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5937. Server svr;
  5938. std::vector<std::string> targets;
  5939. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5940. targets.push_back(req.target);
  5941. });
  5942. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5943. auto se = detail::scope_exit([&] {
  5944. svr.stop();
  5945. thread.join();
  5946. ASSERT_FALSE(svr.is_running());
  5947. });
  5948. svr.wait_until_ready();
  5949. Client cli(HOST, PORT);
  5950. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5951. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5952. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5953. // A '?' after the '#' belongs to the fragment, not to the query.
  5954. Request req;
  5955. req.method = "GET";
  5956. req.path = "/hi#f?x=1";
  5957. req.params.emplace("a", "1");
  5958. Response res;
  5959. auto error = Error::Success;
  5960. EXPECT_TRUE(cli.send(req, res, error));
  5961. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5962. "/hi?a=1"}),
  5963. targets);
  5964. }
  5965. TEST(HeaderWriter, SetHeaderWriter) {
  5966. Server svr;
  5967. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5968. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5969. return detail::write_headers(strm, hdrs);
  5970. });
  5971. svr.Get("/hi", [](const Request &req, Response &res) {
  5972. auto it = req.headers.find("CustomClientHeader");
  5973. EXPECT_TRUE(it != req.headers.end());
  5974. EXPECT_EQ(it->second, "CustomClientValue");
  5975. res.set_content("Hello World!\n", "text/plain");
  5976. });
  5977. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5978. auto se = detail::scope_exit([&] {
  5979. svr.stop();
  5980. thread.join();
  5981. ASSERT_FALSE(svr.is_running());
  5982. });
  5983. svr.wait_until_ready();
  5984. {
  5985. Client cli(HOST, PORT);
  5986. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5987. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5988. return detail::write_headers(strm, hdrs);
  5989. });
  5990. auto res = cli.Get("/hi");
  5991. EXPECT_TRUE(res);
  5992. EXPECT_EQ(StatusCode::OK_200, res->status);
  5993. auto it = res->headers.find("CustomServerHeader");
  5994. EXPECT_TRUE(it != res->headers.end());
  5995. EXPECT_EQ(it->second, "CustomServerValue");
  5996. }
  5997. }
  5998. class ServerTest : public ::testing::Test {
  5999. protected:
  6000. ServerTest()
  6001. : cli_(HOST, PORT)
  6002. #ifdef CPPHTTPLIB_SSL_ENABLED
  6003. ,
  6004. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  6005. #endif
  6006. {
  6007. #ifdef CPPHTTPLIB_SSL_ENABLED
  6008. cli_.enable_server_certificate_verification(false);
  6009. #endif
  6010. // Allow LARGE_DATA (100MB) responses
  6011. cli_.set_payload_max_length(200 * 1024 * 1024);
  6012. }
  6013. virtual void SetUp() {
  6014. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  6015. svr_.set_payload_max_length(200 * 1024 * 1024);
  6016. svr_.set_mount_point("/", "./www");
  6017. svr_.set_mount_point("/mount", "./www2");
  6018. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  6019. svr_.Get("/hi",
  6020. [&](const Request & /*req*/, Response &res) {
  6021. res.set_content("Hello World!", "text/plain");
  6022. })
  6023. .Get("/file_content",
  6024. [&](const Request & /*req*/, Response &res) {
  6025. res.set_file_content("./www/dir/test.html");
  6026. })
  6027. .Get("/file_content_with_content_type",
  6028. [&](const Request & /*req*/, Response &res) {
  6029. res.set_file_content("./www/file", "text/plain");
  6030. })
  6031. .Get("/invalid_file_content",
  6032. [&](const Request & /*req*/, Response &res) {
  6033. res.set_file_content("./www/dir/invalid_file_path");
  6034. })
  6035. .Get("/http_response_splitting",
  6036. [&](const Request & /*req*/, Response &res) {
  6037. res.set_header("a", "1\r\nSet-Cookie: a=1");
  6038. EXPECT_EQ(0U, res.headers.size());
  6039. EXPECT_FALSE(res.has_header("a"));
  6040. res.set_header("a", "1\nSet-Cookie: a=1");
  6041. EXPECT_EQ(0U, res.headers.size());
  6042. EXPECT_FALSE(res.has_header("a"));
  6043. res.set_header("a", "1\rSet-Cookie: a=1");
  6044. EXPECT_EQ(0U, res.headers.size());
  6045. EXPECT_FALSE(res.has_header("a"));
  6046. res.set_header("a\r\nb", "0");
  6047. EXPECT_EQ(0U, res.headers.size());
  6048. EXPECT_FALSE(res.has_header("a"));
  6049. res.set_header("a\rb", "0");
  6050. EXPECT_EQ(0U, res.headers.size());
  6051. EXPECT_FALSE(res.has_header("a"));
  6052. res.set_header("a\nb", "0");
  6053. EXPECT_EQ(0U, res.headers.size());
  6054. EXPECT_FALSE(res.has_header("a"));
  6055. res.set_redirect("1\r\nSet-Cookie: a=1");
  6056. EXPECT_EQ(0U, res.headers.size());
  6057. EXPECT_FALSE(res.has_header("Location"));
  6058. })
  6059. .Get("/slow",
  6060. [&](const Request & /*req*/, Response &res) {
  6061. std::this_thread::sleep_for(std::chrono::seconds(4));
  6062. res.set_content("slow", "text/plain");
  6063. })
  6064. #if 0
  6065. .Post("/slowpost",
  6066. [&](const Request & /*req*/, Response &res) {
  6067. std::this_thread::sleep_for(std::chrono::seconds(2));
  6068. res.set_content("slow", "text/plain");
  6069. })
  6070. #endif
  6071. .Get("/remote_addr",
  6072. [&](const Request &req, Response &res) {
  6073. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  6074. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  6075. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6076. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  6077. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  6078. #endif
  6079. res.set_content(req.remote_addr, "text/plain");
  6080. })
  6081. .Get("/local_addr",
  6082. [&](const Request &req, Response &res) {
  6083. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  6084. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  6085. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  6086. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  6087. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  6088. #endif
  6089. auto local_addr = req.local_addr;
  6090. auto local_port = std::to_string(req.local_port);
  6091. res.set_content(local_addr.append(":").append(local_port),
  6092. "text/plain");
  6093. })
  6094. .Get("/endwith%",
  6095. [&](const Request & /*req*/, Response &res) {
  6096. res.set_content("Hello World!", "text/plain");
  6097. })
  6098. .Get("/a\\+\\+b",
  6099. [&](const Request &req, Response &res) {
  6100. ASSERT_TRUE(req.has_param("a +b"));
  6101. auto val = req.get_param_value("a +b");
  6102. res.set_content(val, "text/plain");
  6103. })
  6104. .Get("/", [&](const Request & /*req*/,
  6105. Response &res) { res.set_redirect("/hi"); })
  6106. .Post("/1",
  6107. [](const Request & /*req*/, Response &res) {
  6108. res.set_redirect("/2", StatusCode::SeeOther_303);
  6109. })
  6110. .Get("/2",
  6111. [](const Request & /*req*/, Response &res) {
  6112. res.set_content("redirected.", "text/plain");
  6113. res.status = StatusCode::OK_200;
  6114. })
  6115. .Post("/person",
  6116. [&](const Request &req, Response &res) {
  6117. if (req.has_param("name") && req.has_param("note")) {
  6118. persons_[req.get_param_value("name")] =
  6119. req.get_param_value("note");
  6120. } else {
  6121. res.status = StatusCode::BadRequest_400;
  6122. }
  6123. })
  6124. .Put("/person",
  6125. [&](const Request &req, Response &res) {
  6126. if (req.has_param("name") && req.has_param("note")) {
  6127. persons_[req.get_param_value("name")] =
  6128. req.get_param_value("note");
  6129. } else {
  6130. res.status = StatusCode::BadRequest_400;
  6131. }
  6132. })
  6133. .Get("/person/(.*)",
  6134. [&](const Request &req, Response &res) {
  6135. string name = req.matches[1];
  6136. if (persons_.find(name) != persons_.end()) {
  6137. auto note = persons_[name];
  6138. res.set_content(note, "text/plain");
  6139. } else {
  6140. res.status = StatusCode::NotFound_404;
  6141. }
  6142. })
  6143. .Delete("/person",
  6144. [&](const Request &req, Response &res) {
  6145. if (req.has_param("name")) {
  6146. string name = req.get_param_value("name");
  6147. if (persons_.find(name) != persons_.end()) {
  6148. persons_.erase(name);
  6149. res.set_content("DELETED", "text/plain");
  6150. } else {
  6151. res.status = StatusCode::NotFound_404;
  6152. }
  6153. } else {
  6154. res.status = StatusCode::BadRequest_400;
  6155. }
  6156. })
  6157. .Post("/x-www-form-urlencoded-json",
  6158. [&](const Request &req, Response &res) {
  6159. auto json = req.get_param_value("json");
  6160. ASSERT_EQ(JSON_DATA, json);
  6161. res.set_content(json, "appliation/json");
  6162. res.status = StatusCode::OK_200;
  6163. })
  6164. .Get("/streamed-chunked",
  6165. [&](const Request & /*req*/, Response &res) {
  6166. res.set_chunked_content_provider(
  6167. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  6168. sink.os << "123";
  6169. sink.os << "456";
  6170. sink.os << "789";
  6171. sink.done();
  6172. return true;
  6173. });
  6174. })
  6175. .Get("/streamed-chunked-with-prohibited-trailer",
  6176. [&](const Request & /*req*/, Response &res) {
  6177. auto i = new int(0);
  6178. // Declare both a prohibited trailer (Content-Length) and an
  6179. // allowed one
  6180. res.set_header("Trailer", "Content-Length, X-Allowed");
  6181. res.set_chunked_content_provider(
  6182. "text/plain",
  6183. [i](size_t /*offset*/, DataSink &sink) {
  6184. switch (*i) {
  6185. case 0: sink.os << "123"; break;
  6186. case 1: sink.os << "456"; break;
  6187. case 2: sink.os << "789"; break;
  6188. case 3: {
  6189. sink.done_with_trailer(
  6190. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  6191. } break;
  6192. }
  6193. (*i)++;
  6194. return true;
  6195. },
  6196. [i](bool success) {
  6197. EXPECT_TRUE(success);
  6198. delete i;
  6199. });
  6200. })
  6201. .Get("/streamed-chunked2",
  6202. [&](const Request & /*req*/, Response &res) {
  6203. auto i = new int(0);
  6204. res.set_chunked_content_provider(
  6205. "text/plain",
  6206. [i](size_t /*offset*/, DataSink &sink) {
  6207. switch (*i) {
  6208. case 0: sink.os << "123"; break;
  6209. case 1: sink.os << "456"; break;
  6210. case 2: sink.os << "789"; break;
  6211. case 3: sink.done(); break;
  6212. }
  6213. (*i)++;
  6214. return true;
  6215. },
  6216. [i](bool success) {
  6217. EXPECT_TRUE(success);
  6218. delete i;
  6219. });
  6220. })
  6221. .Get("/streamed-chunked-with-trailer",
  6222. [&](const Request & /*req*/, Response &res) {
  6223. auto i = new int(0);
  6224. res.set_header("Trailer", "Dummy1, Dummy2");
  6225. res.set_chunked_content_provider(
  6226. "text/plain",
  6227. [i](size_t /*offset*/, DataSink &sink) {
  6228. switch (*i) {
  6229. case 0: sink.os << "123"; break;
  6230. case 1: sink.os << "456"; break;
  6231. case 2: sink.os << "789"; break;
  6232. case 3: {
  6233. sink.done_with_trailer(
  6234. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  6235. } break;
  6236. }
  6237. (*i)++;
  6238. return true;
  6239. },
  6240. [i](bool success) {
  6241. EXPECT_TRUE(success);
  6242. delete i;
  6243. });
  6244. })
  6245. .Get("/streamed",
  6246. [&](const Request & /*req*/, Response &res) {
  6247. res.set_content_provider(
  6248. 6, "text/plain",
  6249. [](size_t offset, size_t /*length*/, DataSink &sink) {
  6250. sink.os << (offset < 3 ? "a" : "b");
  6251. return true;
  6252. });
  6253. })
  6254. .Get("/streamed-without-length",
  6255. [&](const Request & /*req*/, Response &res) {
  6256. auto data = new std::string("abcdefg");
  6257. res.set_content_provider(
  6258. "text/plain",
  6259. [data](size_t offset, DataSink &sink) {
  6260. if (offset < data->size()) {
  6261. sink.os << data->substr(offset);
  6262. }
  6263. sink.done();
  6264. return true;
  6265. },
  6266. [data](bool success) {
  6267. EXPECT_TRUE(success);
  6268. delete data;
  6269. });
  6270. })
  6271. .Get("/streamed-with-range",
  6272. [&](const Request &req, Response &res) {
  6273. auto data = new std::string("abcdefg");
  6274. // An explicit status keeps the server from picking the 206 it
  6275. // would otherwise choose for a ranged request, so the response
  6276. // is not a partial representation.
  6277. auto status = req.get_param_value("status");
  6278. if (status == "200") {
  6279. res.status = StatusCode::OK_200;
  6280. } else if (status == "403") {
  6281. res.status = StatusCode::Forbidden_403;
  6282. }
  6283. res.set_content_provider(
  6284. data->size(), "text/plain",
  6285. [data](size_t offset, size_t length, DataSink &sink) {
  6286. size_t DATA_CHUNK_SIZE = 4;
  6287. const auto &d = *data;
  6288. auto out_len =
  6289. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  6290. auto ret =
  6291. sink.write(&d[static_cast<size_t>(offset)], out_len);
  6292. EXPECT_TRUE(ret);
  6293. return true;
  6294. },
  6295. [data, &req](bool success) {
  6296. EXPECT_EQ(success, !req.has_param("error"));
  6297. delete data;
  6298. });
  6299. })
  6300. .Get("/streamed-cancel",
  6301. [&](const Request & /*req*/, Response &res) {
  6302. res.set_content_provider(
  6303. size_t(-1), "text/plain",
  6304. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6305. sink.os << "data_chunk";
  6306. return true;
  6307. });
  6308. })
  6309. .Get("/regex-with-delimiter",
  6310. [&](const Request &req, Response & /*res*/) {
  6311. ASSERT_TRUE(req.has_param("key"));
  6312. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  6313. })
  6314. .Get("/with-range",
  6315. [&](const Request & /*req*/, Response &res) {
  6316. res.set_content("abcdefg", "text/plain");
  6317. })
  6318. .Get("/test-start-time",
  6319. [&](const Request &req, Response & /*res*/) {
  6320. EXPECT_NE(req.start_time_,
  6321. std::chrono::steady_clock::time_point::min());
  6322. })
  6323. .Get("/with-range-customized-response",
  6324. [&](const Request & /*req*/, Response &res) {
  6325. res.status = StatusCode::BadRequest_400;
  6326. res.set_content(JSON_DATA, "application/json");
  6327. })
  6328. .Post("/chunked",
  6329. [&](const Request &req, Response & /*res*/) {
  6330. EXPECT_EQ(req.body, "dechunked post body");
  6331. })
  6332. .Post("/large-chunked",
  6333. [&](const Request &req, Response & /*res*/) {
  6334. std::string expected(6 * 30 * 1024u, 'a');
  6335. EXPECT_EQ(req.body, expected);
  6336. })
  6337. .Post("/multipart",
  6338. [&](const Request &req, Response & /*res*/) {
  6339. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  6340. req.form.get_field_count("text2") +
  6341. req.form.get_field_count("file3") +
  6342. req.form.get_field_count("file4"));
  6343. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  6344. req.form.get_file_count("file2"));
  6345. ASSERT_TRUE(!req.form.has_file("???"));
  6346. ASSERT_TRUE(!req.form.has_field("???"));
  6347. ASSERT_TRUE(req.body.empty());
  6348. {
  6349. const auto &text = req.form.get_field("text1");
  6350. EXPECT_EQ("text default", text);
  6351. }
  6352. {
  6353. const auto &text = req.form.get_field("text2");
  6354. EXPECT_EQ("aωb", text);
  6355. }
  6356. {
  6357. const auto &file = req.form.get_file("file1");
  6358. EXPECT_EQ("hello.txt", file.filename);
  6359. EXPECT_EQ("text/plain", file.content_type);
  6360. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6361. }
  6362. {
  6363. const auto &file = req.form.get_file("file2");
  6364. EXPECT_EQ("world.json", file.filename);
  6365. EXPECT_EQ("application/json", file.content_type);
  6366. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  6367. }
  6368. {
  6369. const auto &text = req.form.get_field("file3");
  6370. EXPECT_EQ(0u, text.size());
  6371. }
  6372. {
  6373. const auto &text = req.form.get_field("file4");
  6374. EXPECT_EQ(0u, text.size());
  6375. }
  6376. })
  6377. .Post("/multipart/multi_file_values",
  6378. [&](const Request &req, Response & /*res*/) {
  6379. EXPECT_EQ(3u, req.form.get_field_count("text") +
  6380. req.form.get_field_count("multi_text1"));
  6381. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  6382. ASSERT_TRUE(!req.form.has_file("???"));
  6383. ASSERT_TRUE(!req.form.has_field("???"));
  6384. ASSERT_TRUE(req.body.empty());
  6385. {
  6386. const auto &text = req.form.get_field("text");
  6387. EXPECT_EQ("default text", text);
  6388. }
  6389. {
  6390. const auto &text1_values = req.form.get_fields("multi_text1");
  6391. EXPECT_EQ(2u, text1_values.size());
  6392. EXPECT_EQ("aaaaa", text1_values[0]);
  6393. EXPECT_EQ("bbbbb", text1_values[1]);
  6394. }
  6395. {
  6396. const auto &file1_values = req.form.get_files("multi_file1");
  6397. EXPECT_EQ(2u, file1_values.size());
  6398. auto file1 = file1_values[0];
  6399. EXPECT_EQ(file1.filename, "hello.txt");
  6400. EXPECT_EQ(file1.content_type, "text/plain");
  6401. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  6402. auto file2 = file1_values[1];
  6403. EXPECT_EQ(file2.filename, "world.json");
  6404. EXPECT_EQ(file2.content_type, "application/json");
  6405. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  6406. }
  6407. })
  6408. .Post("/empty",
  6409. [&](const Request &req, Response &res) {
  6410. EXPECT_EQ(req.body, "");
  6411. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  6412. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6413. res.set_content("empty", "text/plain");
  6414. })
  6415. .Post("/empty-no-content-type",
  6416. [&](const Request &req, Response &res) {
  6417. EXPECT_EQ(req.body, "");
  6418. EXPECT_FALSE(req.has_header("Content-Type"));
  6419. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6420. res.set_content("empty-no-content-type", "text/plain");
  6421. })
  6422. .Post("/path-only",
  6423. [&](const Request &req, Response &res) {
  6424. EXPECT_EQ(req.body, "");
  6425. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6426. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6427. res.set_content("path-only", "text/plain");
  6428. })
  6429. .Post("/path-headers-only",
  6430. [&](const Request &req, Response &res) {
  6431. EXPECT_EQ(req.body, "");
  6432. EXPECT_EQ("", req.get_header_value("Content-Type"));
  6433. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6434. EXPECT_EQ("world", req.get_header_value("hello"));
  6435. EXPECT_EQ("world2", req.get_header_value("hello2"));
  6436. res.set_content("path-headers-only", "text/plain");
  6437. })
  6438. .Post("/post-large",
  6439. [&](const Request &req, Response &res) {
  6440. EXPECT_EQ(req.body, LARGE_DATA);
  6441. res.set_content(req.body, "text/plain");
  6442. })
  6443. .Post("/post-loopback",
  6444. [&](const Request &, Response &res,
  6445. ContentReader const &content_reader) {
  6446. std::string body;
  6447. content_reader([&](const char *data, size_t data_length) {
  6448. body.append(data, data_length);
  6449. return true;
  6450. });
  6451. res.set_content(body, "text/plain");
  6452. })
  6453. .Put("/put-loopback",
  6454. [&](const Request &, Response &res,
  6455. ContentReader const &content_reader) {
  6456. std::string body;
  6457. content_reader([&](const char *data, size_t data_length) {
  6458. body.append(data, data_length);
  6459. return true;
  6460. });
  6461. res.set_content(body, "text/plain");
  6462. })
  6463. .Patch("/patch-loopback",
  6464. [&](const Request &, Response &res,
  6465. ContentReader const &content_reader) {
  6466. std::string body;
  6467. content_reader([&](const char *data, size_t data_length) {
  6468. body.append(data, data_length);
  6469. return true;
  6470. });
  6471. res.set_content(body, "text/plain");
  6472. })
  6473. .Put("/empty-no-content-type",
  6474. [&](const Request &req, Response &res) {
  6475. EXPECT_EQ(req.body, "");
  6476. EXPECT_FALSE(req.has_header("Content-Type"));
  6477. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  6478. res.set_content("empty-no-content-type", "text/plain");
  6479. })
  6480. .Put("/put",
  6481. [&](const Request &req, Response &res) {
  6482. EXPECT_EQ(req.body, "PUT");
  6483. res.set_content(req.body, "text/plain");
  6484. })
  6485. .Put("/put-large",
  6486. [&](const Request &req, Response &res) {
  6487. EXPECT_EQ(req.body, LARGE_DATA);
  6488. res.set_content(req.body, "text/plain");
  6489. })
  6490. .Patch("/patch",
  6491. [&](const Request &req, Response &res) {
  6492. EXPECT_EQ(req.body, "PATCH");
  6493. res.set_content(req.body, "text/plain");
  6494. })
  6495. .Delete("/delete",
  6496. [&](const Request & /*req*/, Response &res) {
  6497. res.set_content("DELETE", "text/plain");
  6498. })
  6499. .Delete("/delete-body",
  6500. [&](const Request &req, Response &res) {
  6501. EXPECT_EQ(req.body, "content");
  6502. res.set_content(req.body, "text/plain");
  6503. })
  6504. .Options(R"(\*)",
  6505. [&](const Request & /*req*/, Response &res) {
  6506. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  6507. })
  6508. .CustomRoute("PROPFIND", "/dav/:id",
  6509. [&](const Request &req, Response &res) {
  6510. res.set_header("x-body-size",
  6511. std::to_string(req.body.size()));
  6512. res.set_header("x-matched-route", req.matched_route);
  6513. res.set_header("x-dav-id", req.path_params.at("id"));
  6514. res.status = StatusCode::MultiStatus_207;
  6515. res.set_content(req.body, "application/xml");
  6516. })
  6517. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  6518. [&](const Request &req, Response &res) {
  6519. res.set_header("x-dav-match", req.matches[1]);
  6520. res.status = StatusCode::MultiStatus_207;
  6521. })
  6522. .CustomRoute("MKCOL", "/dav-mkcol",
  6523. [&](const Request &req, Response &res) {
  6524. EXPECT_TRUE(req.body.empty());
  6525. res.status = StatusCode::Created_201;
  6526. })
  6527. .CustomRoute(
  6528. "REPORT", "/dav-report",
  6529. [&](const Request & /*req*/, Response &res,
  6530. const ContentReader &content_reader) {
  6531. std::string body;
  6532. content_reader([&](const char *data, size_t data_length) {
  6533. body.append(data, data_length);
  6534. return true;
  6535. });
  6536. res.set_header("x-body-size", std::to_string(body.size()));
  6537. res.status = StatusCode::MultiStatus_207;
  6538. res.set_content(body, "application/xml");
  6539. })
  6540. .Get("/request-target",
  6541. [&](const Request &req, Response & /*res*/) {
  6542. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  6543. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  6544. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  6545. })
  6546. .Get("/long-query-value",
  6547. [&](const Request &req, Response & /*res*/) {
  6548. EXPECT_EQ(LONG_QUERY_URL, req.target);
  6549. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  6550. })
  6551. .Get("/too-long-query-value",
  6552. [&](const Request &req, Response & /*res*/) {
  6553. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  6554. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  6555. })
  6556. .Get("/array-param",
  6557. [&](const Request &req, Response & /*res*/) {
  6558. EXPECT_EQ(3u, req.get_param_value_count("array"));
  6559. EXPECT_EQ("value1", req.get_param_value("array", 0));
  6560. EXPECT_EQ("value2", req.get_param_value("array", 1));
  6561. EXPECT_EQ("value3", req.get_param_value("array", 2));
  6562. })
  6563. .Get("/array-param-values",
  6564. [&](const Request &req, Response & /*res*/) {
  6565. auto values = req.get_param_values("array");
  6566. EXPECT_EQ(3u, values.size());
  6567. EXPECT_EQ("value1", values[0]);
  6568. EXPECT_EQ("value2", values[1]);
  6569. EXPECT_EQ("value3", values[2]);
  6570. auto empty = req.get_param_values("nonexistent");
  6571. EXPECT_TRUE(empty.empty());
  6572. })
  6573. .Post("/validate-no-multiple-headers",
  6574. [&](const Request &req, Response & /*res*/) {
  6575. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  6576. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  6577. })
  6578. .Post("/content_receiver",
  6579. [&](const Request &req, Response &res,
  6580. const ContentReader &content_reader) {
  6581. if (req.is_multipart_form_data()) {
  6582. std::vector<FormData> items;
  6583. content_reader(
  6584. [&](const FormData &file) {
  6585. items.push_back(file);
  6586. return true;
  6587. },
  6588. [&](const char *data, size_t data_length) {
  6589. items.back().content.append(data, data_length);
  6590. return true;
  6591. });
  6592. EXPECT_EQ(5u, items.size());
  6593. {
  6594. const auto &file = get_file_value(items, "text1");
  6595. EXPECT_TRUE(file.filename.empty());
  6596. EXPECT_EQ("text default", file.content);
  6597. }
  6598. {
  6599. const auto &file = get_file_value(items, "text2");
  6600. EXPECT_TRUE(file.filename.empty());
  6601. EXPECT_EQ("aωb", file.content);
  6602. }
  6603. {
  6604. const auto &file = get_file_value(items, "file1");
  6605. EXPECT_EQ("hello.txt", file.filename);
  6606. EXPECT_EQ("text/plain", file.content_type);
  6607. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  6608. }
  6609. {
  6610. const auto &file = get_file_value(items, "file2");
  6611. EXPECT_EQ("world.json", file.filename);
  6612. EXPECT_EQ("application/json", file.content_type);
  6613. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  6614. }
  6615. {
  6616. const auto &file = get_file_value(items, "file3");
  6617. EXPECT_TRUE(file.filename.empty());
  6618. EXPECT_EQ("application/octet-stream", file.content_type);
  6619. EXPECT_EQ(0u, file.content.size());
  6620. }
  6621. } else {
  6622. std::string body;
  6623. content_reader([&](const char *data, size_t data_length) {
  6624. EXPECT_EQ(7U, data_length);
  6625. body.append(data, data_length);
  6626. return true;
  6627. });
  6628. EXPECT_EQ(body, "content");
  6629. res.set_content(body, "text/plain");
  6630. }
  6631. })
  6632. .Put("/content_receiver",
  6633. [&](const Request & /*req*/, Response &res,
  6634. const ContentReader &content_reader) {
  6635. std::string body;
  6636. content_reader([&](const char *data, size_t data_length) {
  6637. body.append(data, data_length);
  6638. return true;
  6639. });
  6640. EXPECT_EQ(body, "content");
  6641. res.set_content(body, "text/plain");
  6642. })
  6643. .Patch("/content_receiver",
  6644. [&](const Request & /*req*/, Response &res,
  6645. const ContentReader &content_reader) {
  6646. std::string body;
  6647. content_reader([&](const char *data, size_t data_length) {
  6648. body.append(data, data_length);
  6649. return true;
  6650. });
  6651. EXPECT_EQ(body, "content");
  6652. res.set_content(body, "text/plain");
  6653. })
  6654. .Post("/query-string-and-body",
  6655. [&](const Request &req, Response & /*res*/) {
  6656. ASSERT_TRUE(req.has_param("key"));
  6657. EXPECT_EQ(req.get_param_value("key"), "value");
  6658. EXPECT_EQ(req.body, "content");
  6659. })
  6660. .Get("/last-request",
  6661. [&](const Request &req, Response & /*res*/) {
  6662. EXPECT_EQ("close", req.get_header_value("Connection"));
  6663. })
  6664. .Get(R"(/redirect/(\d+))",
  6665. [&](const Request &req, Response &res) {
  6666. auto num = std::stoi(req.matches[1]) + 1;
  6667. std::string url = "/redirect/" + std::to_string(num);
  6668. res.set_redirect(url);
  6669. })
  6670. .Post("/binary",
  6671. [&](const Request &req, Response &res) {
  6672. EXPECT_EQ(4U, req.body.size());
  6673. EXPECT_EQ("application/octet-stream",
  6674. req.get_header_value("Content-Type"));
  6675. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6676. res.set_content(req.body, "application/octet-stream");
  6677. })
  6678. .Put("/binary",
  6679. [&](const Request &req, Response &res) {
  6680. EXPECT_EQ(4U, req.body.size());
  6681. EXPECT_EQ("application/octet-stream",
  6682. req.get_header_value("Content-Type"));
  6683. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6684. res.set_content(req.body, "application/octet-stream");
  6685. })
  6686. .Patch("/binary",
  6687. [&](const Request &req, Response &res) {
  6688. EXPECT_EQ(4U, req.body.size());
  6689. EXPECT_EQ("application/octet-stream",
  6690. req.get_header_value("Content-Type"));
  6691. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6692. res.set_content(req.body, "application/octet-stream");
  6693. })
  6694. .Delete("/binary",
  6695. [&](const Request &req, Response &res) {
  6696. EXPECT_EQ(4U, req.body.size());
  6697. EXPECT_EQ("application/octet-stream",
  6698. req.get_header_value("Content-Type"));
  6699. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  6700. res.set_content(req.body, "application/octet-stream");
  6701. })
  6702. .Get("/issue1772",
  6703. [&](const Request & /*req*/, Response &res) {
  6704. res.status = 401;
  6705. res.set_header("WWW-Authenticate", "Basic realm=123456");
  6706. })
  6707. .Delete("/issue609",
  6708. [](const httplib::Request &, httplib::Response &res,
  6709. const httplib::ContentReader &) {
  6710. res.set_content("ok", "text/plain");
  6711. })
  6712. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  6713. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6714. .Get("/compress",
  6715. [&](const Request & /*req*/, Response &res) {
  6716. res.set_content(
  6717. "12345678901234567890123456789012345678901234567890123456789"
  6718. "01234567890123456789012345678901234567890",
  6719. "text/plain");
  6720. })
  6721. .Get("/compress-with-charset",
  6722. [&](const Request & /*req*/, Response &res) {
  6723. res.set_content(
  6724. "12345678901234567890123456789012345678901234567890123456789"
  6725. "01234567890123456789012345678901234567890",
  6726. "application/json; charset=utf-8");
  6727. })
  6728. .Get("/nocompress",
  6729. [&](const Request & /*req*/, Response &res) {
  6730. res.set_content(
  6731. "12345678901234567890123456789012345678901234567890123456789"
  6732. "01234567890123456789012345678901234567890",
  6733. "application/octet-stream");
  6734. })
  6735. .Post("/compress-multipart",
  6736. [&](const Request &req, Response & /*res*/) {
  6737. EXPECT_EQ(2u, req.form.fields.size());
  6738. ASSERT_TRUE(!req.form.has_field("???"));
  6739. {
  6740. const auto &text = req.form.get_field("key1");
  6741. EXPECT_EQ("test", text);
  6742. }
  6743. {
  6744. const auto &text = req.form.get_field("key2");
  6745. EXPECT_EQ("--abcdefg123", text);
  6746. }
  6747. })
  6748. #endif
  6749. ;
  6750. persons_["john"] = "programmer";
  6751. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6752. svr_.wait_until_ready();
  6753. }
  6754. virtual void TearDown() {
  6755. svr_.stop();
  6756. if (!request_threads_.empty()) {
  6757. std::this_thread::sleep_for(std::chrono::seconds(1));
  6758. for (auto &t : request_threads_) {
  6759. t.join();
  6760. }
  6761. }
  6762. t_.join();
  6763. }
  6764. map<string, string> persons_;
  6765. #ifdef CPPHTTPLIB_SSL_ENABLED
  6766. SSLClient cli_;
  6767. SSLServer svr_;
  6768. #else
  6769. Client cli_;
  6770. Server svr_;
  6771. #endif
  6772. thread t_;
  6773. std::vector<thread> request_threads_;
  6774. };
  6775. TEST_F(ServerTest, GetMethod200) {
  6776. auto res = cli_.Get("/hi");
  6777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6778. EXPECT_EQ("HTTP/1.1", res->version);
  6779. EXPECT_EQ(StatusCode::OK_200, res->status);
  6780. EXPECT_EQ("OK", res->reason);
  6781. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6782. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6783. EXPECT_EQ("Hello World!", res->body);
  6784. }
  6785. TEST_F(ServerTest, GetEmptyFile) {
  6786. auto res = cli_.Get("/empty_file");
  6787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6788. EXPECT_EQ(StatusCode::OK_200, res->status);
  6789. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6790. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6791. EXPECT_EQ("", res->body);
  6792. }
  6793. TEST_F(ServerTest, GetFileContent) {
  6794. auto res = cli_.Get("/file_content");
  6795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6796. EXPECT_EQ(StatusCode::OK_200, res->status);
  6797. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6798. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6799. EXPECT_EQ("test.html", res->body);
  6800. }
  6801. TEST_F(ServerTest, GetFileContentWithRange) {
  6802. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6804. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6805. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6806. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6807. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6808. EXPECT_EQ("est", res->body);
  6809. }
  6810. TEST_F(ServerTest, GetFileContentWithContentType) {
  6811. auto res = cli_.Get("/file_content_with_content_type");
  6812. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6813. EXPECT_EQ(StatusCode::OK_200, res->status);
  6814. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6815. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6816. EXPECT_EQ("file\n", res->body);
  6817. }
  6818. TEST_F(ServerTest, GetInvalidFileContent) {
  6819. auto res = cli_.Get("/invalid_file_content");
  6820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6822. }
  6823. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6824. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6826. EXPECT_EQ("HTTP/1.1", res->version);
  6827. EXPECT_EQ(StatusCode::OK_200, res->status);
  6828. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6829. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6830. EXPECT_EQ("Hello World!", res->body);
  6831. }
  6832. TEST_F(ServerTest, GetMethod302) {
  6833. auto res = cli_.Get("/");
  6834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6835. EXPECT_EQ(StatusCode::Found_302, res->status);
  6836. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6837. }
  6838. TEST_F(ServerTest, GetMethod302Redirect) {
  6839. cli_.set_follow_location(true);
  6840. auto res = cli_.Get("/");
  6841. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6842. EXPECT_EQ(StatusCode::OK_200, res->status);
  6843. EXPECT_EQ("Hello World!", res->body);
  6844. EXPECT_EQ("/hi", res->location);
  6845. }
  6846. TEST_F(ServerTest, GetMethod404) {
  6847. auto res = cli_.Get("/invalid");
  6848. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6849. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6850. }
  6851. TEST_F(ServerTest, HeadMethod200) {
  6852. auto res = cli_.Head("/hi");
  6853. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6854. EXPECT_EQ(StatusCode::OK_200, res->status);
  6855. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6856. EXPECT_TRUE(res->body.empty());
  6857. }
  6858. TEST_F(ServerTest, HeadMethod200Static) {
  6859. auto res = cli_.Head("/mount/dir/index.html");
  6860. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6861. EXPECT_EQ(StatusCode::OK_200, res->status);
  6862. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6863. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6864. EXPECT_TRUE(res->body.empty());
  6865. }
  6866. TEST_F(ServerTest, HeadMethod404) {
  6867. auto res = cli_.Head("/invalid");
  6868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6869. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6870. EXPECT_TRUE(res->body.empty());
  6871. }
  6872. TEST_F(ServerTest, GetMethodPersonJohn) {
  6873. auto res = cli_.Get("/person/john");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6877. EXPECT_EQ("programmer", res->body);
  6878. }
  6879. TEST_F(ServerTest, PostMethod1) {
  6880. auto res = cli_.Get("/person/john1");
  6881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6882. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6883. res = cli_.Post("/person", "name=john1&note=coder",
  6884. "application/x-www-form-urlencoded");
  6885. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6886. ASSERT_EQ(StatusCode::OK_200, res->status);
  6887. res = cli_.Get("/person/john1");
  6888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6889. ASSERT_EQ(StatusCode::OK_200, res->status);
  6890. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6891. ASSERT_EQ("coder", res->body);
  6892. }
  6893. TEST_F(ServerTest, PostMethod2) {
  6894. auto res = cli_.Get("/person/john2");
  6895. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6896. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6897. Params params;
  6898. params.emplace("name", "john2");
  6899. params.emplace("note", "coder");
  6900. res = cli_.Post("/person", params);
  6901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6902. ASSERT_EQ(StatusCode::OK_200, res->status);
  6903. res = cli_.Get("/person/john2");
  6904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6905. ASSERT_EQ(StatusCode::OK_200, res->status);
  6906. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6907. ASSERT_EQ("coder", res->body);
  6908. }
  6909. TEST_F(ServerTest, PutMethod3) {
  6910. auto res = cli_.Get("/person/john3");
  6911. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6912. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6913. Params params;
  6914. params.emplace("name", "john3");
  6915. params.emplace("note", "coder");
  6916. res = cli_.Put("/person", params);
  6917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6918. ASSERT_EQ(StatusCode::OK_200, res->status);
  6919. res = cli_.Get("/person/john3");
  6920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6921. ASSERT_EQ(StatusCode::OK_200, res->status);
  6922. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6923. ASSERT_EQ("coder", res->body);
  6924. }
  6925. TEST_F(ServerTest, DeleteMethod1) {
  6926. auto res = cli_.Get("/person/john4");
  6927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6928. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6929. Params params;
  6930. params.emplace("name", "john4");
  6931. params.emplace("note", "coder");
  6932. res = cli_.Post("/person", params);
  6933. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6934. ASSERT_EQ(StatusCode::OK_200, res->status);
  6935. res = cli_.Get("/person/john4");
  6936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6937. ASSERT_EQ(StatusCode::OK_200, res->status);
  6938. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6939. ASSERT_EQ("coder", res->body);
  6940. Params delete_params;
  6941. delete_params.emplace("name", "john4");
  6942. res = cli_.Delete("/person", delete_params);
  6943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6944. ASSERT_EQ(StatusCode::OK_200, res->status);
  6945. ASSERT_EQ("DELETED", res->body);
  6946. res = cli_.Get("/person/john4");
  6947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6948. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6949. }
  6950. TEST_F(ServerTest, DeleteMethod2) {
  6951. auto res = cli_.Get("/person/john5");
  6952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6953. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6954. Params params;
  6955. params.emplace("name", "john5");
  6956. params.emplace("note", "developer");
  6957. res = cli_.Post("/person", params);
  6958. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6959. ASSERT_EQ(StatusCode::OK_200, res->status);
  6960. res = cli_.Get("/person/john5");
  6961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6962. ASSERT_EQ(StatusCode::OK_200, res->status);
  6963. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6964. ASSERT_EQ("developer", res->body);
  6965. Params delete_params;
  6966. delete_params.emplace("name", "john5");
  6967. Headers headers;
  6968. headers.emplace("Custom-Header", "test-value");
  6969. res = cli_.Delete("/person", headers, delete_params);
  6970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6971. ASSERT_EQ(StatusCode::OK_200, res->status);
  6972. ASSERT_EQ("DELETED", res->body);
  6973. res = cli_.Get("/person/john5");
  6974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6975. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6976. }
  6977. TEST_F(ServerTest, DeleteMethod3) {
  6978. auto res = cli_.Get("/person/john6");
  6979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6980. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6981. Params params;
  6982. params.emplace("name", "john6");
  6983. params.emplace("note", "tester");
  6984. res = cli_.Post("/person", params);
  6985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6986. ASSERT_EQ(StatusCode::OK_200, res->status);
  6987. res = cli_.Get("/person/john6");
  6988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6989. ASSERT_EQ(StatusCode::OK_200, res->status);
  6990. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6991. ASSERT_EQ("tester", res->body);
  6992. Params delete_params;
  6993. delete_params.emplace("name", "john6");
  6994. Headers headers;
  6995. headers.emplace("Custom-Header", "test-value");
  6996. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6998. ASSERT_EQ(StatusCode::OK_200, res->status);
  6999. ASSERT_EQ("DELETED", res->body);
  7000. res = cli_.Get("/person/john6");
  7001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7002. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  7003. }
  7004. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  7005. Params params;
  7006. params.emplace("json", JSON_DATA);
  7007. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  7008. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7009. ASSERT_EQ(StatusCode::OK_200, res->status);
  7010. ASSERT_EQ(JSON_DATA, res->body);
  7011. }
  7012. TEST_F(ServerTest, PostEmptyContent) {
  7013. auto res = cli_.Post("/empty", "", "text/plain");
  7014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7015. ASSERT_EQ(StatusCode::OK_200, res->status);
  7016. ASSERT_EQ("empty", res->body);
  7017. }
  7018. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  7019. auto res = cli_.Post("/empty-no-content-type");
  7020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7021. ASSERT_EQ(StatusCode::OK_200, res->status);
  7022. ASSERT_EQ("empty-no-content-type", res->body);
  7023. }
  7024. TEST_F(ServerTest, PostPathOnly) {
  7025. auto res = cli_.Post("/path-only");
  7026. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7027. ASSERT_EQ(StatusCode::OK_200, res->status);
  7028. ASSERT_EQ("path-only", res->body);
  7029. }
  7030. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  7031. auto res = cli_.Post("/path-headers-only",
  7032. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  7033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7034. ASSERT_EQ(StatusCode::OK_200, res->status);
  7035. ASSERT_EQ("path-headers-only", res->body);
  7036. }
  7037. TEST_F(ServerTest, PostLarge) {
  7038. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  7039. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7040. ASSERT_EQ(StatusCode::OK_200, res->status);
  7041. EXPECT_EQ(LARGE_DATA, res->body);
  7042. }
  7043. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  7044. auto res = cli_.Put("/empty-no-content-type");
  7045. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7046. ASSERT_EQ(StatusCode::OK_200, res->status);
  7047. ASSERT_EQ("empty-no-content-type", res->body);
  7048. }
  7049. TEST_F(ServerTest, GetMethodDir) {
  7050. auto res = cli_.Get("/dir/");
  7051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7052. EXPECT_EQ(StatusCode::OK_200, res->status);
  7053. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7054. auto body = R"(<html>
  7055. <head>
  7056. </head>
  7057. <body>
  7058. <a href="/dir/test.html">Test</a>
  7059. <a href="/hi">hi</a>
  7060. </body>
  7061. </html>
  7062. )";
  7063. EXPECT_EQ(body, res->body);
  7064. }
  7065. TEST_F(ServerTest, GetMethodDirTest) {
  7066. auto res = cli_.Get("/dir/test.html");
  7067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7068. EXPECT_EQ(StatusCode::OK_200, res->status);
  7069. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7070. EXPECT_EQ("test.html", res->body);
  7071. }
  7072. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  7073. auto res = cli_.Get("/dir/../dir/test.html");
  7074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7075. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7076. }
  7077. TEST_F(ServerTest, GetMethodInvalidPath) {
  7078. auto res = cli_.Get("/dir/../test.html");
  7079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7080. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7081. }
  7082. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  7083. auto res = cli_.Get("/../www/dir/test.html");
  7084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7086. }
  7087. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  7088. auto res = cli_.Get("/dir/../../www/dir/test.html");
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7091. }
  7092. TEST_F(ServerTest, GetMethodDirMountTest) {
  7093. auto res = cli_.Get("/mount/dir/test.html");
  7094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7095. EXPECT_EQ(StatusCode::OK_200, res->status);
  7096. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7097. EXPECT_EQ("test.html", res->body);
  7098. }
  7099. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  7100. auto res = cli_.Get("/mount/dir/../dir/test.html");
  7101. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7102. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7103. }
  7104. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  7105. auto res = cli_.Get("/mount/dir/../test.html");
  7106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7107. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7108. }
  7109. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  7110. auto res = cli_.Get("/mount/dir/test.html%00.js");
  7111. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7112. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7113. }
  7114. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  7115. auto res = cli_.Get("/mount/../www2/dir/test.html");
  7116. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7117. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7118. }
  7119. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  7120. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  7121. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7122. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7123. }
  7124. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  7125. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  7126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7127. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7128. }
  7129. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  7130. auto res = cli_.Get("/mount/dir");
  7131. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7132. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  7133. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  7134. }
  7135. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  7136. auto res = cli_.Get("//dir");
  7137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7138. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7139. EXPECT_FALSE(res->has_header("Location"));
  7140. }
  7141. TEST_F(ServerTest, PostMethod303) {
  7142. auto res = cli_.Post("/1", "body", "text/plain");
  7143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7144. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  7145. EXPECT_EQ("/2", res->get_header_value("Location"));
  7146. }
  7147. TEST_F(ServerTest, PostMethod303Redirect) {
  7148. cli_.set_follow_location(true);
  7149. auto res = cli_.Post("/1", "body", "text/plain");
  7150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7151. EXPECT_EQ(StatusCode::OK_200, res->status);
  7152. EXPECT_EQ("redirected.", res->body);
  7153. EXPECT_EQ("/2", res->location);
  7154. }
  7155. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  7156. auto res = cli_.Get("/dir/test.abcde");
  7157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7158. EXPECT_EQ(StatusCode::OK_200, res->status);
  7159. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7160. EXPECT_EQ("abcde", res->body);
  7161. }
  7162. TEST_F(ServerTest, StaticFileRange) {
  7163. auto res =
  7164. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  7165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7167. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7168. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7169. EXPECT_EQ(true, res->has_header("Content-Range"));
  7170. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7171. EXPECT_EQ(std::string("cd"), res->body);
  7172. }
  7173. TEST_F(ServerTest, StaticFileRanges) {
  7174. auto res = cli_.Get("/dir/test.abcde",
  7175. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  7176. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7177. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7178. EXPECT_TRUE(
  7179. res->get_header_value("Content-Type")
  7180. .find(
  7181. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  7182. 0);
  7183. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  7184. }
  7185. TEST_F(ServerTest, StaticFileRangeHead) {
  7186. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  7187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7188. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7189. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  7190. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7191. EXPECT_EQ(true, res->has_header("Content-Range"));
  7192. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7193. }
  7194. TEST_F(ServerTest, StaticFileRangeBigFile) {
  7195. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  7196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7197. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7198. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7199. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7200. EXPECT_EQ(true, res->has_header("Content-Range"));
  7201. EXPECT_EQ("bytes 1048571-1048575/1048576",
  7202. res->get_header_value("Content-Range"));
  7203. EXPECT_EQ("LAST\n", res->body);
  7204. }
  7205. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  7206. auto res =
  7207. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  7208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7209. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7211. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  7212. EXPECT_EQ(true, res->has_header("Content-Range"));
  7213. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  7214. }
  7215. TEST_F(ServerTest, StaticFileBigFile) {
  7216. auto res = cli_.Get("/dir/1MB.txt");
  7217. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7218. EXPECT_EQ(StatusCode::OK_200, res->status);
  7219. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7220. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7221. }
  7222. TEST_F(ServerTest, InvalidBaseDirMount) {
  7223. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  7224. }
  7225. TEST_F(ServerTest, Binary) {
  7226. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  7227. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  7228. "application/octet-stream");
  7229. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7230. ASSERT_EQ(StatusCode::OK_200, res->status);
  7231. ASSERT_EQ(4U, res->body.size());
  7232. res = cli_.Put("/binary", binary.data(), binary.size(),
  7233. "application/octet-stream");
  7234. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7235. ASSERT_EQ(StatusCode::OK_200, res->status);
  7236. ASSERT_EQ(4U, res->body.size());
  7237. res = cli_.Patch("/binary", binary.data(), binary.size(),
  7238. "application/octet-stream");
  7239. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7240. ASSERT_EQ(StatusCode::OK_200, res->status);
  7241. ASSERT_EQ(4U, res->body.size());
  7242. res = cli_.Delete("/binary", binary.data(), binary.size(),
  7243. "application/octet-stream");
  7244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7245. ASSERT_EQ(StatusCode::OK_200, res->status);
  7246. ASSERT_EQ(4U, res->body.size());
  7247. }
  7248. TEST_F(ServerTest, BinaryString) {
  7249. auto binary = std::string("\x00\x01\x02\x03", 4);
  7250. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  7251. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7252. ASSERT_EQ(StatusCode::OK_200, res->status);
  7253. ASSERT_EQ(4U, res->body.size());
  7254. res = cli_.Put("/binary", binary, "application/octet-stream");
  7255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7256. ASSERT_EQ(StatusCode::OK_200, res->status);
  7257. ASSERT_EQ(4U, res->body.size());
  7258. res = cli_.Patch("/binary", binary, "application/octet-stream");
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. ASSERT_EQ(StatusCode::OK_200, res->status);
  7261. ASSERT_EQ(4U, res->body.size());
  7262. res = cli_.Delete("/binary", binary, "application/octet-stream");
  7263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7264. ASSERT_EQ(StatusCode::OK_200, res->status);
  7265. ASSERT_EQ(4U, res->body.size());
  7266. }
  7267. TEST_F(ServerTest, EmptyRequest) {
  7268. auto res = cli_.Get("");
  7269. ASSERT_TRUE(!res);
  7270. EXPECT_EQ(Error::Connection, res.error());
  7271. }
  7272. TEST_F(ServerTest, LongRequest) {
  7273. std::string request;
  7274. for (size_t i = 0; i < 545; i++) {
  7275. request += "/TooLongRequest";
  7276. }
  7277. request += "OK";
  7278. auto res = cli_.Get(request.c_str());
  7279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7280. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7281. }
  7282. TEST_F(ServerTest, TooLongRequest) {
  7283. std::string request;
  7284. for (size_t i = 0; i < 546; i++) {
  7285. request += "/TooLongRequest";
  7286. }
  7287. request += "_NG";
  7288. auto start = std::chrono::high_resolution_clock::now();
  7289. cli_.set_keep_alive(true);
  7290. auto res = cli_.Get(request.c_str());
  7291. auto end = std::chrono::high_resolution_clock::now();
  7292. auto elapsed =
  7293. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7294. .count();
  7295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7296. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7297. EXPECT_LE(elapsed, 1000);
  7298. EXPECT_EQ("close", res->get_header_value("Connection"));
  7299. EXPECT_FALSE(cli_.is_socket_open());
  7300. }
  7301. TEST_F(ServerTest, AlmostTooLongRequest) {
  7302. // test for #2046 - URI length check shouldn't include other content on req
  7303. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  7304. // leading /, space, HTTP/1.1)
  7305. std::string request =
  7306. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  7307. auto res = cli_.Get(request.c_str());
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7310. }
  7311. TEST_F(ServerTest, LongHeader) {
  7312. Request req;
  7313. req.method = "GET";
  7314. req.path = "/hi";
  7315. std::string host_and_port;
  7316. host_and_port += HOST;
  7317. host_and_port += ":";
  7318. host_and_port += std::to_string(PORT);
  7319. req.headers.emplace("Host", host_and_port.c_str());
  7320. req.headers.emplace("Accept", "*/*");
  7321. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7322. req.headers.emplace(
  7323. "Header-Name",
  7324. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7325. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7326. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7327. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7328. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7329. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7330. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7331. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7332. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7333. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7334. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7335. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7336. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7337. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7338. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7339. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7340. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7341. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7342. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7343. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7344. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7345. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7346. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7347. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7348. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7349. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7350. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7351. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7352. "@@@@@@@@@@@@@@@@");
  7353. auto res = std::make_shared<Response>();
  7354. auto error = Error::Success;
  7355. auto ret = cli_.send(req, *res, error);
  7356. ASSERT_TRUE(ret);
  7357. EXPECT_EQ(StatusCode::OK_200, res->status);
  7358. }
  7359. TEST_F(ServerTest, LongQueryValue) {
  7360. auto start = std::chrono::high_resolution_clock::now();
  7361. cli_.set_keep_alive(true);
  7362. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  7363. auto end = std::chrono::high_resolution_clock::now();
  7364. auto elapsed =
  7365. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  7366. .count();
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  7369. EXPECT_LE(elapsed, 1000);
  7370. EXPECT_EQ("close", res->get_header_value("Connection"));
  7371. EXPECT_FALSE(cli_.is_socket_open());
  7372. }
  7373. TEST_F(ServerTest, TooLongQueryValue) {
  7374. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  7375. ASSERT_FALSE(res);
  7376. EXPECT_EQ(Error::Read, res.error());
  7377. }
  7378. TEST_F(ServerTest, TooLongHeader) {
  7379. Request req;
  7380. req.method = "GET";
  7381. req.path = "/hi";
  7382. std::string host_and_port;
  7383. host_and_port += HOST;
  7384. host_and_port += ":";
  7385. host_and_port += std::to_string(PORT);
  7386. req.headers.emplace("Host", host_and_port.c_str());
  7387. req.headers.emplace("Accept", "*/*");
  7388. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7389. req.headers.emplace(
  7390. "Header-Name",
  7391. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7392. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7393. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7394. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7395. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7396. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7397. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7398. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7399. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7400. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7401. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7402. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7403. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7404. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7405. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7406. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7407. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7408. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7409. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7410. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7411. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7412. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7413. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7414. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7415. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7416. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7417. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7418. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  7419. "@@@@@@@@@@@@@@@@@");
  7420. auto res = std::make_shared<Response>();
  7421. auto error = Error::Success;
  7422. auto ret = cli_.send(req, *res, error);
  7423. ASSERT_TRUE(ret);
  7424. EXPECT_EQ(StatusCode::OK_200, res->status);
  7425. }
  7426. TEST_F(ServerTest, HeaderCountAtLimit) {
  7427. // Test with headers just under the 100 limit
  7428. httplib::Headers headers;
  7429. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  7430. // This should keep us just under the 100 header limit
  7431. for (int i = 0; i < 95; i++) {
  7432. std::string name = "X-Test-Header-" + std::to_string(i);
  7433. std::string value = "value" + std::to_string(i);
  7434. headers.emplace(name, value);
  7435. }
  7436. // This should work fine as we're under the limit
  7437. auto res = cli_.Get("/hi", headers);
  7438. EXPECT_TRUE(res);
  7439. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  7440. }
  7441. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  7442. // Test with many headers to exceed the 100 limit
  7443. httplib::Headers headers;
  7444. // Add 150 headers to definitely exceed the 100 limit
  7445. for (int i = 0; i < 150; i++) {
  7446. std::string name = "X-Test-Header-" + std::to_string(i);
  7447. std::string value = "value" + std::to_string(i);
  7448. headers.emplace(name, value);
  7449. }
  7450. // This should fail due to exceeding header count limit
  7451. cli_.set_keep_alive(true);
  7452. auto res = cli_.Get("/hi", headers);
  7453. // The server should respond with 400 Bad Request
  7454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7455. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7456. EXPECT_EQ("close", res->get_header_value("Connection"));
  7457. EXPECT_FALSE(cli_.is_socket_open());
  7458. }
  7459. TEST_F(ServerTest, PercentEncoding) {
  7460. auto res = cli_.Get("/e%6edwith%");
  7461. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7462. EXPECT_EQ(StatusCode::OK_200, res->status);
  7463. }
  7464. TEST_F(ServerTest, PercentEncodingUnicode) {
  7465. auto res = cli_.Get("/e%u006edwith%");
  7466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7467. EXPECT_EQ(StatusCode::OK_200, res->status);
  7468. }
  7469. TEST_F(ServerTest, InvalidPercentEncoding) {
  7470. auto res = cli_.Get("/%endwith%");
  7471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7472. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7473. }
  7474. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  7475. auto res = cli_.Get("/%uendwith%");
  7476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7477. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7478. }
  7479. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  7480. auto res = cli_.Get("/hello?aaa=bbb%");
  7481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7482. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7483. }
  7484. TEST_F(ServerTest, PlusSignEncoding) {
  7485. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  7486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7487. EXPECT_EQ(StatusCode::OK_200, res->status);
  7488. EXPECT_EQ("a +b", res->body);
  7489. }
  7490. TEST_F(ServerTest, HeaderCountSecurityTest) {
  7491. // This test simulates a potential DoS attack using many headers
  7492. // to verify our security fix prevents memory exhaustion
  7493. httplib::Headers attack_headers;
  7494. // Attempt to add many headers like an attacker would (200 headers to far
  7495. // exceed limit)
  7496. for (int i = 0; i < 200; i++) {
  7497. std::string name = "X-Attack-Header-" + std::to_string(i);
  7498. std::string value = "attack_payload_" + std::to_string(i);
  7499. attack_headers.emplace(name, value);
  7500. }
  7501. // Try to POST with excessive headers
  7502. cli_.set_keep_alive(true);
  7503. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  7504. // Should either fail or return 400 Bad Request due to security limit
  7505. if (res) {
  7506. // If we get a response, it should be 400 Bad Request
  7507. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7508. EXPECT_EQ("close", res->get_header_value("Connection"));
  7509. }
  7510. EXPECT_FALSE(cli_.is_socket_open());
  7511. }
  7512. TEST_F(ServerTest, MultipartFormData) {
  7513. UploadFormDataItems items = {
  7514. {"text1", "text default", "", ""},
  7515. {"text2", "aωb", "", ""},
  7516. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7517. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  7518. {"file3", "", "", "application/octet-stream"},
  7519. {"file4", "", "", " application/json tmp-string "}};
  7520. auto res = cli_.Post("/multipart", items);
  7521. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7522. EXPECT_EQ(StatusCode::OK_200, res->status);
  7523. }
  7524. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  7525. UploadFormDataItems items = {
  7526. {"text", "default text", "", ""},
  7527. {"multi_text1", "aaaaa", "", ""},
  7528. {"multi_text1", "bbbbb", "", ""},
  7529. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7530. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  7531. "application/json"},
  7532. };
  7533. auto res = cli_.Post("/multipart/multi_file_values", items);
  7534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7535. EXPECT_EQ(StatusCode::OK_200, res->status);
  7536. }
  7537. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  7538. auto res = cli_.Get("/hi");
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_EQ(StatusCode::OK_200, res->status);
  7541. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  7542. EXPECT_EQ("Hello World!", res->body);
  7543. }
  7544. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  7545. Request req;
  7546. req.method = "POST";
  7547. req.path = "/chunked";
  7548. std::string host_and_port;
  7549. host_and_port += HOST;
  7550. host_and_port += ":";
  7551. host_and_port += std::to_string(PORT);
  7552. req.headers.emplace("Host", host_and_port.c_str());
  7553. req.headers.emplace("Accept", "*/*");
  7554. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7555. req.headers.emplace("Content-Type", "text/plain");
  7556. req.headers.emplace("Content-Length", "0");
  7557. req.headers.emplace(
  7558. "Transfer-Encoding",
  7559. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  7560. // Client does not chunk, so make a chunked body manually.
  7561. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  7562. auto res = std::make_shared<Response>();
  7563. auto error = Error::Success;
  7564. auto ret = cli_.send(req, *res, error);
  7565. ASSERT_TRUE(ret);
  7566. EXPECT_EQ(StatusCode::OK_200, res->status);
  7567. }
  7568. template <typename ClientT>
  7569. static void expect_chunked_body_status(ClientT &cli, const char *body,
  7570. int expected_status) {
  7571. Request req;
  7572. req.method = "POST";
  7573. req.path = "/chunked";
  7574. std::string host_and_port;
  7575. host_and_port += HOST;
  7576. host_and_port += ":";
  7577. host_and_port += std::to_string(PORT);
  7578. req.headers.emplace("Host", host_and_port.c_str());
  7579. req.headers.emplace("Content-Length", "0");
  7580. req.headers.emplace("Transfer-Encoding", "chunked");
  7581. req.body = body;
  7582. auto res = std::make_shared<Response>();
  7583. auto error = Error::Success;
  7584. ASSERT_TRUE(cli.send(req, *res, error));
  7585. EXPECT_EQ(expected_status, res->status);
  7586. }
  7587. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  7588. // rather than treat them as valid lengths.
  7589. template <typename ClientT>
  7590. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  7591. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  7592. }
  7593. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  7594. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  7595. }
  7596. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  7597. expect_chunked_body_rejected(
  7598. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7599. }
  7600. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  7601. // chunk-size line carries no CR, LF or other control character ahead of its
  7602. // terminator. Such a line must be refused rather than read as extension text.
  7603. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  7604. expect_chunked_body_rejected(
  7605. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7606. }
  7607. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  7608. expect_chunked_body_rejected(
  7609. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7610. }
  7611. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  7612. expect_chunked_body_rejected(
  7613. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7614. }
  7615. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  7616. // The literal stays split: a hex escape consumes every hex digit that
  7617. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  7618. expect_chunked_body_rejected(
  7619. cli_, "4;a\x01"
  7620. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  7621. }
  7622. // The bytes around chunk data are no payload, so they cannot ride on the
  7623. // payload limit
  7624. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  7625. // Small enough that the whole request is sent before the server turns it
  7626. // down, yet past the limit by the last chunks
  7627. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  7628. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  7629. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  7630. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  7631. SCOPED_TRACE(size_line.substr(0, 2));
  7632. std::string body;
  7633. for (auto c : std::string("dechunked post body")) {
  7634. body += size_line + "\r\n" + c + "\r\n";
  7635. }
  7636. body += "0\r\n\r\n";
  7637. expect_chunked_body_rejected(cli_, body.c_str());
  7638. }
  7639. }
  7640. TEST_F(ServerTest, AcceptsChunkExtension) {
  7641. expect_chunked_body_status(cli_,
  7642. "4;name=value\r\ndech\r\n"
  7643. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  7644. "0;last\r\n\r\n",
  7645. StatusCode::OK_200);
  7646. }
  7647. TEST_F(ServerTest, GetStreamed2) {
  7648. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  7649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7650. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7651. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7652. EXPECT_EQ(true, res->has_header("Content-Range"));
  7653. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  7654. EXPECT_EQ(std::string("ab"), res->body);
  7655. }
  7656. TEST_F(ServerTest, GetStreamed) {
  7657. auto res = cli_.Get("/streamed");
  7658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7659. EXPECT_EQ(StatusCode::OK_200, res->status);
  7660. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7661. EXPECT_EQ(std::string("aaabbb"), res->body);
  7662. }
  7663. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  7664. auto res = cli_.Get("/streamed-without-length",
  7665. Headers{make_range_header({{0, -1}})});
  7666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7667. EXPECT_EQ(StatusCode::OK_200, res->status);
  7668. EXPECT_EQ(false, res->has_header("Content-Length"));
  7669. EXPECT_EQ(false, res->has_header("Content-Range"));
  7670. EXPECT_EQ(std::string("abcdefg"), res->body);
  7671. }
  7672. TEST_F(ServerTest, GetStreamedWithRange1) {
  7673. auto res =
  7674. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  7675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7676. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7677. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7678. EXPECT_EQ(true, res->has_header("Content-Range"));
  7679. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7680. EXPECT_EQ(std::string("def"), res->body);
  7681. }
  7682. TEST_F(ServerTest, GetStreamedWithRange2) {
  7683. auto res =
  7684. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  7685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7686. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7687. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7688. EXPECT_EQ(true, res->has_header("Content-Range"));
  7689. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7690. EXPECT_EQ(std::string("bcdefg"), res->body);
  7691. }
  7692. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  7693. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  7694. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7695. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7696. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7697. EXPECT_EQ(true, res->has_header("Content-Range"));
  7698. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  7699. EXPECT_EQ(std::string("efg"), res->body);
  7700. }
  7701. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  7702. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  7703. // the entire representation.
  7704. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  7705. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  7706. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7707. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  7708. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  7709. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  7710. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  7711. }
  7712. }
  7713. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  7714. auto res =
  7715. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  7716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7717. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7718. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7719. EXPECT_EQ(false, res->has_header("Content-Range"));
  7720. EXPECT_EQ(0U, res->body.size());
  7721. }
  7722. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7723. // Only a 206 is served as a partial representation. Under any other status
  7724. // `apply_ranges()` reported the full content length, so the body must match
  7725. // that header, and the content provider must never be asked for an offset
  7726. // outside the representation.
  7727. auto check = [&](int status, const char *range) {
  7728. auto path =
  7729. std::string("/streamed-with-range?status=") + std::to_string(status);
  7730. auto ctx = path + " Range: " + range;
  7731. auto res = cli_.Get(path, Headers{{"Range", range}});
  7732. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7733. EXPECT_EQ(status, res->status) << ctx;
  7734. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7735. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7736. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7737. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7738. };
  7739. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7740. check(403, "bytes=3-5");
  7741. // The offset is far past the representation.
  7742. check(403, "bytes=100000-100200");
  7743. // `first_pos` is still -1 here, and the bounds asserts in
  7744. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7745. check(403, "bytes=-3");
  7746. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7747. // multipart branch would have written one that is empty.
  7748. check(403, "bytes=1-2, 4-5");
  7749. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7750. // covers the whole representation.
  7751. check(200, "bytes=3-5");
  7752. check(200, "bytes=1-2, 4-5");
  7753. }
  7754. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7755. auto res =
  7756. cli_.Get("/streamed-with-range",
  7757. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7758. "92233720368547758079223372036854775807"}});
  7759. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7760. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7761. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7762. EXPECT_EQ(false, res->has_header("Content-Range"));
  7763. EXPECT_EQ(0U, res->body.size());
  7764. }
  7765. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7766. auto res = cli_.Get(
  7767. "/with-range",
  7768. Headers{{"Range",
  7769. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7770. {"Accept-Encoding", ""}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7773. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7774. EXPECT_EQ(true, res->has_header("Content-Range"));
  7775. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7776. EXPECT_EQ(std::string("abcdefg"), res->body);
  7777. }
  7778. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7779. auto res = cli_.Get("/with-range", Headers{
  7780. {"Range", "bytes=0-"},
  7781. {"Accept-Encoding", ""},
  7782. });
  7783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7784. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7785. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7786. EXPECT_EQ(true, res->has_header("Content-Range"));
  7787. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7788. EXPECT_EQ(std::string("abcdefg"), res->body);
  7789. }
  7790. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7791. auto res = cli_.Get("/streamed-with-range",
  7792. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7795. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7796. EXPECT_EQ(false, res->has_header("Content-Range"));
  7797. EXPECT_EQ(267U, res->body.size());
  7798. // Check that both range contents are present
  7799. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7800. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7801. // Check that Content-Range headers are present for both ranges
  7802. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7803. std::string::npos);
  7804. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7805. std::string::npos);
  7806. }
  7807. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7808. Ranges ranges;
  7809. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7810. ranges.emplace_back(0, -1);
  7811. }
  7812. auto res = cli_.Get("/streamed-with-range?error",
  7813. Headers{{make_range_header(ranges)}});
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7816. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7817. EXPECT_EQ(false, res->has_header("Content-Range"));
  7818. EXPECT_EQ(0U, res->body.size());
  7819. }
  7820. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7821. auto res = cli_.Get("/streamed-with-range",
  7822. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7824. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7825. EXPECT_EQ(5U, res->body.size());
  7826. // Check that overlapping ranges are coalesced into a single range
  7827. EXPECT_EQ("bcdef", res->body);
  7828. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7829. // Should be single range, not multipart
  7830. EXPECT_TRUE(res->has_header("Content-Range"));
  7831. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7832. }
  7833. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7834. auto res = cli_.Get("/streamed-with-range",
  7835. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7837. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7838. EXPECT_EQ(268U, res->body.size());
  7839. // Check that both range contents are present
  7840. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7841. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7842. // Check that Content-Range headers are present for both ranges
  7843. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7844. std::string::npos);
  7845. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7846. std::string::npos);
  7847. }
  7848. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7849. auto res = cli_.Get("/streamed-with-range",
  7850. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7851. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7852. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7853. EXPECT_EQ(269U, res->body.size());
  7854. // Check that both duplicate range contents are present
  7855. size_t first_abc = res->body.find("abc\r\n");
  7856. EXPECT_TRUE(first_abc != std::string::npos);
  7857. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7858. EXPECT_TRUE(second_abc != std::string::npos);
  7859. // Check that Content-Range headers are present for both ranges
  7860. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7861. EXPECT_TRUE(first_range != std::string::npos);
  7862. size_t second_range =
  7863. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7864. EXPECT_TRUE(second_range != std::string::npos);
  7865. }
  7866. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7867. auto res =
  7868. cli_.Get("/streamed-with-range?error",
  7869. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7870. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7871. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7872. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7873. EXPECT_EQ(false, res->has_header("Content-Range"));
  7874. EXPECT_EQ(0U, res->body.size());
  7875. }
  7876. TEST_F(ServerTest, GetStreamedEndless) {
  7877. uint64_t offset = 0;
  7878. auto res = cli_.Get("/streamed-cancel",
  7879. [&](const char * /*data*/, uint64_t data_length) {
  7880. if (offset < 100) {
  7881. offset += data_length;
  7882. return true;
  7883. }
  7884. return false;
  7885. });
  7886. ASSERT_TRUE(!res);
  7887. EXPECT_EQ(Error::Canceled, res.error());
  7888. }
  7889. TEST_F(ServerTest, ClientStop) {
  7890. std::atomic_size_t count{4};
  7891. std::vector<std::thread> threads;
  7892. for (auto i = count.load(); i != 0; --i) {
  7893. threads.emplace_back([&]() {
  7894. auto res = cli_.Get("/streamed-cancel",
  7895. [&](const char *, uint64_t) { return true; });
  7896. --count;
  7897. ASSERT_TRUE(!res);
  7898. EXPECT_TRUE(res.error() == Error::Canceled ||
  7899. res.error() == Error::Read || res.error() == Error::Write);
  7900. });
  7901. }
  7902. std::this_thread::sleep_for(std::chrono::seconds(2));
  7903. while (count != 0) {
  7904. cli_.stop();
  7905. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7906. }
  7907. for (auto &t : threads) {
  7908. t.join();
  7909. }
  7910. }
  7911. TEST_F(ServerTest, GetWithRange1) {
  7912. auto res = cli_.Get("/with-range", Headers{
  7913. make_range_header({{3, 5}}),
  7914. {"Accept-Encoding", ""},
  7915. });
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7918. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7919. EXPECT_EQ(true, res->has_header("Content-Range"));
  7920. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7921. EXPECT_EQ(std::string("def"), res->body);
  7922. }
  7923. TEST_F(ServerTest, GetWithRange2) {
  7924. auto res = cli_.Get("/with-range", Headers{
  7925. make_range_header({{1, -1}}),
  7926. {"Accept-Encoding", ""},
  7927. });
  7928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7930. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7931. EXPECT_EQ(true, res->has_header("Content-Range"));
  7932. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7933. EXPECT_EQ(std::string("bcdefg"), res->body);
  7934. }
  7935. TEST_F(ServerTest, GetWithRange3) {
  7936. auto res = cli_.Get("/with-range", Headers{
  7937. make_range_header({{0, 0}}),
  7938. {"Accept-Encoding", ""},
  7939. });
  7940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7941. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7942. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7943. EXPECT_EQ(true, res->has_header("Content-Range"));
  7944. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7945. EXPECT_EQ(std::string("a"), res->body);
  7946. }
  7947. TEST_F(ServerTest, GetWithRange4) {
  7948. auto res = cli_.Get("/with-range", Headers{
  7949. make_range_header({{-1, 2}}),
  7950. {"Accept-Encoding", ""},
  7951. });
  7952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7953. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7954. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7955. EXPECT_EQ(true, res->has_header("Content-Range"));
  7956. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7957. EXPECT_EQ(std::string("fg"), res->body);
  7958. }
  7959. TEST_F(ServerTest, GetWithRange5) {
  7960. auto res = cli_.Get("/with-range", Headers{
  7961. make_range_header({{0, 5}}),
  7962. {"Accept-Encoding", ""},
  7963. });
  7964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7965. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7967. EXPECT_EQ(true, res->has_header("Content-Range"));
  7968. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7969. EXPECT_EQ(std::string("abcdef"), res->body);
  7970. }
  7971. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7972. auto res =
  7973. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7974. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7975. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7976. }
  7977. TEST_F(ServerTest, GetWithRangeMultipart) {
  7978. auto res =
  7979. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7981. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7982. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7983. EXPECT_EQ(false, res->has_header("Content-Range"));
  7984. EXPECT_EQ(267U, res->body.size());
  7985. }
  7986. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7987. auto res = cli_.Get("/with-range",
  7988. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7989. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7990. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7991. }
  7992. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7993. auto res = cli_.Get("/with-range-customized-response",
  7994. Headers{{make_range_header({{1, 2}})}});
  7995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7996. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7997. EXPECT_EQ(true, res->has_header("Content-Length"));
  7998. EXPECT_EQ(false, res->has_header("Content-Range"));
  7999. EXPECT_EQ(JSON_DATA, res->body);
  8000. }
  8001. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  8002. auto res = cli_.Get("/with-range-customized-response",
  8003. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  8004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8005. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8006. EXPECT_EQ(true, res->has_header("Content-Length"));
  8007. EXPECT_EQ(false, res->has_header("Content-Range"));
  8008. EXPECT_EQ(JSON_DATA, res->body);
  8009. }
  8010. TEST_F(ServerTest, Issue1772) {
  8011. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  8012. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8013. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  8014. }
  8015. TEST_F(ServerTest, Issue609) {
  8016. auto res = cli_.Delete("/issue609");
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(StatusCode::OK_200, res->status);
  8019. EXPECT_EQ(std::string("ok"), res->body);
  8020. }
  8021. TEST_F(ServerTest, GetStreamedChunked) {
  8022. auto res = cli_.Get("/streamed-chunked");
  8023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. EXPECT_EQ(std::string("123456789"), res->body);
  8026. }
  8027. TEST_F(ServerTest, GetStreamedChunked2) {
  8028. auto res = cli_.Get("/streamed-chunked2");
  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, GetStreamedChunkedWithTrailer) {
  8034. auto res = cli_.Get("/streamed-chunked-with-trailer");
  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. EXPECT_TRUE(res->has_header("Trailer"));
  8039. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  8040. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  8041. // Trailers are now stored separately from headers (security fix)
  8042. EXPECT_EQ(2U, res->trailers.size());
  8043. EXPECT_TRUE(res->has_trailer("Dummy1"));
  8044. EXPECT_TRUE(res->has_trailer("Dummy2"));
  8045. EXPECT_FALSE(res->has_trailer("Dummy3"));
  8046. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  8047. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  8048. // Verify trailers are NOT in headers (security verification)
  8049. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  8050. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  8051. }
  8052. TEST_F(ServerTest, LargeChunkedPost) {
  8053. Request req;
  8054. req.method = "POST";
  8055. req.path = "/large-chunked";
  8056. std::string host_and_port;
  8057. host_and_port += HOST;
  8058. host_and_port += ":";
  8059. host_and_port += std::to_string(PORT);
  8060. req.headers.emplace("Host", host_and_port.c_str());
  8061. req.headers.emplace("Accept", "*/*");
  8062. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  8063. req.headers.emplace("Content-Type", "text/plain");
  8064. req.headers.emplace("Content-Length", "0");
  8065. req.headers.emplace("Transfer-Encoding", "chunked");
  8066. std::string long_string(30 * 1024u, 'a');
  8067. std::string chunk = "7800\r\n" + long_string + "\r\n";
  8068. // Attempt to make a large enough post to exceed OS buffers, to test that
  8069. // the server handles short reads if the full chunk data isn't available.
  8070. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  8071. auto res = std::make_shared<Response>();
  8072. auto error = Error::Success;
  8073. auto ret = cli_.send(req, *res, error);
  8074. ASSERT_TRUE(ret);
  8075. EXPECT_EQ(StatusCode::OK_200, res->status);
  8076. }
  8077. TEST_F(ServerTest, GetMethodRemoteAddr) {
  8078. auto res = cli_.Get("/remote_addr");
  8079. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8080. EXPECT_EQ(StatusCode::OK_200, res->status);
  8081. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8082. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  8083. }
  8084. TEST_F(ServerTest, GetMethodLocalAddr) {
  8085. auto res = cli_.Get("/local_addr");
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::OK_200, res->status);
  8088. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8089. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  8090. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  8091. }
  8092. TEST_F(ServerTest, HTTPResponseSplitting) {
  8093. auto res = cli_.Get("/http_response_splitting");
  8094. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8095. EXPECT_EQ(StatusCode::OK_200, res->status);
  8096. }
  8097. TEST_F(ServerTest, SlowRequest) {
  8098. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8099. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8100. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  8101. }
  8102. #if 0
  8103. TEST_F(ServerTest, SlowPost) {
  8104. char buffer[64 * 1024];
  8105. memset(buffer, 0x42, sizeof(buffer));
  8106. auto res = cli_.Post(
  8107. "/slowpost", 64 * 1024 * 1024,
  8108. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8109. auto ret = sink.write(buffer, sizeof(buffer));
  8110. EXPECT_TRUE(ret);
  8111. return true;
  8112. },
  8113. "text/plain");
  8114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8115. EXPECT_EQ(StatusCode::OK_200, res->status);
  8116. }
  8117. TEST_F(ServerTest, SlowPostFail) {
  8118. char buffer[64 * 1024];
  8119. memset(buffer, 0x42, sizeof(buffer));
  8120. cli_.set_write_timeout(std::chrono::seconds(0));
  8121. auto res = cli_.Post(
  8122. "/slowpost", 64 * 1024 * 1024,
  8123. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8124. sink.write(buffer, sizeof(buffer));
  8125. return true;
  8126. },
  8127. "text/plain");
  8128. ASSERT_TRUE(!res);
  8129. EXPECT_EQ(Error::Write, res.error());
  8130. }
  8131. #endif
  8132. TEST_F(ServerTest, Put) {
  8133. auto res = cli_.Put("/put", "PUT", "text/plain");
  8134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8135. EXPECT_EQ(StatusCode::OK_200, res->status);
  8136. EXPECT_EQ("PUT", res->body);
  8137. }
  8138. TEST_F(ServerTest, PutWithContentProvider) {
  8139. auto res = cli_.Put(
  8140. "/put", 3,
  8141. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8142. sink.os << "PUT";
  8143. return true;
  8144. },
  8145. "text/plain");
  8146. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8147. EXPECT_EQ(StatusCode::OK_200, res->status);
  8148. EXPECT_EQ("PUT", res->body);
  8149. }
  8150. TEST_F(ServerTest, PostWithContentProviderAbort) {
  8151. auto res = cli_.Post(
  8152. "/post", 42,
  8153. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8154. return false;
  8155. },
  8156. "text/plain");
  8157. ASSERT_TRUE(!res);
  8158. EXPECT_EQ(Error::Canceled, res.error());
  8159. }
  8160. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  8161. auto res = cli_.Put(
  8162. "/put",
  8163. [](size_t /*offset*/, DataSink &sink) {
  8164. sink.os << "PUT";
  8165. sink.done();
  8166. return true;
  8167. },
  8168. "text/plain");
  8169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8170. EXPECT_EQ(StatusCode::OK_200, res->status);
  8171. EXPECT_EQ("PUT", res->body);
  8172. }
  8173. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  8174. auto res = cli_.Post(
  8175. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8176. "text/plain");
  8177. ASSERT_TRUE(!res);
  8178. EXPECT_EQ(Error::Canceled, res.error());
  8179. }
  8180. TEST_F(ServerTest, PostLoopBack) {
  8181. std::string body;
  8182. auto res = cli_.Post(
  8183. "/post-loopback", 9,
  8184. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8185. EXPECT_EQ(9u, length);
  8186. sink.write("123", 3);
  8187. sink.write("456", 3);
  8188. sink.write("789", 3);
  8189. return true;
  8190. },
  8191. "text/plain",
  8192. [&body](const char *data, size_t data_length) {
  8193. body.append(data, data_length);
  8194. return true;
  8195. });
  8196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8197. EXPECT_EQ(StatusCode::OK_200, res->status);
  8198. EXPECT_EQ("123456789", body);
  8199. }
  8200. TEST_F(ServerTest, PutLoopBack) {
  8201. std::string body;
  8202. auto res = cli_.Put(
  8203. "/put-loopback", 9,
  8204. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8205. EXPECT_EQ(9u, length);
  8206. sink.write("123", 3);
  8207. sink.write("456", 3);
  8208. sink.write("789", 3);
  8209. return true;
  8210. },
  8211. "text/plain",
  8212. [&body](const char *data, size_t data_length) {
  8213. body.append(data, data_length);
  8214. return true;
  8215. });
  8216. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8217. EXPECT_EQ(StatusCode::OK_200, res->status);
  8218. EXPECT_EQ("123456789", body);
  8219. }
  8220. TEST_F(ServerTest, PatchLoopBack) {
  8221. std::string body;
  8222. auto res = cli_.Patch(
  8223. "/patch-loopback", 9,
  8224. [](size_t /*offset*/, size_t length, DataSink &sink) {
  8225. EXPECT_EQ(9u, length);
  8226. sink.write("123", 3);
  8227. sink.write("456", 3);
  8228. sink.write("789", 3);
  8229. return true;
  8230. },
  8231. "text/plain",
  8232. [&body](const char *data, size_t data_length) {
  8233. body.append(data, data_length);
  8234. return true;
  8235. });
  8236. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8237. EXPECT_EQ(StatusCode::OK_200, res->status);
  8238. EXPECT_EQ("123456789", body);
  8239. }
  8240. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  8241. std::string body;
  8242. auto res = cli_.Post(
  8243. "/post-loopback",
  8244. [](size_t /*offset*/, DataSink &sink) {
  8245. sink.write("123", 3);
  8246. sink.write("456", 3);
  8247. sink.write("789", 3);
  8248. sink.done();
  8249. return true;
  8250. },
  8251. "text/plain",
  8252. [&body](const char *data, size_t data_length) {
  8253. body.append(data, data_length);
  8254. return true;
  8255. });
  8256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8257. EXPECT_EQ(StatusCode::OK_200, res->status);
  8258. EXPECT_EQ("123456789", body);
  8259. }
  8260. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8261. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  8262. cli_.set_compress(true);
  8263. auto res = cli_.Put(
  8264. "/put", 3,
  8265. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8266. sink.os << "PUT";
  8267. return true;
  8268. },
  8269. "text/plain");
  8270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8271. EXPECT_EQ(StatusCode::OK_200, res->status);
  8272. EXPECT_EQ("PUT", res->body);
  8273. }
  8274. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  8275. cli_.set_compress(true);
  8276. auto res = cli_.Post(
  8277. "/post", 42,
  8278. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  8279. return false;
  8280. },
  8281. "text/plain");
  8282. ASSERT_TRUE(!res);
  8283. EXPECT_EQ(Error::Canceled, res.error());
  8284. }
  8285. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  8286. cli_.set_compress(true);
  8287. auto res = cli_.Put(
  8288. "/put",
  8289. [](size_t /*offset*/, DataSink &sink) {
  8290. sink.os << "PUT";
  8291. sink.done();
  8292. return true;
  8293. },
  8294. "text/plain");
  8295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8296. EXPECT_EQ(StatusCode::OK_200, res->status);
  8297. EXPECT_EQ("PUT", res->body);
  8298. }
  8299. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  8300. cli_.set_compress(true);
  8301. auto res = cli_.Post(
  8302. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  8303. "text/plain");
  8304. ASSERT_TRUE(!res);
  8305. EXPECT_EQ(Error::Canceled, res.error());
  8306. }
  8307. TEST_F(ServerTest, PutLargeFileWithGzip) {
  8308. cli_.set_compress(true);
  8309. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8311. EXPECT_EQ(StatusCode::OK_200, res->status);
  8312. EXPECT_EQ(LARGE_DATA, res->body);
  8313. }
  8314. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  8315. #ifdef CPPHTTPLIB_SSL_ENABLED
  8316. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  8317. Client cli(s.c_str());
  8318. cli.enable_server_certificate_verification(false);
  8319. #else
  8320. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  8321. Client cli(s.c_str());
  8322. #endif
  8323. cli.set_compress(true);
  8324. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  8325. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8326. EXPECT_EQ(StatusCode::OK_200, res->status);
  8327. EXPECT_EQ(LARGE_DATA, res->body);
  8328. // The compressed size should be less than a 10th of the original. May vary
  8329. // depending on the zlib library.
  8330. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  8331. static_cast<uint64_t>(10 * 1024 * 1024));
  8332. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8333. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8334. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  8335. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  8336. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  8337. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  8338. #endif
  8339. }
  8340. TEST_F(ServerTest, PutContentWithDeflate) {
  8341. cli_.set_compress(false);
  8342. Headers headers;
  8343. headers.emplace("Content-Encoding", "deflate");
  8344. // PUT in deflate format:
  8345. auto res = cli_.Put("/put", headers,
  8346. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  8347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8348. EXPECT_EQ(StatusCode::OK_200, res->status);
  8349. EXPECT_EQ("PUT", res->body);
  8350. }
  8351. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  8352. Headers headers;
  8353. headers.emplace("Accept-Encoding", "gzip, deflate");
  8354. auto res = cli_.Get("/streamed-chunked", headers);
  8355. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8356. EXPECT_EQ(StatusCode::OK_200, res->status);
  8357. EXPECT_EQ(std::string("123456789"), res->body);
  8358. }
  8359. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  8360. Headers headers;
  8361. headers.emplace("Accept-Encoding", "gzip, deflate");
  8362. auto res = cli_.Get("/streamed-chunked2", headers);
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ(StatusCode::OK_200, res->status);
  8365. EXPECT_EQ(std::string("123456789"), res->body);
  8366. }
  8367. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  8368. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  8369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8370. EXPECT_EQ(StatusCode::OK_200, res->status);
  8371. }
  8372. TEST(GzipDecompressor, ChunkedDecompression) {
  8373. std::string data;
  8374. for (size_t i = 0; i < 32 * 1024; ++i) {
  8375. data.push_back(static_cast<char>('a' + i % 26));
  8376. }
  8377. std::string compressed_data;
  8378. {
  8379. httplib::detail::gzip_compressor compressor;
  8380. bool result = compressor.compress(
  8381. data.data(), data.size(),
  8382. /*last=*/true,
  8383. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8384. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8385. compressed_data_size);
  8386. return true;
  8387. });
  8388. ASSERT_TRUE(result);
  8389. }
  8390. std::string decompressed_data;
  8391. {
  8392. httplib::detail::gzip_decompressor decompressor;
  8393. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8394. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8395. size_t chunk_size = 130;
  8396. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8397. chunk_begin += chunk_size) {
  8398. size_t current_chunk_size =
  8399. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8400. bool result = decompressor.decompress(
  8401. compressed_data.data() + chunk_begin, current_chunk_size,
  8402. [&](const char *decompressed_data_chunk,
  8403. size_t decompressed_data_chunk_size) {
  8404. decompressed_data.insert(decompressed_data.size(),
  8405. decompressed_data_chunk,
  8406. decompressed_data_chunk_size);
  8407. return true;
  8408. });
  8409. ASSERT_TRUE(result);
  8410. }
  8411. }
  8412. ASSERT_EQ(data, decompressed_data);
  8413. }
  8414. TEST(GzipDecompressor, DeflateDecompression) {
  8415. std::string original_text = "Raw deflate without gzip";
  8416. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8417. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8418. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8419. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  8420. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8421. std::string decompressed_data;
  8422. {
  8423. httplib::detail::gzip_decompressor decompressor;
  8424. bool result = decompressor.decompress(
  8425. compressed_data.data(), compressed_data.size(),
  8426. [&](const char *decompressed_data_chunk,
  8427. size_t decompressed_data_chunk_size) {
  8428. decompressed_data.insert(decompressed_data.size(),
  8429. decompressed_data_chunk,
  8430. decompressed_data_chunk_size);
  8431. return true;
  8432. });
  8433. ASSERT_TRUE(result);
  8434. }
  8435. ASSERT_EQ(original_text, decompressed_data);
  8436. }
  8437. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  8438. std::string original_text = "Raw deflate without gzip";
  8439. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  8440. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  8441. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  8442. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  8443. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  8444. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8445. std::string decompressed_data;
  8446. {
  8447. httplib::detail::gzip_decompressor decompressor;
  8448. bool result = decompressor.decompress(
  8449. compressed_data.data(), compressed_data.size(),
  8450. [&](const char *decompressed_data_chunk,
  8451. size_t decompressed_data_chunk_size) {
  8452. decompressed_data.insert(decompressed_data.size(),
  8453. decompressed_data_chunk,
  8454. decompressed_data_chunk_size);
  8455. return true;
  8456. });
  8457. ASSERT_TRUE(result);
  8458. }
  8459. ASSERT_EQ(original_text, decompressed_data);
  8460. }
  8461. #endif
  8462. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8463. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  8464. Headers headers;
  8465. headers.emplace("Accept-Encoding", "br");
  8466. auto res = cli_.Get("/streamed-chunked", headers);
  8467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8468. EXPECT_EQ(StatusCode::OK_200, res->status);
  8469. EXPECT_EQ(std::string("123456789"), res->body);
  8470. }
  8471. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  8472. Headers headers;
  8473. headers.emplace("Accept-Encoding", "br");
  8474. auto res = cli_.Get("/streamed-chunked2", headers);
  8475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8476. EXPECT_EQ(StatusCode::OK_200, res->status);
  8477. EXPECT_EQ(std::string("123456789"), res->body);
  8478. }
  8479. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  8480. cli_.set_compress(true);
  8481. auto res = cli_.Put(
  8482. "/put", 3,
  8483. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8484. sink.os << "PUT";
  8485. return true;
  8486. },
  8487. "text/plain");
  8488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8489. EXPECT_EQ(StatusCode::OK_200, res->status);
  8490. EXPECT_EQ("PUT", res->body);
  8491. }
  8492. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  8493. cli_.set_compress(true);
  8494. auto res = cli_.Put(
  8495. "/put",
  8496. [](size_t /*offset*/, DataSink &sink) {
  8497. sink.os << "PUT";
  8498. sink.done();
  8499. return true;
  8500. },
  8501. "text/plain");
  8502. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8503. EXPECT_EQ(StatusCode::OK_200, res->status);
  8504. EXPECT_EQ("PUT", res->body);
  8505. }
  8506. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  8507. cli_.set_compress(true);
  8508. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  8509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8510. EXPECT_EQ(StatusCode::OK_200, res->status);
  8511. EXPECT_EQ(LARGE_DATA, res->body);
  8512. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  8513. }
  8514. #endif
  8515. TEST_F(ServerTest, Patch) {
  8516. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(StatusCode::OK_200, res->status);
  8519. EXPECT_EQ("PATCH", res->body);
  8520. }
  8521. TEST_F(ServerTest, Delete) {
  8522. auto res = cli_.Delete("/delete");
  8523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8524. EXPECT_EQ(StatusCode::OK_200, res->status);
  8525. EXPECT_EQ("DELETE", res->body);
  8526. }
  8527. TEST_F(ServerTest, DeleteContentReceiver) {
  8528. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  8529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8530. EXPECT_EQ(StatusCode::OK_200, res->status);
  8531. EXPECT_EQ("content", res->body);
  8532. }
  8533. TEST_F(ServerTest, Options) {
  8534. auto res = cli_.Options("*");
  8535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8536. EXPECT_EQ(StatusCode::OK_200, res->status);
  8537. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  8538. EXPECT_TRUE(res->body.empty());
  8539. }
  8540. TEST_F(ServerTest, URL) {
  8541. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  8542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8543. EXPECT_EQ(StatusCode::OK_200, res->status);
  8544. }
  8545. TEST_F(ServerTest, ArrayParam) {
  8546. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  8547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8548. EXPECT_EQ(StatusCode::OK_200, res->status);
  8549. }
  8550. TEST_F(ServerTest, ArrayParamValues) {
  8551. auto res =
  8552. cli_.Get("/array-param-values?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, NoMultipleHeaders) {
  8557. Headers headers = {{"Content-Length", "5"}};
  8558. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  8559. "text/plain");
  8560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8561. EXPECT_EQ(StatusCode::OK_200, res->status);
  8562. }
  8563. TEST_F(ServerTest, PostContentReceiver) {
  8564. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8565. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8566. ASSERT_EQ(StatusCode::OK_200, res->status);
  8567. ASSERT_EQ("content", res->body);
  8568. }
  8569. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  8570. UploadFormDataItems items = {
  8571. {"text1", "text default", "", ""},
  8572. {"text2", "aωb", "", ""},
  8573. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8574. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8575. {"file3", "", "", "application/octet-stream"},
  8576. };
  8577. auto res = cli_.Post("/content_receiver", items);
  8578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8579. EXPECT_EQ(StatusCode::OK_200, res->status);
  8580. }
  8581. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  8582. UploadFormDataItems items = {
  8583. {"text1", "text default", "", ""},
  8584. {"text2", "aωb", "", ""},
  8585. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  8586. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  8587. {"file3", "", "", "application/octet-stream"},
  8588. };
  8589. auto boundary = std::string("+++++");
  8590. std::string body;
  8591. for (const auto &item : items) {
  8592. body += "--" + boundary + "\r\n";
  8593. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  8594. if (!item.filename.empty()) {
  8595. body += "; filename=\"" + item.filename + "\"";
  8596. }
  8597. body += "\r\n";
  8598. if (!item.content_type.empty()) {
  8599. body += "Content-Type: " + item.content_type + "\r\n";
  8600. }
  8601. body += "\r\n";
  8602. body += item.content + "\r\n";
  8603. }
  8604. body += "--" + boundary + "--\r\n";
  8605. std::string content_type = "multipart/form-data; boundary=" + boundary;
  8606. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  8607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8608. EXPECT_EQ(StatusCode::OK_200, res->status);
  8609. }
  8610. TEST(MultipartFormDataTest, FieldEscaping) {
  8611. Server svr;
  8612. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8613. const ContentReader &content_reader) {
  8614. ASSERT_TRUE(req.is_multipart_form_data());
  8615. std::vector<FormData> received;
  8616. content_reader(
  8617. [&](const FormData &file) {
  8618. received.push_back(file);
  8619. return true;
  8620. },
  8621. [&](const char *data, size_t data_length) {
  8622. received.back().content.append(data, data_length);
  8623. return true;
  8624. });
  8625. // '"', CR and LF in names and filenames are escaped following the
  8626. // WHATWG HTML standard, so each part still parses as a single part
  8627. // with no injected headers. Content types get CR/LF escaped too,
  8628. // while '"' (legal there, e.g. quoted charset) is preserved.
  8629. ASSERT_EQ(4U, received.size());
  8630. EXPECT_EQ("na%22me", received[0].name);
  8631. EXPECT_EQ("quoted name", received[0].content);
  8632. EXPECT_EQ("file", received[1].name);
  8633. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  8634. received[1].filename);
  8635. EXPECT_EQ("application/octet-stream", received[1].content_type);
  8636. EXPECT_EQ("injected", received[1].content);
  8637. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  8638. EXPECT_EQ("my%22file.txt", received[2].filename);
  8639. EXPECT_EQ("cr lf name", received[2].content);
  8640. EXPECT_EQ("typed", received[3].name);
  8641. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  8642. received[3].content_type);
  8643. EXPECT_EQ("typed content", received[3].content);
  8644. });
  8645. auto port = svr.bind_to_any_port("localhost");
  8646. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8647. auto se = detail::scope_exit([&] {
  8648. svr.stop();
  8649. t.join();
  8650. ASSERT_FALSE(svr.is_running());
  8651. });
  8652. svr.wait_until_ready();
  8653. Client cli("localhost", port);
  8654. UploadFormDataItems items = {
  8655. {"na\"me", "quoted name", "", ""},
  8656. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  8657. "application/octet-stream"},
  8658. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  8659. {"typed", "typed content", "",
  8660. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  8661. };
  8662. auto res = cli.Post("/post", items);
  8663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8664. EXPECT_EQ(StatusCode::OK_200, res->status);
  8665. }
  8666. TEST(MultipartFormDataTest, PublicWriterAPI) {
  8667. const UploadFormDataItems items = {
  8668. {"name1", "Content 1", "", ""},
  8669. {"name2", "Content 2", "file2.txt", "text/plain"},
  8670. };
  8671. Server svr;
  8672. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  8673. const ContentReader &content_reader) {
  8674. ASSERT_TRUE(req.is_multipart_form_data());
  8675. std::vector<FormData> received;
  8676. content_reader(
  8677. [&](const FormData &file) {
  8678. received.push_back(file);
  8679. return true;
  8680. },
  8681. [&](const char *data, size_t data_length) {
  8682. received.back().content.append(data, data_length);
  8683. return true;
  8684. });
  8685. ASSERT_EQ(2U, received.size());
  8686. EXPECT_EQ("name1", received[0].name);
  8687. EXPECT_EQ("Content 1", received[0].content);
  8688. EXPECT_EQ("name2", received[1].name);
  8689. EXPECT_EQ("Content 2", received[1].content);
  8690. EXPECT_EQ("file2.txt", received[1].filename);
  8691. EXPECT_EQ("text/plain", received[1].content_type);
  8692. });
  8693. auto port = svr.bind_to_any_port("localhost");
  8694. auto t = std::thread([&]() { svr.listen_after_bind(); });
  8695. auto se = detail::scope_exit([&] {
  8696. svr.stop();
  8697. t.join();
  8698. ASSERT_FALSE(svr.is_running());
  8699. });
  8700. svr.wait_until_ready();
  8701. Client cli("localhost", port);
  8702. // Whole-body serialization with a generated boundary
  8703. {
  8704. MultipartFormDataWriter writer;
  8705. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  8706. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  8707. writer.content_type());
  8708. auto body = writer.serialize(items);
  8709. EXPECT_EQ(body.size(), writer.content_length(items));
  8710. auto res = cli.Post("/post", body, writer.content_type());
  8711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8712. EXPECT_EQ(StatusCode::OK_200, res->status);
  8713. }
  8714. // Per-part framing with a custom boundary via a content provider
  8715. {
  8716. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  8717. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  8718. MultipartFormDataWriter writer("custom-boundary_123");
  8719. EXPECT_EQ("custom-boundary_123", writer.boundary());
  8720. std::string body;
  8721. for (const auto &item : items) {
  8722. body += writer.item_begin(item);
  8723. body += item.content;
  8724. body += MultipartFormDataWriter::item_end();
  8725. }
  8726. body += writer.finish();
  8727. EXPECT_EQ(body.size(), writer.content_length(items));
  8728. auto res = cli.Post(
  8729. "/post", body.size(),
  8730. [&](size_t offset, size_t length, DataSink &sink) {
  8731. sink.write(body.data() + offset, length);
  8732. return true;
  8733. },
  8734. writer.content_type());
  8735. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8736. EXPECT_EQ(StatusCode::OK_200, res->status);
  8737. }
  8738. }
  8739. TEST_F(ServerTest, PostContentReceiverGzip) {
  8740. cli_.set_compress(true);
  8741. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8743. ASSERT_EQ(StatusCode::OK_200, res->status);
  8744. ASSERT_EQ("content", res->body);
  8745. }
  8746. TEST_F(ServerTest, PutContentReceiver) {
  8747. auto res = cli_.Put("/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, PatchContentReceiver) {
  8753. auto res = cli_.Patch("/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. template <typename ClientType>
  8759. void TestWithHeadersAndContentReceiver(
  8760. ClientType &cli,
  8761. std::function<Result(ClientType &, const std::string &, const Headers &,
  8762. const std::string &, const std::string &,
  8763. ContentReceiver, DownloadProgress)>
  8764. request_func) {
  8765. Headers headers;
  8766. headers.emplace("X-Custom-Header", "test-value");
  8767. std::string received_body;
  8768. auto res = request_func(
  8769. cli, "/content_receiver", headers, "content", "application/json",
  8770. [&](const char *data, size_t data_length) {
  8771. received_body.append(data, data_length);
  8772. return true;
  8773. },
  8774. nullptr);
  8775. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8776. EXPECT_EQ(StatusCode::OK_200, res->status);
  8777. EXPECT_EQ("content", received_body);
  8778. }
  8779. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8780. #ifdef CPPHTTPLIB_SSL_ENABLED
  8781. using ClientT = SSLClient;
  8782. #else
  8783. using ClientT = Client;
  8784. #endif
  8785. TestWithHeadersAndContentReceiver<ClientT>(
  8786. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8787. const std::string &body, const std::string &content_type,
  8788. ContentReceiver receiver, DownloadProgress progress) {
  8789. return cli.Post(path, headers, body, content_type, receiver, progress);
  8790. });
  8791. }
  8792. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8793. #ifdef CPPHTTPLIB_SSL_ENABLED
  8794. using ClientT = SSLClient;
  8795. #else
  8796. using ClientT = Client;
  8797. #endif
  8798. TestWithHeadersAndContentReceiver<ClientT>(
  8799. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8800. const std::string &body, const std::string &content_type,
  8801. ContentReceiver receiver, DownloadProgress progress) {
  8802. return cli.Put(path, headers, body, content_type, receiver, progress);
  8803. });
  8804. }
  8805. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8806. #ifdef CPPHTTPLIB_SSL_ENABLED
  8807. using ClientT = SSLClient;
  8808. #else
  8809. using ClientT = Client;
  8810. #endif
  8811. TestWithHeadersAndContentReceiver<ClientT>(
  8812. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8813. const std::string &body, const std::string &content_type,
  8814. ContentReceiver receiver, DownloadProgress progress) {
  8815. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8816. });
  8817. }
  8818. template <typename ClientType>
  8819. void TestWithHeadersAndContentReceiverWithProgress(
  8820. ClientType &cli,
  8821. std::function<Result(ClientType &, const std::string &, const Headers &,
  8822. const std::string &, const std::string &,
  8823. ContentReceiver, DownloadProgress)>
  8824. request_func) {
  8825. Headers headers;
  8826. headers.emplace("X-Test-Header", "progress-test");
  8827. std::string received_body;
  8828. auto progress_called = false;
  8829. auto res = request_func(
  8830. cli, "/content_receiver", headers, "content", "text/plain",
  8831. [&](const char *data, size_t data_length) {
  8832. received_body.append(data, data_length);
  8833. return true;
  8834. },
  8835. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8836. progress_called = true;
  8837. return true;
  8838. });
  8839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8840. EXPECT_EQ(StatusCode::OK_200, res->status);
  8841. EXPECT_EQ("content", received_body);
  8842. EXPECT_TRUE(progress_called);
  8843. }
  8844. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8845. #ifdef CPPHTTPLIB_SSL_ENABLED
  8846. using ClientT = SSLClient;
  8847. #else
  8848. using ClientT = Client;
  8849. #endif
  8850. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8851. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8852. const std::string &body, const std::string &content_type,
  8853. ContentReceiver receiver, DownloadProgress progress) {
  8854. return cli.Post(path, headers, body, content_type, receiver, progress);
  8855. });
  8856. }
  8857. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8858. #ifdef CPPHTTPLIB_SSL_ENABLED
  8859. using ClientT = SSLClient;
  8860. #else
  8861. using ClientT = Client;
  8862. #endif
  8863. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8864. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8865. const std::string &body, const std::string &content_type,
  8866. ContentReceiver receiver, DownloadProgress progress) {
  8867. return cli.Put(path, headers, body, content_type, receiver, progress);
  8868. });
  8869. }
  8870. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8871. #ifdef CPPHTTPLIB_SSL_ENABLED
  8872. using ClientT = SSLClient;
  8873. #else
  8874. using ClientT = Client;
  8875. #endif
  8876. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8877. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8878. const std::string &body, const std::string &content_type,
  8879. ContentReceiver receiver, DownloadProgress progress) {
  8880. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8881. });
  8882. }
  8883. template <typename ClientType>
  8884. void TestWithHeadersAndContentReceiverError(
  8885. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8886. const Headers &, const std::string &,
  8887. const std::string &, ContentReceiver)>
  8888. request_func) {
  8889. Headers headers;
  8890. headers.emplace("X-Error-Test", "true");
  8891. std::string received_body;
  8892. auto receiver_failed = false;
  8893. auto res =
  8894. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8895. [&](const char *data, size_t data_length) {
  8896. received_body.append(data, data_length);
  8897. receiver_failed = true;
  8898. return false;
  8899. });
  8900. ASSERT_FALSE(res);
  8901. EXPECT_TRUE(receiver_failed);
  8902. }
  8903. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8904. #ifdef CPPHTTPLIB_SSL_ENABLED
  8905. using ClientT = SSLClient;
  8906. #else
  8907. using ClientT = Client;
  8908. #endif
  8909. TestWithHeadersAndContentReceiverError<ClientT>(
  8910. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8911. const std::string &body, const std::string &content_type,
  8912. ContentReceiver receiver) {
  8913. return cli.Post(path, headers, body, content_type, receiver);
  8914. });
  8915. }
  8916. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8917. #ifdef CPPHTTPLIB_SSL_ENABLED
  8918. using ClientT = SSLClient;
  8919. #else
  8920. using ClientT = Client;
  8921. #endif
  8922. TestWithHeadersAndContentReceiverError<ClientT>(
  8923. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8924. const std::string &body, const std::string &content_type,
  8925. ContentReceiver receiver) {
  8926. return cli.Put(path, headers, body, content_type, receiver);
  8927. });
  8928. }
  8929. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8930. #ifdef CPPHTTPLIB_SSL_ENABLED
  8931. using ClientT = SSLClient;
  8932. #else
  8933. using ClientT = Client;
  8934. #endif
  8935. TestWithHeadersAndContentReceiverError<ClientT>(
  8936. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8937. const std::string &body, const std::string &content_type,
  8938. ContentReceiver receiver) {
  8939. return cli.Patch(path, headers, body, content_type, receiver);
  8940. });
  8941. }
  8942. TEST_F(ServerTest, PostQueryStringAndBody) {
  8943. auto res =
  8944. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8946. ASSERT_EQ(StatusCode::OK_200, res->status);
  8947. }
  8948. TEST_F(ServerTest, HTTP2Magic) {
  8949. Request req;
  8950. req.method = "PRI";
  8951. req.path = "*";
  8952. req.body = "SM";
  8953. auto res = std::make_shared<Response>();
  8954. auto error = Error::Success;
  8955. auto ret = cli_.send(req, *res, error);
  8956. ASSERT_TRUE(ret);
  8957. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8958. }
  8959. TEST_F(ServerTest, KeepAlive) {
  8960. auto res = cli_.Get("/hi");
  8961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8962. EXPECT_EQ(StatusCode::OK_200, res->status);
  8963. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8964. EXPECT_EQ("Hello World!", res->body);
  8965. res = cli_.Get("/hi");
  8966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8967. EXPECT_EQ(StatusCode::OK_200, res->status);
  8968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8969. EXPECT_EQ("Hello World!", res->body);
  8970. res = cli_.Get("/hi");
  8971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8972. EXPECT_EQ(StatusCode::OK_200, res->status);
  8973. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8974. EXPECT_EQ("Hello World!", res->body);
  8975. res = cli_.Get("/not-exist");
  8976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8977. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8978. res = cli_.Post("/empty", "", "text/plain");
  8979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8980. EXPECT_EQ(StatusCode::OK_200, res->status);
  8981. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8982. EXPECT_EQ("empty", res->body);
  8983. EXPECT_EQ("close", res->get_header_value("Connection"));
  8984. res = cli_.Post(
  8985. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8986. "text/plain");
  8987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8988. EXPECT_EQ(StatusCode::OK_200, res->status);
  8989. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8990. EXPECT_EQ("empty", res->body);
  8991. cli_.set_keep_alive(false);
  8992. res = cli_.Get("/last-request");
  8993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8994. EXPECT_EQ(StatusCode::OK_200, res->status);
  8995. EXPECT_EQ("close", res->get_header_value("Connection"));
  8996. }
  8997. TEST_F(ServerTest, TooManyRedirect) {
  8998. cli_.set_follow_location(true);
  8999. auto res = cli_.Get("/redirect/0");
  9000. ASSERT_TRUE(!res);
  9001. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  9002. }
  9003. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  9004. Request req;
  9005. req.method = "FOOBAR";
  9006. req.path = "/hi";
  9007. cli_.set_keep_alive(true);
  9008. auto res = cli_.send(req);
  9009. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9010. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9011. EXPECT_EQ("close", res->get_header_value("Connection"));
  9012. EXPECT_FALSE(cli_.is_socket_open());
  9013. }
  9014. TEST_F(ServerTest, CustomRouteReadsBody) {
  9015. const std::string xml =
  9016. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  9017. Request req;
  9018. req.method = "PROPFIND";
  9019. req.path = "/dav/dir";
  9020. req.set_header("Depth", "1");
  9021. req.body = xml;
  9022. auto res = cli_.send(req);
  9023. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9024. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9025. EXPECT_EQ(xml, res->body);
  9026. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  9027. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  9028. }
  9029. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  9030. Request req;
  9031. req.method = "PROPFIND";
  9032. req.path = "/dav/42";
  9033. auto res = cli_.send(req);
  9034. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9035. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9036. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  9037. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  9038. }
  9039. TEST_F(ServerTest, CustomRouteRegexPattern) {
  9040. Request req;
  9041. req.method = "PROPFIND";
  9042. req.path = "/dav-re/123";
  9043. auto res = cli_.send(req);
  9044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9045. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9046. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  9047. }
  9048. TEST_F(ServerTest, CustomRouteWithoutBody) {
  9049. Request req;
  9050. req.method = "MKCOL";
  9051. req.path = "/dav-mkcol";
  9052. auto res = cli_.send(req);
  9053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9054. EXPECT_EQ(StatusCode::Created_201, res->status);
  9055. }
  9056. TEST_F(ServerTest, CustomRouteWithContentReader) {
  9057. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  9058. Request req;
  9059. req.method = "REPORT";
  9060. req.path = "/dav-report";
  9061. req.body = xml;
  9062. auto res = cli_.send(req);
  9063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9064. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9065. EXPECT_EQ(xml, res->body);
  9066. }
  9067. // A content reader route must fire even when the request carries no body,
  9068. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  9069. // Without that, a body-less PROPFIND-style request would fall through to 404.
  9070. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  9071. Request req;
  9072. req.method = "REPORT";
  9073. req.path = "/dav-report";
  9074. auto res = cli_.send(req);
  9075. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9076. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9077. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  9078. }
  9079. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  9080. Request req;
  9081. req.method = "PROPFIND";
  9082. req.path = "/not-dav";
  9083. auto res = cli_.send(req);
  9084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9085. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9086. }
  9087. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  9088. Request req;
  9089. req.method = "UNLOCK";
  9090. req.path = "/dav/dir";
  9091. cli_.set_keep_alive(true);
  9092. auto res = cli_.send(req);
  9093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9094. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  9095. EXPECT_EQ("close", res->get_header_value("Connection"));
  9096. EXPECT_FALSE(cli_.is_socket_open());
  9097. }
  9098. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  9099. // The mount point serves this path, but only for GET and HEAD.
  9100. auto get_res = cli_.Get("/dir/index.html");
  9101. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  9102. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  9103. Request req;
  9104. req.method = "PROPFIND";
  9105. req.path = "/dir/index.html";
  9106. auto res = cli_.send(req);
  9107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9108. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9109. }
  9110. TEST_F(ServerTest, CustomRouteKeepAlive) {
  9111. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9112. cli_.set_keep_alive(true);
  9113. for (auto i = 0; i < 2; i++) {
  9114. Request req;
  9115. req.method = "PROPFIND";
  9116. req.path = "/dav/dir";
  9117. req.body = xml;
  9118. auto res = cli_.send(req);
  9119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9120. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9121. EXPECT_EQ(xml, res->body);
  9122. EXPECT_TRUE(cli_.is_socket_open());
  9123. }
  9124. // A built-in method must still be served on the same connection.
  9125. cli_.set_keep_alive(false);
  9126. auto res = cli_.Get("/hi");
  9127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9128. EXPECT_EQ(StatusCode::OK_200, res->status);
  9129. EXPECT_EQ("close", res->get_header_value("Connection"));
  9130. }
  9131. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  9132. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  9133. Request req;
  9134. req.method = "PROPFIND";
  9135. req.path = "/dav/dir";
  9136. req.set_header("Expect", "100-continue");
  9137. req.body = xml;
  9138. auto res = cli_.send(req);
  9139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9140. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  9141. EXPECT_EQ(xml, res->body);
  9142. }
  9143. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  9144. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9145. TEST_F(ServerTest, Gzip) {
  9146. Headers headers;
  9147. headers.emplace("Accept-Encoding", "gzip, deflate");
  9148. auto res = cli_.Get("/compress", headers);
  9149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9150. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9151. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9152. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9153. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9154. "7890123456789012345678901234567890",
  9155. res->body);
  9156. EXPECT_EQ(StatusCode::OK_200, res->status);
  9157. }
  9158. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  9159. Headers headers;
  9160. headers.emplace("Accept-Encoding", "gzip, deflate");
  9161. auto res = cli_.Get("/compress-with-charset", headers);
  9162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9163. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9164. EXPECT_EQ("application/json; charset=utf-8",
  9165. res->get_header_value("Content-Type"));
  9166. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9167. "7890123456789012345678901234567890",
  9168. res->body);
  9169. EXPECT_EQ(StatusCode::OK_200, res->status);
  9170. }
  9171. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  9172. Headers headers;
  9173. headers.emplace("Accept-Encoding", "");
  9174. auto res = cli_.Get("/compress", headers);
  9175. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9176. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9177. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9178. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9179. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9180. "7890123456789012345678901234567890",
  9181. res->body);
  9182. EXPECT_EQ(StatusCode::OK_200, res->status);
  9183. }
  9184. TEST_F(ServerTest, GzipWithContentReceiver) {
  9185. Headers headers;
  9186. headers.emplace("Accept-Encoding", "gzip, deflate");
  9187. std::string body;
  9188. auto res =
  9189. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9190. EXPECT_EQ(100U, data_length);
  9191. body.append(data, data_length);
  9192. return true;
  9193. });
  9194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9195. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9196. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9197. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9198. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9199. "7890123456789012345678901234567890",
  9200. body);
  9201. EXPECT_EQ(StatusCode::OK_200, res->status);
  9202. }
  9203. TEST_F(ServerTest, GzipWithoutDecompressing) {
  9204. Headers headers;
  9205. headers.emplace("Accept-Encoding", "gzip, deflate");
  9206. cli_.set_decompress(false);
  9207. auto res = cli_.Get("/compress", headers);
  9208. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9209. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9210. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9211. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  9212. EXPECT_EQ(33U, res->body.size());
  9213. EXPECT_EQ(StatusCode::OK_200, res->status);
  9214. }
  9215. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  9216. Headers headers;
  9217. headers.emplace("Accept-Encoding", "");
  9218. std::string body;
  9219. auto res =
  9220. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9221. EXPECT_EQ(100U, data_length);
  9222. body.append(data, data_length);
  9223. return true;
  9224. });
  9225. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9226. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9227. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9228. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9229. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9230. "7890123456789012345678901234567890",
  9231. body);
  9232. EXPECT_EQ(StatusCode::OK_200, res->status);
  9233. }
  9234. TEST_F(ServerTest, NoGzip) {
  9235. Headers headers;
  9236. headers.emplace("Accept-Encoding", "gzip, deflate");
  9237. auto res = cli_.Get("/nocompress", headers);
  9238. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9239. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9240. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9241. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9242. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9243. "7890123456789012345678901234567890",
  9244. res->body);
  9245. EXPECT_EQ(StatusCode::OK_200, res->status);
  9246. }
  9247. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  9248. Headers headers;
  9249. headers.emplace("Accept-Encoding", "gzip, deflate");
  9250. std::string body;
  9251. auto res = cli_.Get("/nocompress", headers,
  9252. [&](const char *data, size_t data_length) {
  9253. EXPECT_EQ(100U, data_length);
  9254. body.append(data, data_length);
  9255. return true;
  9256. });
  9257. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9258. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9259. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9260. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9261. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9262. "7890123456789012345678901234567890",
  9263. body);
  9264. EXPECT_EQ(StatusCode::OK_200, res->status);
  9265. }
  9266. TEST_F(ServerTest, MultipartFormDataGzip) {
  9267. UploadFormDataItems items = {
  9268. {"key1", "test", "", ""},
  9269. {"key2", "--abcdefg123", "", ""},
  9270. };
  9271. cli_.set_compress(true);
  9272. auto res = cli_.Post("/compress-multipart", items);
  9273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9274. EXPECT_EQ(StatusCode::OK_200, res->status);
  9275. }
  9276. #endif
  9277. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9278. // Static file compression is opt-in, so these run their own server rather than
  9279. // flipping it on for the shared ServerTest fixture, which would silently
  9280. // rewrite what every other static file test is asserting.
  9281. class StaticFileCompressionTest : public ::testing::Test {
  9282. protected:
  9283. void TearDown() override {
  9284. if (t_.joinable()) {
  9285. svr_.stop();
  9286. t_.join();
  9287. }
  9288. }
  9289. int start(const std::function<void(Server &)> &configure = nullptr) {
  9290. // Serves the same tree as a directory of build-time compressed assets
  9291. // would be served: the mount point names the coding the files are already
  9292. // stored in. Registered before "/" so it is the one that matches.
  9293. svr_.set_mount_point("/pre-encoded", "./www",
  9294. {{"Content-Encoding", "gzip"}});
  9295. svr_.set_mount_point("/", "./www");
  9296. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  9297. res.set_file_content("./www/dir/index.html", "text/html");
  9298. });
  9299. svr_.Get("/pre-encoded-file-content",
  9300. [](const Request & /*req*/, Response &res) {
  9301. res.set_header("Content-Encoding", "gzip");
  9302. res.set_file_content("./www/dir/index.html", "text/html");
  9303. });
  9304. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  9305. res.set_content_provider(
  9306. 6, "text/plain",
  9307. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9308. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  9309. return true;
  9310. });
  9311. });
  9312. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  9313. res.set_content_provider(
  9314. 1000, "text/plain",
  9315. [](size_t offset, size_t /*length*/, DataSink &sink) {
  9316. if (offset < 100) {
  9317. std::string data(100, 'A');
  9318. sink.write(data.data(), data.size());
  9319. return true;
  9320. }
  9321. std::this_thread::sleep_for(std::chrono::seconds(2));
  9322. std::string data(900, 'B');
  9323. sink.write(data.data(), data.size());
  9324. return true;
  9325. });
  9326. });
  9327. if (configure) { configure(svr_); }
  9328. auto port = svr_.bind_to_any_port(HOST);
  9329. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  9330. svr_.wait_until_ready();
  9331. return port;
  9332. }
  9333. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  9334. // Every file under ./www except 1MB.txt is smaller than the default
  9335. // 1400-byte floor, so a test that needs a small file compressed has to lower
  9336. // it out of the way.
  9337. static void enable_without_floor(Server &svr) {
  9338. svr.set_static_file_compression(true);
  9339. svr.set_static_file_compression_min_length(0);
  9340. }
  9341. Server svr_;
  9342. std::thread t_;
  9343. };
  9344. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  9345. auto port = start();
  9346. Client cli(HOST, port);
  9347. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9349. EXPECT_EQ(StatusCode::OK_200, res->status);
  9350. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9351. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9352. EXPECT_EQ(1048576U, res->body.size());
  9353. }
  9354. TEST_F(StaticFileCompressionTest, MountPoint) {
  9355. auto port = start(enable);
  9356. Client cli(HOST, port);
  9357. cli.set_decompress(false);
  9358. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9359. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9360. EXPECT_EQ(StatusCode::OK_200, res->status);
  9361. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9362. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9363. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  9364. // The response stays self-delimiting: a length, not a chunked body.
  9365. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9366. EXPECT_EQ(std::to_string(res->body.size()),
  9367. res->get_header_value("Content-Length"));
  9368. EXPECT_LT(res->body.size(), 1048576U);
  9369. EXPECT_FALSE(res->body.empty());
  9370. }
  9371. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  9372. auto port = start(enable);
  9373. Client cli(HOST, port);
  9374. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9376. EXPECT_EQ(StatusCode::OK_200, res->status);
  9377. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9378. EXPECT_EQ(1048576U, res->body.size());
  9379. }
  9380. TEST_F(StaticFileCompressionTest, FileContent) {
  9381. auto port = start(enable_without_floor);
  9382. Client cli(HOST, port);
  9383. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  9384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9385. EXPECT_EQ(StatusCode::OK_200, res->status);
  9386. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  9387. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9388. EXPECT_EQ(104U, res->body.size());
  9389. }
  9390. // A handler that serves an already-encoded file names the coding itself. The
  9391. // file-backed path decided its coding from Accept-Encoding and the content
  9392. // type alone, so it compressed the stored bytes a second time and appended a
  9393. // second Content-Encoding field line.
  9394. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  9395. auto port = start(enable_without_floor);
  9396. Client cli(HOST, port);
  9397. cli.set_decompress(false);
  9398. auto res = cli.Get("/pre-encoded-file-content",
  9399. Headers{{"Accept-Encoding", "gzip"}});
  9400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9401. EXPECT_EQ(StatusCode::OK_200, res->status);
  9402. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9403. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9404. // Vary belongs to a coding the server chose, and it chose none here.
  9405. EXPECT_FALSE(res->has_header("Vary"));
  9406. // The file travels exactly as it is stored on disk.
  9407. EXPECT_EQ(104U, res->body.size());
  9408. }
  9409. // The 1MB file clears the default floor, so this one runs the configuration a
  9410. // deployment would actually have.
  9411. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  9412. auto port = start(enable);
  9413. Client cli(HOST, port);
  9414. cli.set_decompress(false);
  9415. auto res =
  9416. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9417. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9418. EXPECT_EQ(StatusCode::OK_200, res->status);
  9419. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  9420. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9421. EXPECT_FALSE(res->has_header("Vary"));
  9422. EXPECT_EQ(1048576U, res->body.size());
  9423. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  9424. }
  9425. TEST_F(StaticFileCompressionTest, Head) {
  9426. auto port = start(enable);
  9427. Client cli(HOST, port);
  9428. cli.set_decompress(false);
  9429. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9430. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  9431. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9433. EXPECT_EQ(StatusCode::OK_200, res->status);
  9434. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9435. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  9436. // HEAD still reports the size a GET would return.
  9437. EXPECT_EQ(get->get_header_value("Content-Length"),
  9438. res->get_header_value("Content-Length"));
  9439. EXPECT_TRUE(res->body.empty());
  9440. }
  9441. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  9442. auto port = start(enable);
  9443. Client cli(HOST, port);
  9444. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  9445. {"Accept-Encoding", "gzip"}});
  9446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9447. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  9448. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9449. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  9450. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  9451. EXPECT_EQ("cd", res->body);
  9452. }
  9453. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  9454. auto port = start(enable);
  9455. Client cli(HOST, port);
  9456. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  9457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9458. EXPECT_EQ(StatusCode::OK_200, res->status);
  9459. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9460. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9461. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  9462. }
  9463. TEST_F(StaticFileCompressionTest, EmptyFile) {
  9464. auto port = start(enable);
  9465. Client cli(HOST, port);
  9466. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  9467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9468. EXPECT_EQ(StatusCode::OK_200, res->status);
  9469. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9470. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  9471. EXPECT_TRUE(res->body.empty());
  9472. }
  9473. TEST_F(StaticFileCompressionTest, MinLength) {
  9474. auto port = start(enable);
  9475. Client cli(HOST, port);
  9476. // 104 bytes, well under the default floor. Compressing it would add the
  9477. // gzip header and trailer to a body that already fits in one packet.
  9478. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9480. EXPECT_EQ(StatusCode::OK_200, res->status);
  9481. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9482. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  9483. }
  9484. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  9485. auto port = start([](Server &svr) {
  9486. svr.set_static_file_compression(true);
  9487. svr.set_static_file_compression_min_length(1);
  9488. });
  9489. Client cli(HOST, port);
  9490. cli.set_decompress(false);
  9491. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  9492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9493. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9494. // A 9-byte file comes back larger than it went in, because gzip's header and
  9495. // trailer outweigh anything deflate can save. That is the end of the range
  9496. // the floor exists to keep out.
  9497. EXPECT_GT(res->body.size(), 9U);
  9498. }
  9499. TEST_F(StaticFileCompressionTest, MaxLength) {
  9500. auto port = start([](Server &svr) {
  9501. svr.set_static_file_compression(true);
  9502. svr.set_static_file_compression_min_length(0);
  9503. svr.set_static_file_compression_max_length(1024);
  9504. });
  9505. Client cli(HOST, port);
  9506. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  9507. // defines `small` as a macro on Windows.
  9508. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  9509. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  9510. EXPECT_FALSE(over->has_header("Content-Encoding"));
  9511. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  9512. // Under it: compressed.
  9513. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9514. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  9515. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  9516. }
  9517. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  9518. auto port = start(enable_without_floor);
  9519. Client cli(HOST, port);
  9520. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  9521. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  9522. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  9523. auto identity_etag = identity->get_header_value("ETag");
  9524. ASSERT_FALSE(identity_etag.empty());
  9525. auto gzipped =
  9526. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  9527. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  9528. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  9529. auto gzip_etag = gzipped->get_header_value("ETag");
  9530. ASSERT_FALSE(gzip_etag.empty());
  9531. // Two representations, two validators.
  9532. EXPECT_NE(identity_etag, gzip_etag);
  9533. // Each one revalidates against the request that would produce it...
  9534. auto fresh =
  9535. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  9536. {"If-None-Match", gzip_etag}});
  9537. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  9538. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  9539. auto fresh_identity =
  9540. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  9541. {"If-None-Match", identity_etag}});
  9542. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  9543. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  9544. // ...and not against the other representation.
  9545. auto crossed =
  9546. cli.Get("/dir/index.html",
  9547. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  9548. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  9549. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  9550. }
  9551. // The opt-in covers responses the server reads off disk itself. A caller's own
  9552. // known-length provider keeps its Content-Length and, more importantly, keeps
  9553. // delivering incrementally: routing it through a compressor would hold every
  9554. // write back until zlib's window filled.
  9555. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  9556. auto port = start(enable);
  9557. Client cli(HOST, port);
  9558. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  9559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9560. EXPECT_EQ(StatusCode::OK_200, res->status);
  9561. EXPECT_FALSE(res->has_header("Content-Encoding"));
  9562. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  9563. EXPECT_EQ("aaabbb", res->body);
  9564. }
  9565. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  9566. auto port = start(enable);
  9567. Client cli(HOST, port);
  9568. cli.set_read_timeout(1, 0);
  9569. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  9570. Headers{{"Accept-Encoding", "gzip"}});
  9571. ASSERT_TRUE(handle.is_valid());
  9572. // The provider writes 100 bytes and then stalls for longer than the read
  9573. // timeout. Those first bytes have to arrive anyway: run the response through
  9574. // a compressor and zlib holds them until its window fills, so the read would
  9575. // come back empty instead.
  9576. char buf[256];
  9577. auto n = handle.read(buf, sizeof(buf));
  9578. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  9579. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  9580. }
  9581. #endif
  9582. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  9583. TEST_F(ServerTest, Brotli) {
  9584. Headers headers;
  9585. headers.emplace("Accept-Encoding", "br");
  9586. auto res = cli_.Get("/compress", headers);
  9587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9588. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9589. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9590. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  9591. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9592. "7890123456789012345678901234567890",
  9593. res->body);
  9594. EXPECT_EQ(StatusCode::OK_200, res->status);
  9595. }
  9596. #endif
  9597. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  9598. TEST_F(ServerTest, Zstd) {
  9599. Headers headers;
  9600. headers.emplace("Accept-Encoding", "zstd");
  9601. auto res = cli_.Get("/compress", headers);
  9602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9603. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9604. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9605. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9606. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9607. "7890123456789012345678901234567890",
  9608. res->body);
  9609. EXPECT_EQ(StatusCode::OK_200, res->status);
  9610. }
  9611. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  9612. Headers headers;
  9613. headers.emplace("Accept-Encoding", "");
  9614. auto res = cli_.Get("/compress", headers);
  9615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9616. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9617. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9618. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9619. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9620. "7890123456789012345678901234567890",
  9621. res->body);
  9622. EXPECT_EQ(StatusCode::OK_200, res->status);
  9623. }
  9624. TEST_F(ServerTest, ZstdWithContentReceiver) {
  9625. Headers headers;
  9626. headers.emplace("Accept-Encoding", "zstd");
  9627. std::string body;
  9628. auto res =
  9629. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9630. EXPECT_EQ(100U, data_length);
  9631. body.append(data, data_length);
  9632. return true;
  9633. });
  9634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9635. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9636. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9637. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9638. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9639. "7890123456789012345678901234567890",
  9640. body);
  9641. EXPECT_EQ(StatusCode::OK_200, res->status);
  9642. }
  9643. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  9644. Headers headers;
  9645. headers.emplace("Accept-Encoding", "zstd");
  9646. cli_.set_decompress(false);
  9647. auto res = cli_.Get("/compress", headers);
  9648. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  9649. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  9650. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  9651. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  9652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9653. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  9654. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9655. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  9656. EXPECT_EQ(StatusCode::OK_200, res->status);
  9657. ASSERT_EQ(26U, res->body.size());
  9658. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  9659. 0);
  9660. }
  9661. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  9662. Headers headers;
  9663. headers.emplace("Accept-Encoding", "");
  9664. std::string body;
  9665. auto res =
  9666. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  9667. EXPECT_EQ(100U, data_length);
  9668. body.append(data, data_length);
  9669. return true;
  9670. });
  9671. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9672. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9673. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  9674. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9675. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9676. "7890123456789012345678901234567890",
  9677. body);
  9678. EXPECT_EQ(StatusCode::OK_200, res->status);
  9679. }
  9680. TEST_F(ServerTest, NoZstd) {
  9681. Headers headers;
  9682. headers.emplace("Accept-Encoding", "zstd");
  9683. auto res = cli_.Get("/nocompress", headers);
  9684. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9685. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9686. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9687. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9688. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9689. "7890123456789012345678901234567890",
  9690. res->body);
  9691. EXPECT_EQ(StatusCode::OK_200, res->status);
  9692. }
  9693. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  9694. Headers headers;
  9695. headers.emplace("Accept-Encoding", "zstd");
  9696. std::string body;
  9697. auto res = cli_.Get("/nocompress", headers,
  9698. [&](const char *data, size_t data_length) {
  9699. EXPECT_EQ(100U, data_length);
  9700. body.append(data, data_length);
  9701. return true;
  9702. });
  9703. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9704. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  9705. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  9706. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  9707. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  9708. "7890123456789012345678901234567890",
  9709. body);
  9710. EXPECT_EQ(StatusCode::OK_200, res->status);
  9711. }
  9712. // TODO: How to enable zstd ??
  9713. TEST_F(ServerTest, MultipartFormDataZstd) {
  9714. UploadFormDataItems items = {
  9715. {"key1", "test", "", ""},
  9716. {"key2", "--abcdefg123", "", ""},
  9717. };
  9718. Headers headers;
  9719. headers.emplace("Accept-Encoding", "zstd");
  9720. cli_.set_compress(true);
  9721. auto res = cli_.Post("/compress-multipart", headers, items);
  9722. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9723. EXPECT_EQ(StatusCode::OK_200, res->status);
  9724. }
  9725. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9726. Headers headers;
  9727. headers.emplace("Accept-Encoding", "zstd");
  9728. cli_.set_compress(true);
  9729. auto res = cli_.Put(
  9730. "/put", headers, 3,
  9731. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9732. sink.os << "PUT";
  9733. return true;
  9734. },
  9735. "text/plain");
  9736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9737. EXPECT_EQ(StatusCode::OK_200, res->status);
  9738. EXPECT_EQ("PUT", res->body);
  9739. }
  9740. // Pre-compression logging tests
  9741. TEST_F(ServerTest, PreCompressionLogging) {
  9742. // Test data for compression (matches the actual /compress endpoint content)
  9743. const std::string test_content =
  9744. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9745. "3456789012345678901234567890";
  9746. // Variables to capture logging data
  9747. std::string pre_compression_body;
  9748. std::string pre_compression_content_type;
  9749. std::string pre_compression_content_encoding;
  9750. std::string post_compression_body;
  9751. std::string post_compression_content_type;
  9752. std::string post_compression_content_encoding;
  9753. // Set up pre-compression logger
  9754. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9755. const Response &res) {
  9756. pre_compression_body = res.body;
  9757. pre_compression_content_type = res.get_header_value("Content-Type");
  9758. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9759. });
  9760. // Set up post-compression logger
  9761. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9762. post_compression_body = res.body;
  9763. post_compression_content_type = res.get_header_value("Content-Type");
  9764. post_compression_content_encoding =
  9765. res.get_header_value("Content-Encoding");
  9766. });
  9767. // Test with gzip compression
  9768. Headers headers;
  9769. headers.emplace("Accept-Encoding", "gzip");
  9770. auto res = cli_.Get("/compress", headers);
  9771. // Verify response was compressed
  9772. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9773. EXPECT_EQ(StatusCode::OK_200, res->status);
  9774. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9775. // Verify pre-compression logger captured uncompressed content
  9776. EXPECT_EQ(test_content, pre_compression_body);
  9777. EXPECT_EQ("text/plain", pre_compression_content_type);
  9778. EXPECT_TRUE(pre_compression_content_encoding
  9779. .empty()); // No encoding header before compression
  9780. // Verify post-compression logger captured compressed content
  9781. EXPECT_NE(test_content,
  9782. post_compression_body); // Should be different after compression
  9783. EXPECT_EQ("text/plain", post_compression_content_type);
  9784. EXPECT_EQ("gzip", post_compression_content_encoding);
  9785. // Verify compressed content is smaller
  9786. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9787. }
  9788. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9789. const std::string test_content =
  9790. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9791. "3456789012345678901234567890";
  9792. std::string pre_compression_body;
  9793. std::string post_compression_body;
  9794. svr_.set_pre_compression_logger(
  9795. [&](const Request & /*req*/, const Response &res) {
  9796. pre_compression_body = res.body;
  9797. });
  9798. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9799. post_compression_body = res.body;
  9800. });
  9801. Headers headers;
  9802. headers.emplace("Accept-Encoding", "br");
  9803. auto res = cli_.Get("/compress", headers);
  9804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9805. EXPECT_EQ(StatusCode::OK_200, res->status);
  9806. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9807. // Verify pre-compression content is uncompressed
  9808. EXPECT_EQ(test_content, pre_compression_body);
  9809. // Verify post-compression content is compressed
  9810. EXPECT_NE(test_content, post_compression_body);
  9811. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9812. }
  9813. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9814. const std::string test_content =
  9815. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9816. "3456789012345678901234567890";
  9817. std::string pre_compression_body;
  9818. std::string post_compression_body;
  9819. svr_.set_pre_compression_logger(
  9820. [&](const Request & /*req*/, const Response &res) {
  9821. pre_compression_body = res.body;
  9822. });
  9823. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9824. post_compression_body = res.body;
  9825. });
  9826. // Request without compression (use /nocompress endpoint)
  9827. Headers headers;
  9828. auto res = cli_.Get("/nocompress", headers);
  9829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9830. EXPECT_EQ(StatusCode::OK_200, res->status);
  9831. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9832. // Pre-compression logger should not be called when no compression is applied
  9833. EXPECT_TRUE(
  9834. pre_compression_body.empty()); // Pre-compression logger not called
  9835. EXPECT_EQ(
  9836. test_content,
  9837. post_compression_body); // Post-compression logger captures final content
  9838. }
  9839. TEST_F(ServerTest, LoggerSeesContentLength) {
  9840. size_t logged_content_length = 0;
  9841. std::string logged_content_length_header;
  9842. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9843. logged_content_length = res.content_length_;
  9844. logged_content_length_header = res.get_header_value("Content-Length");
  9845. });
  9846. auto res = cli_.Get("/nocompress");
  9847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9848. EXPECT_EQ(StatusCode::OK_200, res->status);
  9849. EXPECT_EQ(res->body.size(), logged_content_length);
  9850. EXPECT_EQ(std::to_string(logged_content_length),
  9851. logged_content_length_header);
  9852. }
  9853. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9854. const std::string test_content =
  9855. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9856. "3456789012345678901234567890";
  9857. std::string pre_compression_body;
  9858. bool pre_logger_called = false;
  9859. // Set only pre-compression logger
  9860. svr_.set_pre_compression_logger(
  9861. [&](const Request & /*req*/, const Response &res) {
  9862. pre_compression_body = res.body;
  9863. pre_logger_called = true;
  9864. });
  9865. Headers headers;
  9866. headers.emplace("Accept-Encoding", "gzip");
  9867. auto res = cli_.Get("/compress", headers);
  9868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9869. EXPECT_EQ(StatusCode::OK_200, res->status);
  9870. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9871. // Verify pre-compression logger was called
  9872. EXPECT_TRUE(pre_logger_called);
  9873. EXPECT_EQ(test_content, pre_compression_body);
  9874. }
  9875. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9876. {
  9877. // Test with Expect: 100-continue header - success case
  9878. // Server returns 100 Continue, client sends body, server returns 200 OK
  9879. Request req;
  9880. req.method = "POST";
  9881. req.path = "/post-large";
  9882. req.set_header("Expect", "100-continue");
  9883. req.body = LARGE_DATA;
  9884. Response res;
  9885. auto error = Error::Success;
  9886. cli_.set_keep_alive(true);
  9887. auto ret = cli_.send(req, res, error);
  9888. EXPECT_TRUE(ret);
  9889. EXPECT_EQ(StatusCode::OK_200, res.status);
  9890. EXPECT_EQ(LARGE_DATA, res.body);
  9891. }
  9892. {
  9893. // Test with Expect: 100-continue header - error case
  9894. // Client should not send the body when server returns an error
  9895. Request req;
  9896. req.method = "POST";
  9897. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9898. req.set_header("Expect", "100-continue");
  9899. req.body = LARGE_DATA;
  9900. Response res;
  9901. auto error = Error::Success;
  9902. auto start = std::chrono::high_resolution_clock::now();
  9903. cli_.set_keep_alive(true);
  9904. auto ret = cli_.send(req, res, error);
  9905. auto end = std::chrono::high_resolution_clock::now();
  9906. auto elapsed =
  9907. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9908. .count();
  9909. // With Expect: 100-continue, request completes successfully but with error
  9910. EXPECT_TRUE(ret);
  9911. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9912. EXPECT_EQ("close", res.get_header_value("Connection"));
  9913. EXPECT_FALSE(cli_.is_socket_open());
  9914. EXPECT_LE(elapsed, 2000);
  9915. }
  9916. {
  9917. // Send an extra GET request to ensure error recovery without hanging
  9918. Request req;
  9919. req.method = "GET";
  9920. req.path = "/hi";
  9921. auto start = std::chrono::high_resolution_clock::now();
  9922. auto res = cli_.send(req);
  9923. auto end = std::chrono::high_resolution_clock::now();
  9924. auto elapsed =
  9925. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9926. .count();
  9927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9928. EXPECT_EQ(StatusCode::OK_200, res->status);
  9929. EXPECT_EQ("Hello World!", res->body);
  9930. EXPECT_LE(elapsed, 500);
  9931. }
  9932. }
  9933. TEST(ZstdDecompressor, ChunkedDecompression) {
  9934. std::string data;
  9935. for (size_t i = 0; i < 32 * 1024; ++i) {
  9936. data.push_back(static_cast<char>('a' + i % 26));
  9937. }
  9938. std::string compressed_data;
  9939. {
  9940. httplib::detail::zstd_compressor compressor;
  9941. bool result = compressor.compress(
  9942. data.data(), data.size(),
  9943. /*last=*/true,
  9944. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9945. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9946. compressed_data_size);
  9947. return true;
  9948. });
  9949. ASSERT_TRUE(result);
  9950. }
  9951. std::string decompressed_data;
  9952. {
  9953. httplib::detail::zstd_decompressor decompressor;
  9954. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9955. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9956. size_t chunk_size = 130;
  9957. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9958. chunk_begin += chunk_size) {
  9959. size_t current_chunk_size =
  9960. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9961. bool result = decompressor.decompress(
  9962. compressed_data.data() + chunk_begin, current_chunk_size,
  9963. [&](const char *decompressed_data_chunk,
  9964. size_t decompressed_data_chunk_size) {
  9965. decompressed_data.insert(decompressed_data.size(),
  9966. decompressed_data_chunk,
  9967. decompressed_data_chunk_size);
  9968. return true;
  9969. });
  9970. ASSERT_TRUE(result);
  9971. }
  9972. }
  9973. ASSERT_EQ(data, decompressed_data);
  9974. }
  9975. TEST(ZstdDecompressor, Decompress) {
  9976. std::string original_text = "Compressed with ZSTD";
  9977. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9978. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9979. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9980. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9981. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9982. std::string decompressed_data;
  9983. {
  9984. httplib::detail::zstd_decompressor decompressor;
  9985. bool result = decompressor.decompress(
  9986. compressed_data.data(), compressed_data.size(),
  9987. [&](const char *decompressed_data_chunk,
  9988. size_t decompressed_data_chunk_size) {
  9989. decompressed_data.insert(decompressed_data.size(),
  9990. decompressed_data_chunk,
  9991. decompressed_data_chunk_size);
  9992. return true;
  9993. });
  9994. ASSERT_TRUE(result);
  9995. }
  9996. ASSERT_EQ(original_text, decompressed_data);
  9997. }
  9998. #endif
  9999. // Sends a raw request to a server listening at HOST:PORT, writing it in
  10000. // separate chunks so that the server sees each part in its own read(). Used to
  10001. // place a read boundary at a specific offset of a request body.
  10002. static bool send_request_in_parts(time_t read_timeout_sec,
  10003. const std::vector<std::string> &parts,
  10004. std::string *resp = nullptr,
  10005. int port = PORT) {
  10006. auto error = Error::Success;
  10007. auto client_sock = detail::create_client_socket(
  10008. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10009. /*connection_timeout_sec=*/5, 0,
  10010. /*read_timeout_sec=*/5, 0,
  10011. /*write_timeout_sec=*/5, 0, std::string(), error);
  10012. if (client_sock == INVALID_SOCKET) { return false; }
  10013. auto ret = detail::process_client_socket(
  10014. client_sock, read_timeout_sec, 0, 0, 0, 0,
  10015. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  10016. for (size_t i = 0; i < parts.size(); i++) {
  10017. const auto &part = parts[i];
  10018. if (part.size() !=
  10019. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  10020. return false;
  10021. }
  10022. if (i + 1 < parts.size()) {
  10023. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10024. }
  10025. }
  10026. char buf[512];
  10027. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  10028. while (line_reader.getline()) {
  10029. if (resp) { *resp += line_reader.ptr(); }
  10030. }
  10031. return true;
  10032. });
  10033. detail::close_socket(client_sock);
  10034. return ret;
  10035. }
  10036. // Sends a raw request to a server listening at HOST:PORT.
  10037. static bool send_request(time_t read_timeout_sec, const std::string &req,
  10038. std::string *resp = nullptr, int port = PORT) {
  10039. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  10040. }
  10041. #ifdef CPPHTTPLIB_SSL_ENABLED
  10042. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  10043. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10044. ASSERT_TRUE(svr.is_valid());
  10045. svr.set_read_timeout(1, 0);
  10046. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10047. auto se = detail::scope_exit([&] {
  10048. svr.stop();
  10049. t.join();
  10050. ASSERT_FALSE(svr.is_running());
  10051. });
  10052. svr.wait_until_ready();
  10053. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  10054. // keeps each wait well within the read timeout. The server gives up a
  10055. // second in, so the bytes sent after that fail.
  10056. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  10057. parts.resize(26, std::string(1, '\0'));
  10058. EXPECT_FALSE(send_request_in_parts(5, parts));
  10059. }
  10060. #endif
  10061. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10062. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  10063. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  10064. const std::vector<std::string> &parts,
  10065. std::string *resp = nullptr,
  10066. int port = PORT) {
  10067. auto error = Error::Success;
  10068. auto sock = detail::create_client_socket(
  10069. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  10070. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  10071. /*write_timeout_sec=*/5, 0, std::string(), error);
  10072. if (sock == INVALID_SOCKET) { return false; }
  10073. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  10074. auto ctx = SSL_CTX_new(TLS_client_method());
  10075. auto ssl = SSL_new(ctx);
  10076. auto ssl_se = detail::scope_exit([&] {
  10077. SSL_free(ssl);
  10078. SSL_CTX_free(ctx);
  10079. });
  10080. SSL_set_fd(ssl, static_cast<int>(sock));
  10081. if (SSL_connect(ssl) != 1) { return false; }
  10082. for (size_t i = 0; i < parts.size(); i++) {
  10083. const auto &part = parts[i];
  10084. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  10085. static_cast<int>(part.size())) {
  10086. return false;
  10087. }
  10088. if (i + 1 < parts.size()) {
  10089. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10090. }
  10091. }
  10092. char buf[512];
  10093. int n;
  10094. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  10095. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  10096. }
  10097. return true;
  10098. }
  10099. #endif
  10100. // The request line, then a header value a byte at a time.
  10101. static std::vector<std::string> slow_request_head_parts() {
  10102. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  10103. parts.resize(26, "a");
  10104. parts.emplace_back("\r\n\r\n");
  10105. return parts;
  10106. }
  10107. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  10108. // within the one-second read timeout. The server gives up a second in, before
  10109. // the head is complete.
  10110. static void
  10111. expect_slow_request_head_dropped(Server &svr,
  10112. const std::function<std::string()> &send) {
  10113. std::atomic<bool> handled(false);
  10114. svr.Get("/", [&](const Request &, Response &res) {
  10115. handled = true;
  10116. res.set_content("ok", "text/plain");
  10117. });
  10118. svr.set_read_timeout(1, 0);
  10119. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  10120. auto se = detail::scope_exit([&] {
  10121. svr.stop();
  10122. t.join();
  10123. ASSERT_FALSE(svr.is_running());
  10124. });
  10125. svr.wait_until_ready();
  10126. auto resp = send();
  10127. EXPECT_FALSE(handled);
  10128. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  10129. }
  10130. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10131. Server svr;
  10132. expect_slow_request_head_dropped(svr, [] {
  10133. std::string resp;
  10134. send_request_in_parts(5, slow_request_head_parts(), &resp);
  10135. return resp;
  10136. });
  10137. }
  10138. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10139. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  10140. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10141. ASSERT_TRUE(svr.is_valid());
  10142. expect_slow_request_head_dropped(svr, [] {
  10143. std::string resp;
  10144. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  10145. return resp;
  10146. });
  10147. }
  10148. #endif
  10149. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  10150. Server svr;
  10151. std::string header_value;
  10152. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  10153. header_value = req.get_header_value("foo");
  10154. res.set_content("ok", "text/plain");
  10155. });
  10156. thread t = thread([&] { svr.listen(HOST, PORT); });
  10157. auto se = detail::scope_exit([&] {
  10158. svr.stop();
  10159. t.join();
  10160. ASSERT_FALSE(svr.is_running());
  10161. });
  10162. svr.wait_until_ready();
  10163. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  10164. // like characters are not treated the same - use vertical tab and escape.
  10165. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  10166. "foo: \t \v bar \x1B\t \r\n"
  10167. "Connection: close\r\n"
  10168. "\r\n";
  10169. std::string res;
  10170. ASSERT_TRUE(send_request(5, req, &res));
  10171. EXPECT_EQ(header_value, "");
  10172. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10173. }
  10174. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  10175. Server svr;
  10176. std::string received;
  10177. svr.Get("/order", [&](const Request &req, Response &res) {
  10178. received = entries_to_string(req.headers);
  10179. res.set_content("ok", "text/plain");
  10180. });
  10181. auto port = svr.bind_to_any_port(HOST);
  10182. thread t = thread([&] { svr.listen_after_bind(); });
  10183. auto se = detail::scope_exit([&] {
  10184. svr.stop();
  10185. t.join();
  10186. ASSERT_FALSE(svr.is_running());
  10187. });
  10188. svr.wait_until_ready();
  10189. const std::string req = "GET /order HTTP/1.1\r\n"
  10190. "Host: localhost\r\n"
  10191. "X-First: 1\r\n"
  10192. "X-Dup: a\r\n"
  10193. "X-Second: 2\r\n"
  10194. "X-Dup: b\r\n"
  10195. "Connection: close\r\n"
  10196. "\r\n";
  10197. std::string res;
  10198. ASSERT_TRUE(send_request(5, req, &res, port));
  10199. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10200. EXPECT_EQ(
  10201. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  10202. received);
  10203. }
  10204. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  10205. Server svr;
  10206. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  10207. res.set_header("Set-Cookie", "first=1");
  10208. res.set_header("X-Between", "y");
  10209. res.set_header("Set-Cookie", "second=2");
  10210. res.set_content("ok", "text/plain");
  10211. });
  10212. auto port = svr.bind_to_any_port(HOST);
  10213. thread t = thread([&] { svr.listen_after_bind(); });
  10214. auto se = detail::scope_exit([&] {
  10215. svr.stop();
  10216. t.join();
  10217. ASSERT_FALSE(svr.is_running());
  10218. });
  10219. svr.wait_until_ready();
  10220. Client cli(HOST, port);
  10221. auto res = cli.Get("/cookies");
  10222. ASSERT_TRUE(res);
  10223. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  10224. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  10225. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  10226. }
  10227. // A stream may send a byte at a time with a small extension on each chunk,
  10228. // however long it runs
  10229. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  10230. Server svr;
  10231. svr.Post("/count", [](const Request &req, Response &res) {
  10232. res.set_content(std::to_string(req.body.size()), "text/plain");
  10233. });
  10234. auto port = svr.bind_to_any_port(HOST);
  10235. ASSERT_LT(0, port);
  10236. thread t = thread([&] { svr.listen_after_bind(); });
  10237. auto se = detail::scope_exit([&] {
  10238. svr.stop();
  10239. t.join();
  10240. ASSERT_FALSE(svr.is_running());
  10241. });
  10242. svr.wait_until_ready();
  10243. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  10244. "\r\nTransfer-Encoding: chunked\r\n"
  10245. "Connection: close\r\n\r\n";
  10246. for (auto i = 0; i < 4096; i++) {
  10247. req += "1;a=b\r\nx\r\n";
  10248. }
  10249. req += "0\r\n\r\n";
  10250. std::string res;
  10251. ASSERT_TRUE(send_request(5, req, &res, port));
  10252. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  10253. EXPECT_EQ("4096", res.substr(res.size() - 4));
  10254. }
  10255. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  10256. Server svr;
  10257. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  10258. auto i = new int(0);
  10259. res.set_header("Trailer", "X-Safe, X-Reflected");
  10260. res.set_chunked_content_provider(
  10261. "text/plain",
  10262. [i](size_t /*offset*/, DataSink &sink) {
  10263. if (*i == 0) {
  10264. sink.os << "body";
  10265. } else {
  10266. Headers trailer;
  10267. // A valid trailer that must survive.
  10268. trailer.emplace("X-Safe", "safe");
  10269. // Attacker-controlled value carrying CR/LF (response splitting).
  10270. trailer.emplace("X-Reflected",
  10271. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10272. // Attacker-controlled name carrying CR/LF.
  10273. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10274. sink.done_with_trailer(trailer);
  10275. }
  10276. (*i)++;
  10277. return true;
  10278. },
  10279. [i](bool /*success*/) { delete i; });
  10280. });
  10281. thread t = thread([&] { svr.listen(HOST, PORT); });
  10282. auto se = detail::scope_exit([&] {
  10283. svr.stop();
  10284. t.join();
  10285. ASSERT_FALSE(svr.is_running());
  10286. });
  10287. svr.wait_until_ready();
  10288. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  10289. "Host: " + HOST +
  10290. "\r\n"
  10291. "Connection: close\r\n"
  10292. "\r\n";
  10293. std::string res;
  10294. ASSERT_TRUE(send_request(5, req, &res));
  10295. // The injected fields must not appear anywhere in the raw response.
  10296. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10297. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10298. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10299. // Invalid trailers are dropped entirely, matching set_header().
  10300. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10301. // The valid trailer still passes through.
  10302. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10303. }
  10304. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  10305. // A custom header writer gets only the fields the default one writes
  10306. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  10307. std::string s;
  10308. for (const auto &h : hdrs) {
  10309. s += h.first + ": " + h.second + "\r\n";
  10310. }
  10311. s += "\r\n";
  10312. return strm.write(s.data(), s.size());
  10313. };
  10314. for (auto custom_writer : {false, true}) {
  10315. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  10316. Server svr;
  10317. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  10318. svr.set_post_routing_handler([](const Request &, Response &res) {
  10319. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  10320. });
  10321. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  10322. // res.headers is a public field an application can populate directly,
  10323. // bypassing set_header()'s validation (e.g. reflecting a request value).
  10324. // A valid header that must survive.
  10325. res.headers.emplace("X-Safe", "safe");
  10326. // Attacker-controlled value carrying CR/LF (response splitting).
  10327. res.headers.emplace("X-Reflected",
  10328. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  10329. // Attacker-controlled name carrying CR/LF.
  10330. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  10331. res.set_content("body", "text/plain");
  10332. });
  10333. thread t = thread([&] { svr.listen(HOST, PORT); });
  10334. auto se = detail::scope_exit([&] {
  10335. svr.stop();
  10336. t.join();
  10337. ASSERT_FALSE(svr.is_running());
  10338. });
  10339. svr.wait_until_ready();
  10340. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  10341. "Host: " + HOST +
  10342. "\r\n"
  10343. "Connection: close\r\n"
  10344. "\r\n";
  10345. std::string res;
  10346. ASSERT_TRUE(send_request(5, req, &res));
  10347. // The injected fields must not appear anywhere in the raw response.
  10348. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  10349. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  10350. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  10351. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  10352. // Invalid headers are dropped entirely, matching set_header().
  10353. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  10354. // The valid header still passes through.
  10355. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  10356. }
  10357. }
  10358. // Forward declaration: in split builds split.py strips `inline` and moves the
  10359. // definition into httplib.cc, so detail::write_request_line is not visible from
  10360. // the public httplib.h. Re-declaring it here lets the tests link against the
  10361. // symbol in both header-only and split builds.
  10362. namespace httplib {
  10363. namespace detail {
  10364. ssize_t write_request_line(Stream &strm, const std::string &method,
  10365. const std::string &path);
  10366. } // namespace detail
  10367. } // namespace httplib
  10368. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  10369. // A well-formed target is written verbatim.
  10370. {
  10371. detail::BufferStream strm;
  10372. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  10373. EXPECT_GT(n, 0);
  10374. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  10375. }
  10376. // A target carrying CR/LF, SP or other control octets must be rejected
  10377. // before anything reaches the wire, otherwise it splits the request line and
  10378. // injects a header or a whole request.
  10379. const std::string evil_targets[] = {
  10380. "/a\r\nInjected: pwned",
  10381. "/a\rInjected",
  10382. "/a\nInjected",
  10383. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  10384. "/a b",
  10385. "/a\tb",
  10386. "/a\x7f",
  10387. };
  10388. for (const auto &evil : evil_targets) {
  10389. detail::BufferStream strm;
  10390. auto n = detail::write_request_line(strm, "GET", evil);
  10391. EXPECT_LT(n, 0);
  10392. EXPECT_TRUE(strm.get_buffer().empty());
  10393. }
  10394. }
  10395. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  10396. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  10397. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  10398. // target reaches write_request. The client must fail cleanly with
  10399. // Error::Write instead of putting a request-line-less, header-injecting
  10400. // request on the wire.
  10401. Server svr;
  10402. svr.Get("/a", [](const Request &, Response &res) {
  10403. res.set_content("ok", "text/plain");
  10404. });
  10405. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10406. auto se = detail::scope_exit([&] {
  10407. svr.stop();
  10408. thread.join();
  10409. ASSERT_FALSE(svr.is_running());
  10410. });
  10411. svr.wait_until_ready();
  10412. {
  10413. Client cli(HOST, PORT);
  10414. cli.set_path_encode(false);
  10415. // The request is rejected before anything is written, so the connection
  10416. // stays silent and the subsequent response read would otherwise block for
  10417. // the full default read timeout. Shorten it -- the assertion is on the
  10418. // error, not the timeout.
  10419. cli.set_read_timeout(1, 0);
  10420. auto res = cli.Get("/a\r\nInjected: pwned");
  10421. EXPECT_FALSE(res);
  10422. EXPECT_EQ(Error::Write, res.error());
  10423. }
  10424. }
  10425. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  10426. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  10427. // including extension methods.
  10428. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  10429. for (const auto &method : good_methods) {
  10430. detail::BufferStream strm;
  10431. auto n = detail::write_request_line(strm, method, "/");
  10432. EXPECT_GT(n, 0);
  10433. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  10434. }
  10435. // A method carrying CR/LF would split the request line and smuggle a whole
  10436. // request ahead of the real one. A space or an empty method corrupts the
  10437. // request line. All must be rejected before anything reaches the wire.
  10438. const std::string evil_methods[] = {
  10439. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10440. "GET\r\nInjected: pwned",
  10441. "GET\r",
  10442. "GET\n",
  10443. "GE T",
  10444. "",
  10445. };
  10446. for (const auto &evil : evil_methods) {
  10447. detail::BufferStream strm;
  10448. auto n = detail::write_request_line(strm, evil, "/");
  10449. EXPECT_LT(n, 0);
  10450. EXPECT_TRUE(strm.get_buffer().empty());
  10451. }
  10452. }
  10453. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  10454. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  10455. // through Client::send must fail with Error::Write and no request, neither
  10456. // the smuggled one nor the real one, may reach the server.
  10457. Server svr;
  10458. std::atomic<int> request_count(0);
  10459. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  10460. request_count++;
  10461. res.status = StatusCode::OK_200;
  10462. return Server::HandlerResponse::Handled;
  10463. });
  10464. auto port = svr.bind_to_any_port(HOST);
  10465. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10466. auto se = detail::scope_exit([&] {
  10467. svr.stop();
  10468. thread.join();
  10469. ASSERT_FALSE(svr.is_running());
  10470. });
  10471. svr.wait_until_ready();
  10472. {
  10473. Client cli(HOST, port);
  10474. const std::string evil_methods[] = {
  10475. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  10476. "GE T",
  10477. "",
  10478. };
  10479. for (const auto &evil : evil_methods) {
  10480. Request req;
  10481. req.method = evil;
  10482. req.path = "/";
  10483. auto res = cli.send(req);
  10484. EXPECT_FALSE(res);
  10485. EXPECT_EQ(Error::Write, res.error());
  10486. }
  10487. auto handle =
  10488. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  10489. EXPECT_FALSE(handle.is_valid());
  10490. EXPECT_EQ(Error::Write, handle.error);
  10491. // A valid request on the same client still goes through.
  10492. auto res = cli.Get("/");
  10493. ASSERT_TRUE(res);
  10494. EXPECT_EQ(StatusCode::OK_200, res->status);
  10495. }
  10496. EXPECT_EQ(1, request_count.load());
  10497. }
  10498. // Sends a raw request and verifies that there isn't a crash or exception.
  10499. static void test_raw_request(const std::string &req,
  10500. std::string *out = nullptr) {
  10501. Server svr;
  10502. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10503. res.set_content("ok", "text/plain");
  10504. });
  10505. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  10506. res.set_content("ok", "text/plain");
  10507. });
  10508. svr.Get("/header_field_value_check",
  10509. [&](const Request & /*req*/, Response &res) {
  10510. res.set_content("ok", "text/plain");
  10511. });
  10512. svr.CustomRoute("PROPFIND", "/dav",
  10513. [&](const Request & /*req*/, Response &res) {
  10514. res.status = StatusCode::MultiStatus_207;
  10515. });
  10516. // Server read timeout must be longer than the client read timeout for the
  10517. // bug to reproduce, probably to force the server to process a request
  10518. // without a trailing blank line.
  10519. const time_t client_read_timeout_sec = 1;
  10520. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  10521. bool listen_thread_ok = false;
  10522. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  10523. auto se = detail::scope_exit([&] {
  10524. svr.stop();
  10525. t.join();
  10526. ASSERT_FALSE(svr.is_running());
  10527. EXPECT_TRUE(listen_thread_ok);
  10528. });
  10529. svr.wait_until_ready();
  10530. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  10531. }
  10532. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  10533. // A certain header line causes an exception if the header property is parsed
  10534. // naively with a single regex. This occurs with libc++ but not libstdc++.
  10535. test_raw_request(
  10536. "GET /hi HTTP/1.1\r\n"
  10537. " : "
  10538. " "
  10539. " ");
  10540. }
  10541. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  10542. // A certain header line causes an exception if the header property *name* is
  10543. // parsed with a regular expression starting with "(.+?):" - this is a non-
  10544. // greedy matcher and requires backtracking when there are a lot of ":"
  10545. // characters.
  10546. // This occurs with libc++ but not libstdc++.
  10547. test_raw_request(
  10548. "GET /hi HTTP/1.1\r\n"
  10549. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  10550. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10551. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  10552. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  10553. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  10554. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  10555. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  10556. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  10557. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10558. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10559. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  10560. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10561. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  10562. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  10563. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  10564. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  10565. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  10566. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  10567. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  10568. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  10569. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  10570. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  10571. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  10572. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  10573. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  10574. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  10575. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  10576. "&&&%%%");
  10577. }
  10578. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  10579. // Make sure this doesn't crash the server.
  10580. // In a previous version of the header line regex, the "\r" rendered the line
  10581. // unparsable and the regex engine repeatedly backtracked, trying to look for
  10582. // a new position where the leading white space ended and the field value
  10583. // began.
  10584. // The crash occurs with libc++ but not libstdc++.
  10585. test_raw_request("GET /hi HTTP/1.1\r\n"
  10586. "a:" +
  10587. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  10588. "\r\n"
  10589. "\r\n");
  10590. }
  10591. TEST(ServerRequestParsingTest, StrictRequestLine) {
  10592. const char *rejected[] = {
  10593. // RFC 9112 §3: one SP between the parts, and nothing else
  10594. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10595. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10596. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  10597. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  10598. // A request-target has no fragment
  10599. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  10600. // An HTTP/1.1 request needs a Host
  10601. "GET /hi HTTP/1.1\r\n\r\n",
  10602. };
  10603. for (auto request : rejected) {
  10604. std::string out;
  10605. test_raw_request(request, &out);
  10606. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  10607. }
  10608. std::string out;
  10609. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  10610. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10611. }
  10612. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  10613. // RFC 9112 §6.1
  10614. const char *requests[] = {
  10615. "PUT /put_hi HTTP/1.1\r\n"
  10616. "Host: localhost\r\n"
  10617. "Content-Length: 0\r\n"
  10618. "Transfer-Encoding: chunked\r\n"
  10619. "\r\n"
  10620. "0\r\n\r\n",
  10621. "PUT /put_hi HTTP/1.0\r\n"
  10622. "Connection: keep-alive\r\n"
  10623. "Transfer-Encoding: chunked\r\n"
  10624. "\r\n"
  10625. "0\r\n\r\n",
  10626. };
  10627. for (auto request : requests) {
  10628. std::string out;
  10629. test_raw_request(request, &out);
  10630. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  10631. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  10632. }
  10633. }
  10634. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  10635. std::string out;
  10636. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10637. "Content-Type: text/plain\r\n"
  10638. "Transfer-Encoding: chunked\r\n"
  10639. "\r\n"
  10640. "nothex\r\n",
  10641. &out);
  10642. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10643. }
  10644. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  10645. std::string out;
  10646. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10647. "Content-Type: text/plain\r\n"
  10648. "Transfer-Encoding: chunked\r\n"
  10649. "\r\n"
  10650. "3\r\n"
  10651. "xyz\r\n"
  10652. "NaN\r\n",
  10653. &out);
  10654. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10655. }
  10656. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  10657. std::string out;
  10658. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  10659. "Content-Type: text/plain\r\n"
  10660. "Transfer-Encoding: chunked\r\n"
  10661. "\r\n"
  10662. // Length is too large for 64 bits.
  10663. "1ffffffffffffffff\r\n"
  10664. "xyz\r\n",
  10665. &out);
  10666. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10667. }
  10668. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  10669. test_raw_request("GET /hi HTTP/1.1\r\n"
  10670. "Content-Type: text/plain\r\n\r");
  10671. }
  10672. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  10673. std::string out;
  10674. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  10675. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10676. }
  10677. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  10678. for (auto target : {"/h\ri", "/h\x7fi"}) {
  10679. std::string out;
  10680. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  10681. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  10682. }
  10683. }
  10684. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  10685. std::string out;
  10686. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  10687. "Host: localhost\r\n"
  10688. "Connection: close\r\n\r\n",
  10689. &out);
  10690. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10691. }
  10692. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  10693. Server svr;
  10694. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  10695. EXPECT_TRUE(!req.remote_addr.empty());
  10696. });
  10697. thread t = thread([&] { svr.listen(HOST, PORT); });
  10698. auto se = detail::scope_exit([&] {
  10699. svr.stop();
  10700. t.join();
  10701. ASSERT_FALSE(svr.is_running());
  10702. });
  10703. svr.wait_until_ready();
  10704. // Send an invalid request line to trigger Bad Request
  10705. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  10706. std::string out;
  10707. ASSERT_TRUE(send_request(5, bad_req, &out));
  10708. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10709. }
  10710. // A custom method with neither Content-Length nor Transfer-Encoding must be
  10711. // answered right away rather than blocking on a read that waits for EOF.
  10712. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  10713. std::string out;
  10714. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  10715. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  10716. }
  10717. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  10718. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  10719. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  10720. for (const auto *method : methods) {
  10721. Server svr;
  10722. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10723. EXPECT_FALSE(svr.is_valid()) << method;
  10724. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10725. }
  10726. }
  10727. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10728. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10729. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10730. for (const auto *method : methods) {
  10731. Server svr;
  10732. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10733. EXPECT_FALSE(svr.is_valid()) << method;
  10734. }
  10735. }
  10736. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10737. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10738. "COPY", "MOVE", "LOCK",
  10739. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10740. Server svr;
  10741. for (const auto *method : methods) {
  10742. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10743. }
  10744. EXPECT_TRUE(svr.is_valid());
  10745. }
  10746. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10747. Server svr;
  10748. svr.CustomRoute("POST", "/x",
  10749. [](const Request &, Response &, const ContentReader &) {});
  10750. EXPECT_FALSE(svr.is_valid());
  10751. }
  10752. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10753. Server svr;
  10754. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10755. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10756. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10757. EXPECT_FALSE(svr.is_valid());
  10758. }
  10759. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10760. Server svr;
  10761. auto captured = Error::Success;
  10762. svr.set_error_logger(
  10763. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10764. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10765. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10766. }
  10767. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10768. std::string out;
  10769. std::string request(
  10770. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10771. test_raw_request(request, &out);
  10772. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10773. }
  10774. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10775. std::string out;
  10776. std::string request(
  10777. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10778. test_raw_request(request, &out);
  10779. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10780. }
  10781. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10782. std::string out;
  10783. std::string request(
  10784. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10785. test_raw_request(request, &out);
  10786. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10787. }
  10788. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10789. std::string out;
  10790. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10791. "Host: localhost\r\n"
  10792. "Test: \r\n\r\n",
  10793. &out);
  10794. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10795. }
  10796. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10797. Server svr;
  10798. std::string x_custom;
  10799. std::string cookie;
  10800. std::string xff;
  10801. std::string x_unicode;
  10802. std::string x_iis;
  10803. svr.Get("/check", [&](const Request &req, Response &res) {
  10804. x_custom = req.get_header_value("X-Custom");
  10805. cookie = req.get_header_value("Cookie");
  10806. xff = req.get_header_value("X-Forwarded-For");
  10807. x_unicode = req.get_header_value("X-Unicode");
  10808. x_iis = req.get_header_value("X-IIS");
  10809. res.set_content("ok", "text/plain");
  10810. });
  10811. thread t = thread([&] { svr.listen(HOST, PORT); });
  10812. auto se = detail::scope_exit([&] {
  10813. svr.stop();
  10814. t.join();
  10815. ASSERT_FALSE(svr.is_running());
  10816. });
  10817. svr.wait_until_ready();
  10818. const std::string req = "GET /check HTTP/1.1\r\n"
  10819. "Host: localhost\r\n"
  10820. "X-Custom: a%0D%0AInjected: b\r\n"
  10821. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10822. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10823. "X-Unicode: %E3%81%82\r\n"
  10824. "X-IIS: %u00E9\r\n"
  10825. "Connection: close\r\n"
  10826. "\r\n";
  10827. std::string res;
  10828. ASSERT_TRUE(send_request(5, req, &res));
  10829. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10830. // Every value must be returned verbatim (wire form), with no decoding.
  10831. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10832. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10833. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10834. EXPECT_EQ("%E3%81%82", x_unicode);
  10835. EXPECT_EQ("%u00E9", x_iis);
  10836. }
  10837. // Applications that previously relied on automatic percent-decoding can
  10838. // reproduce the old behavior by explicitly calling decode_path_component()
  10839. // or, for RFC 3986 conformance, decode_uri_component().
  10840. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10841. Server svr;
  10842. std::string decoded;
  10843. svr.Get("/check", [&](const Request &req, Response &res) {
  10844. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10845. res.set_content("ok", "text/plain");
  10846. });
  10847. thread t = thread([&] { svr.listen(HOST, PORT); });
  10848. auto se = detail::scope_exit([&] {
  10849. svr.stop();
  10850. t.join();
  10851. ASSERT_FALSE(svr.is_running());
  10852. });
  10853. svr.wait_until_ready();
  10854. const std::string req = "GET /check HTTP/1.1\r\n"
  10855. "Host: localhost\r\n"
  10856. "X-Custom: hello%20world\r\n"
  10857. "Connection: close\r\n"
  10858. "\r\n";
  10859. std::string res;
  10860. ASSERT_TRUE(send_request(5, req, &res));
  10861. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10862. EXPECT_EQ("hello world", decoded);
  10863. }
  10864. // Regression test for #2033. Browsers send Referer values that include
  10865. // percent-encoded characters such as %0A inside the URL. Decoding the
  10866. // header value would either trip the post-decode CR/LF/NUL guard (the
  10867. // original bug, returning 400) or, after that guard was relaxed, silently
  10868. // store a literal LF — both unacceptable. The wire form must round-trip.
  10869. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10870. Server svr;
  10871. std::string referer;
  10872. svr.Get("/check", [&](const Request &req, Response &res) {
  10873. referer = req.get_header_value("Referer");
  10874. res.set_content("ok", "text/plain");
  10875. });
  10876. thread t = thread([&] { svr.listen(HOST, PORT); });
  10877. auto se = detail::scope_exit([&] {
  10878. svr.stop();
  10879. t.join();
  10880. ASSERT_FALSE(svr.is_running());
  10881. });
  10882. svr.wait_until_ready();
  10883. const std::string req = "GET /check HTTP/1.1\r\n"
  10884. "Host: localhost\r\n"
  10885. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10886. "Connection: close\r\n"
  10887. "\r\n";
  10888. std::string res;
  10889. ASSERT_TRUE(send_request(5, req, &res));
  10890. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10891. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10892. }
  10893. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10894. Server svr;
  10895. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10896. res.set_header("Cache-Control", "no-cache");
  10897. res.set_chunked_content_provider(
  10898. "text/event-stream", [](size_t offset, DataSink &sink) {
  10899. std::string s = "data:";
  10900. s += std::to_string(offset);
  10901. s += "\n\n";
  10902. auto ret = sink.write(s.data(), s.size());
  10903. EXPECT_TRUE(ret);
  10904. std::this_thread::sleep_for(std::chrono::seconds(1));
  10905. return true;
  10906. });
  10907. });
  10908. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10909. svr.wait_until_ready();
  10910. Client client(HOST, PORT);
  10911. const Headers headers = {{"Accept", "text/event-stream"}};
  10912. auto get_thread = std::thread([&client, &headers]() {
  10913. auto res = client.Get(
  10914. "/events", headers,
  10915. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10916. });
  10917. auto se = detail::scope_exit([&] {
  10918. svr.stop();
  10919. get_thread.join();
  10920. listen_thread.join();
  10921. ASSERT_FALSE(svr.is_running());
  10922. });
  10923. // Give GET time to get a few messages.
  10924. std::this_thread::sleep_for(std::chrono::seconds(2));
  10925. }
  10926. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10927. httplib::Server svr;
  10928. svr.Post("/hi",
  10929. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10930. res.status = StatusCode::OK_200;
  10931. });
  10932. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10933. svr.wait_until_ready();
  10934. Client cli(HOST, PORT);
  10935. auto res = cli.Post("/hi", "data", "text/plain");
  10936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10937. EXPECT_EQ(StatusCode::OK_200, res->status);
  10938. svr.stop();
  10939. thread.join();
  10940. ASSERT_FALSE(svr.is_running());
  10941. res = cli.Post("/hi", "data", "text/plain");
  10942. ASSERT_FALSE(res);
  10943. }
  10944. TEST(ServerStopTest, ListenFailure) {
  10945. Server svr;
  10946. auto t = thread([&]() {
  10947. auto ret = svr.listen("????", PORT);
  10948. EXPECT_FALSE(ret);
  10949. });
  10950. svr.wait_until_ready();
  10951. svr.stop();
  10952. t.join();
  10953. }
  10954. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10955. TEST(ServerStopTest, Decommision) {
  10956. Server svr;
  10957. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10958. for (int i = 0; i < 4; i++) {
  10959. auto is_even = !(i % 2);
  10960. std::thread t{[&] {
  10961. try {
  10962. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10963. if (is_even) {
  10964. throw std::runtime_error("Some thing that happens to go wrong.");
  10965. }
  10966. svr.listen(HOST, PORT);
  10967. } catch (...) { svr.decommission(); }
  10968. }};
  10969. svr.wait_until_ready();
  10970. // Server is up
  10971. {
  10972. Client cli(HOST, PORT);
  10973. auto res = cli.Get("/hi");
  10974. if (is_even) {
  10975. EXPECT_FALSE(res);
  10976. } else {
  10977. EXPECT_TRUE(res);
  10978. EXPECT_EQ("hi...", res->body);
  10979. }
  10980. }
  10981. svr.stop();
  10982. t.join();
  10983. // Server is down...
  10984. {
  10985. Client cli(HOST, PORT);
  10986. auto res = cli.Get("/hi");
  10987. EXPECT_FALSE(res);
  10988. }
  10989. }
  10990. }
  10991. #endif
  10992. // Helper function for string body upload progress tests
  10993. template <typename SetupHandler, typename ClientCall>
  10994. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10995. ClientCall &&client_call,
  10996. const string &body) {
  10997. Server svr;
  10998. setup_handler(svr);
  10999. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11000. auto se = detail::scope_exit([&] {
  11001. svr.stop();
  11002. t.join();
  11003. });
  11004. svr.wait_until_ready();
  11005. Client cli(HOST, PORT);
  11006. vector<uint64_t> progress_values;
  11007. bool progress_called = false;
  11008. auto res =
  11009. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11010. progress_values.push_back(current);
  11011. progress_called = true;
  11012. return true;
  11013. });
  11014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11015. EXPECT_EQ(200, res->status);
  11016. EXPECT_TRUE(progress_called);
  11017. }
  11018. TEST(UploadProgressTest, PostStringBodyBasic) {
  11019. TestStringBodyUploadProgress(
  11020. [](Server &svr) {
  11021. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11022. res.set_content("received", "text/plain");
  11023. });
  11024. },
  11025. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11026. return cli.Post("/test", body, "text/plain", progress_callback);
  11027. },
  11028. "test data for upload progress");
  11029. }
  11030. TEST(UploadProgressTest, PutStringBodyBasic) {
  11031. TestStringBodyUploadProgress(
  11032. [](Server &svr) {
  11033. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  11034. res.set_content("put received", "text/plain");
  11035. });
  11036. },
  11037. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11038. return cli.Put("/test", body, "text/plain", progress_callback);
  11039. },
  11040. "put test data for upload progress");
  11041. }
  11042. TEST(UploadProgressTest, PatchStringBodyBasic) {
  11043. TestStringBodyUploadProgress(
  11044. [](Server &svr) {
  11045. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  11046. res.set_content("patch received", "text/plain");
  11047. });
  11048. },
  11049. [](Client &cli, const string &body, UploadProgress progress_callback) {
  11050. return cli.Patch("/test", body, "text/plain", progress_callback);
  11051. },
  11052. "patch test data for upload progress");
  11053. }
  11054. // Helper function for content provider upload progress tests
  11055. template <typename SetupHandler, typename ClientCall>
  11056. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  11057. ClientCall &&client_call) {
  11058. Server svr;
  11059. setup_handler(svr);
  11060. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11061. auto se = detail::scope_exit([&] {
  11062. svr.stop();
  11063. t.join();
  11064. });
  11065. svr.wait_until_ready();
  11066. Client cli(HOST, PORT);
  11067. vector<uint64_t> progress_values;
  11068. auto res =
  11069. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  11070. progress_values.push_back(current);
  11071. return true;
  11072. });
  11073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11074. EXPECT_EQ(200, res->status);
  11075. EXPECT_FALSE(progress_values.empty());
  11076. }
  11077. TEST(UploadProgressTest, PostContentProviderProgress) {
  11078. TestContentProviderUploadProgress(
  11079. [](Server &svr) {
  11080. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  11081. res.set_content("provider received", "text/plain");
  11082. });
  11083. },
  11084. [](Client &cli, UploadProgress progress_callback) {
  11085. return cli.Post(
  11086. "/test", 9,
  11087. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  11088. sink.os << "test data";
  11089. return true;
  11090. },
  11091. "text/plain", progress_callback);
  11092. });
  11093. }
  11094. // Helper function for multipart upload progress tests
  11095. template <typename SetupHandler, typename ClientCall>
  11096. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  11097. ClientCall &&client_call,
  11098. const string &endpoint) {
  11099. Server svr;
  11100. setup_handler(svr);
  11101. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11102. auto se = detail::scope_exit([&] {
  11103. svr.stop();
  11104. t.join();
  11105. });
  11106. svr.wait_until_ready();
  11107. Client cli(HOST, PORT);
  11108. vector<uint64_t> progress_values;
  11109. UploadFormDataItems items = {
  11110. {"field1", "value1", "", ""},
  11111. {"field2", "longer value for progress tracking test", "", ""},
  11112. {"file1", "file content data for upload progress", "test.txt",
  11113. "text/plain"}};
  11114. auto res = client_call(cli, endpoint, items,
  11115. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11116. progress_values.push_back(current);
  11117. return true;
  11118. });
  11119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11120. EXPECT_EQ(200, res->status);
  11121. EXPECT_FALSE(progress_values.empty());
  11122. }
  11123. TEST(UploadProgressTest, PostMultipartProgress) {
  11124. TestMultipartUploadProgress(
  11125. [](Server &svr) {
  11126. svr.Post("/multipart", [](const Request &req, Response &res) {
  11127. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  11128. res.set_content("multipart received", "text/plain");
  11129. });
  11130. },
  11131. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  11132. UploadProgress progress_callback) {
  11133. return cli.Post(endpoint, items, progress_callback);
  11134. },
  11135. "/multipart");
  11136. }
  11137. // Helper function for basic download progress tests
  11138. template <typename SetupHandler, typename ClientCall>
  11139. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  11140. ClientCall &&client_call, const string &endpoint,
  11141. size_t expected_content_size) {
  11142. Server svr;
  11143. setup_handler(svr);
  11144. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11145. auto se = detail::scope_exit([&] {
  11146. svr.stop();
  11147. t.join();
  11148. });
  11149. svr.wait_until_ready();
  11150. Client cli(HOST, PORT);
  11151. vector<uint64_t> progress_values;
  11152. auto res = client_call(cli, endpoint,
  11153. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11154. progress_values.push_back(current);
  11155. return true;
  11156. });
  11157. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11158. EXPECT_EQ(200, res->status);
  11159. EXPECT_FALSE(progress_values.empty());
  11160. EXPECT_EQ(expected_content_size, res->body.size());
  11161. }
  11162. TEST(DownloadProgressTest, GetBasic) {
  11163. TestBasicDownloadProgress(
  11164. [](Server &svr) {
  11165. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  11166. string content(1000, 'D');
  11167. res.set_content(content, "text/plain");
  11168. });
  11169. },
  11170. [](Client &cli, const string &endpoint,
  11171. DownloadProgress progress_callback) {
  11172. return cli.Get(endpoint, progress_callback);
  11173. },
  11174. "/download", 1000u);
  11175. }
  11176. // Helper function for content receiver download progress tests
  11177. template <typename SetupHandler, typename ClientCall>
  11178. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  11179. ClientCall &&client_call,
  11180. const string &endpoint,
  11181. size_t expected_content_size) {
  11182. Server svr;
  11183. setup_handler(svr);
  11184. thread t = thread([&]() { svr.listen(HOST, PORT); });
  11185. auto se = detail::scope_exit([&] {
  11186. svr.stop();
  11187. t.join();
  11188. });
  11189. svr.wait_until_ready();
  11190. Client cli(HOST, PORT);
  11191. vector<uint64_t> progress_values;
  11192. string received_body;
  11193. auto res = client_call(
  11194. cli, endpoint,
  11195. [&](const char *data, size_t data_length) -> bool {
  11196. received_body.append(data, data_length);
  11197. return true;
  11198. },
  11199. [&](uint64_t current, uint64_t /*total*/) -> bool {
  11200. progress_values.push_back(current);
  11201. return true;
  11202. });
  11203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11204. EXPECT_EQ(200, res->status);
  11205. EXPECT_FALSE(progress_values.empty());
  11206. EXPECT_EQ(expected_content_size, received_body.size());
  11207. EXPECT_TRUE(res->body.empty());
  11208. }
  11209. TEST(DownloadProgressTest, GetWithContentReceiver) {
  11210. TestContentReceiverDownloadProgress(
  11211. [](Server &svr) {
  11212. svr.Get("/download-receiver",
  11213. [](const Request & /*req*/, Response &res) {
  11214. string content(2000, 'R');
  11215. res.set_content(content, "text/plain");
  11216. });
  11217. },
  11218. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  11219. DownloadProgress progress_callback) {
  11220. return cli.Get(endpoint, content_receiver, progress_callback);
  11221. },
  11222. "/download-receiver", 2000u);
  11223. }
  11224. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  11225. // A provider reaching a pass with nothing to hand over - an empty buffer
  11226. // popped off a queue, say - must not be taken to mean the body is finished.
  11227. // It used to end the loop with the terminating chunk unwritten while the
  11228. // server still considered the response complete, so the peer waited for an
  11229. // end that never arrived.
  11230. Server svr;
  11231. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11232. auto step = std::make_shared<int>(0);
  11233. res.set_chunked_content_provider("text/plain",
  11234. [step](size_t /*offset*/, DataSink &sink) {
  11235. switch ((*step)++) {
  11236. case 0: sink.write("", 0); break;
  11237. case 1: sink.write("hello", 5); break;
  11238. default: sink.done(); break;
  11239. }
  11240. return true;
  11241. });
  11242. });
  11243. auto port = svr.bind_to_any_port(HOST);
  11244. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11245. auto listen_se = detail::scope_exit([&] {
  11246. svr.stop();
  11247. listen_thread.join();
  11248. ASSERT_FALSE(svr.is_running());
  11249. });
  11250. svr.wait_until_ready();
  11251. Client cli(HOST, port);
  11252. // Without the fix the body is never terminated, so bound the wait rather
  11253. // than letting the test hang on the default read timeout.
  11254. cli.set_read_timeout(5, 0);
  11255. auto res = cli.Get("/stream");
  11256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11257. EXPECT_EQ(StatusCode::OK_200, res->status);
  11258. EXPECT_EQ("hello", res->body);
  11259. }
  11260. TEST(StreamingTest, NoContentLengthStreaming) {
  11261. Server svr;
  11262. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  11263. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  11264. if (offset < 6) {
  11265. sink.os << (offset < 3 ? "a" : "b");
  11266. } else {
  11267. sink.done();
  11268. }
  11269. return true;
  11270. });
  11271. });
  11272. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11273. auto listen_se = detail::scope_exit([&] {
  11274. svr.stop();
  11275. listen_thread.join();
  11276. ASSERT_FALSE(svr.is_running());
  11277. });
  11278. svr.wait_until_ready();
  11279. Client client(HOST, PORT);
  11280. auto get_thread = std::thread([&client]() {
  11281. std::string s;
  11282. auto res =
  11283. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  11284. s += std::string(data, len);
  11285. return true;
  11286. });
  11287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11288. EXPECT_EQ(StatusCode::OK_200, res->status);
  11289. EXPECT_EQ("aaabbb", s);
  11290. });
  11291. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  11292. // Give GET time to get a few messages.
  11293. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  11294. }
  11295. TEST(MountTest, Unmount) {
  11296. Server svr;
  11297. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11298. auto se = detail::scope_exit([&] {
  11299. svr.stop();
  11300. listen_thread.join();
  11301. ASSERT_FALSE(svr.is_running());
  11302. });
  11303. svr.wait_until_ready();
  11304. Client cli("localhost", PORT);
  11305. svr.set_mount_point("/mount2", "./www2");
  11306. auto res = cli.Get("/");
  11307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11308. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11309. res = cli.Get("/mount2/dir/test.html");
  11310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11311. EXPECT_EQ(StatusCode::OK_200, res->status);
  11312. svr.set_mount_point("/", "./www");
  11313. res = cli.Get("/dir/");
  11314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11315. EXPECT_EQ(StatusCode::OK_200, res->status);
  11316. svr.remove_mount_point("/");
  11317. res = cli.Get("/dir/");
  11318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11319. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11320. svr.remove_mount_point("/mount2");
  11321. res = cli.Get("/mount2/dir/test.html");
  11322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11323. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11324. }
  11325. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  11326. Server svr;
  11327. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11328. svr.Get("/api/hello", [](const Request &, Response &res) {
  11329. res.set_content("api", "text/plain");
  11330. });
  11331. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11332. auto se = detail::scope_exit([&] {
  11333. svr.stop();
  11334. listen_thread.join();
  11335. ASSERT_FALSE(svr.is_running());
  11336. });
  11337. svr.wait_until_ready();
  11338. Client cli(HOST, PORT);
  11339. auto res = cli.Get("/dir/test.html");
  11340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11341. EXPECT_EQ(StatusCode::OK_200, res->status);
  11342. res = cli.Get("/api/hello");
  11343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11344. EXPECT_EQ(StatusCode::OK_200, res->status);
  11345. EXPECT_EQ("api", res->body);
  11346. }
  11347. TEST(MountTest, PathSegmentBoundary) {
  11348. Server svr;
  11349. svr.set_mount_point("/mount2", "./www2");
  11350. svr.set_mount_point("/", "./www");
  11351. auto port = svr.bind_to_any_port(HOST);
  11352. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11353. auto se = detail::scope_exit([&] {
  11354. svr.stop();
  11355. listen_thread.join();
  11356. ASSERT_FALSE(svr.is_running());
  11357. });
  11358. svr.wait_until_ready();
  11359. Client cli(HOST, port);
  11360. auto res = cli.Get("/mount2/dir/test.html");
  11361. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11362. EXPECT_EQ(StatusCode::OK_200, res->status);
  11363. // "/mount2" must not match part-way through a path segment.
  11364. res = cli.Get("/mount2dir/test.html");
  11365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11366. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11367. // A mount point ending in '/' keeps matching every path below it.
  11368. res = cli.Get("/dir/test.html");
  11369. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11370. EXPECT_EQ(StatusCode::OK_200, res->status);
  11371. }
  11372. TEST(MountTest, Redicect) {
  11373. Server svr;
  11374. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11375. auto se = detail::scope_exit([&] {
  11376. svr.stop();
  11377. listen_thread.join();
  11378. ASSERT_FALSE(svr.is_running());
  11379. });
  11380. svr.set_mount_point("/", "./www");
  11381. svr.wait_until_ready();
  11382. Client cli("localhost", PORT);
  11383. auto res = cli.Get("/dir/");
  11384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11385. EXPECT_EQ(StatusCode::OK_200, res->status);
  11386. res = cli.Get("/dir");
  11387. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11388. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  11389. res = cli.Get("/file");
  11390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11391. EXPECT_EQ(StatusCode::OK_200, res->status);
  11392. res = cli.Get("/file/");
  11393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11394. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11395. cli.set_follow_location(true);
  11396. res = cli.Get("/dir");
  11397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11398. EXPECT_EQ(StatusCode::OK_200, res->status);
  11399. }
  11400. TEST(MountTest, MultibytesPathName) {
  11401. Server svr;
  11402. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11403. auto se = detail::scope_exit([&] {
  11404. svr.stop();
  11405. listen_thread.join();
  11406. ASSERT_FALSE(svr.is_running());
  11407. });
  11408. svr.set_mount_point("/", "./www");
  11409. svr.wait_until_ready();
  11410. Client cli("localhost", PORT);
  11411. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  11412. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11413. EXPECT_EQ(StatusCode::OK_200, res->status);
  11414. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  11415. }
  11416. // A mount point serves no path with an empty segment or one ending in '.' or
  11417. // a space, so a guard in the pre-routing handler sees the path of every file
  11418. // that is served
  11419. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  11420. Server svr;
  11421. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  11422. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  11423. if (req.path == "/dir/test.html") {
  11424. res.status = StatusCode::Unauthorized_401;
  11425. return Server::HandlerResponse::Handled;
  11426. }
  11427. return Server::HandlerResponse::Unhandled;
  11428. });
  11429. auto port = svr.bind_to_any_port(HOST);
  11430. ASSERT_LT(0, port);
  11431. thread t = thread([&] { svr.listen_after_bind(); });
  11432. auto se = detail::scope_exit([&] {
  11433. svr.stop();
  11434. t.join();
  11435. ASSERT_FALSE(svr.is_running());
  11436. });
  11437. svr.wait_until_ready();
  11438. Client cli(HOST, port);
  11439. for (auto path :
  11440. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  11441. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  11442. "/dir/test.html.", "/dir/test.html%20", "/dir/test.html::$DATA",
  11443. "/dir/test.html%3A%3A$DATA"}) {
  11444. SCOPED_TRACE(path);
  11445. auto res = cli.Get(path);
  11446. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11447. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11448. }
  11449. }
  11450. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  11451. Server svr;
  11452. svr.set_mount_point("/", "./www");
  11453. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  11454. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  11455. auto port = svr.bind_to_any_port(HOST);
  11456. ASSERT_GT(port, 0);
  11457. thread t = thread([&] { svr.listen_after_bind(); });
  11458. auto se = detail::scope_exit([&] {
  11459. svr.stop();
  11460. t.join();
  11461. ASSERT_FALSE(svr.is_running());
  11462. });
  11463. svr.wait_until_ready();
  11464. Client cli(HOST, port);
  11465. auto res = cli.Get("/dir/test.abcde");
  11466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11467. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  11468. res = cli.Get("/dir/test.html");
  11469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11470. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  11471. }
  11472. #ifdef _WIN32
  11473. // Issue #2435: mmap::open() must succeed even when another handle holds
  11474. // the file open for writing (e.g. an active log file).
  11475. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  11476. const char *path = "mmap_concurrent_writer_test.txt";
  11477. const char *content = "hello";
  11478. {
  11479. std::ofstream f(path, std::ios::binary);
  11480. f.write(content, static_cast<std::streamsize>(strlen(content)));
  11481. }
  11482. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11483. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  11484. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  11485. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  11486. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  11487. detail::mmap m(path);
  11488. ASSERT_TRUE(m.is_open());
  11489. EXPECT_EQ(strlen(content), m.size());
  11490. char buf[8];
  11491. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  11492. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  11493. }
  11494. #endif
  11495. #ifndef _WIN32
  11496. // A directory or a device has no size to serve.
  11497. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  11498. const char *path = "./mmap_not_regular_test_dir";
  11499. ASSERT_EQ(0, ::mkdir(path, 0755));
  11500. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  11501. for (auto p : {path, "/dev/null"}) {
  11502. detail::mmap m(p);
  11503. EXPECT_FALSE(m.is_open()) << p;
  11504. EXPECT_EQ(0U, m.size()) << p;
  11505. }
  11506. Server svr;
  11507. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  11508. res.set_file_content("/dev/null");
  11509. });
  11510. auto port = svr.bind_to_any_port(HOST);
  11511. thread t = thread([&] { svr.listen_after_bind(); });
  11512. auto se = detail::scope_exit([&] {
  11513. svr.stop();
  11514. t.join();
  11515. });
  11516. svr.wait_until_ready();
  11517. auto res = Client(HOST, port).Get("/null");
  11518. ASSERT_TRUE(res);
  11519. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11520. }
  11521. #endif
  11522. #ifdef __linux__
  11523. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  11524. TEST(MmapTest, FileIsNotMapped) {
  11525. const char *path = "mmap_not_mapped_test.txt";
  11526. {
  11527. std::ofstream f(path, std::ios::binary);
  11528. f << "hello";
  11529. }
  11530. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  11531. detail::mmap m(path);
  11532. ASSERT_TRUE(m.is_open());
  11533. std::ifstream maps("/proc/self/maps");
  11534. std::string mappings((std::istreambuf_iterator<char>(maps)),
  11535. std::istreambuf_iterator<char>());
  11536. EXPECT_EQ(std::string::npos, mappings.find(path));
  11537. }
  11538. #endif
  11539. TEST(KeepAliveTest, ReadTimeout) {
  11540. Server svr;
  11541. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11542. std::this_thread::sleep_for(std::chrono::seconds(2));
  11543. res.set_content("a", "text/plain");
  11544. });
  11545. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11546. res.set_content("b", "text/plain");
  11547. });
  11548. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11549. auto se = detail::scope_exit([&] {
  11550. svr.stop();
  11551. listen_thread.join();
  11552. ASSERT_FALSE(svr.is_running());
  11553. });
  11554. svr.wait_until_ready();
  11555. Client cli("localhost", PORT);
  11556. cli.set_keep_alive(true);
  11557. cli.set_read_timeout(std::chrono::seconds(1));
  11558. auto resa = cli.Get("/a");
  11559. ASSERT_FALSE(resa);
  11560. EXPECT_EQ(Error::Read, resa.error());
  11561. auto resb = cli.Get("/b");
  11562. ASSERT_TRUE(resb);
  11563. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11564. EXPECT_EQ("b", resb->body);
  11565. }
  11566. TEST(KeepAliveTest, MaxCount) {
  11567. size_t keep_alive_max_count = 3;
  11568. Server svr;
  11569. svr.set_keep_alive_max_count(keep_alive_max_count);
  11570. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11571. res.set_content("Hello World!", "text/plain");
  11572. });
  11573. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11574. auto se = detail::scope_exit([&] {
  11575. svr.stop();
  11576. listen_thread.join();
  11577. ASSERT_FALSE(svr.is_running());
  11578. });
  11579. svr.wait_until_ready();
  11580. Client cli(HOST, PORT);
  11581. cli.set_keep_alive(true);
  11582. for (size_t i = 0; i < 5; i++) {
  11583. auto result = cli.Get("/hi");
  11584. ASSERT_TRUE(result);
  11585. EXPECT_EQ(StatusCode::OK_200, result->status);
  11586. if (i == keep_alive_max_count - 1) {
  11587. EXPECT_EQ("close", result->get_header_value("Connection"));
  11588. } else {
  11589. EXPECT_FALSE(result->has_header("Connection"));
  11590. }
  11591. }
  11592. }
  11593. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  11594. // can pull the next one into the server's buffer. The server must serve it
  11595. // without waiting for the socket to become readable again. The keep-alive
  11596. // timeout outlasts the client's read timeout, so a request left waiting for it
  11597. // shows up as a missing response.
  11598. static void serve_pipelining_routes(Server &svr,
  11599. const std::function<void(int)> &client) {
  11600. svr.set_keep_alive_timeout(5);
  11601. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  11602. res.set_content("hi " + req.matches[1].str(), "text/plain");
  11603. });
  11604. svr.Post("/echo", [](const Request &req, Response &res) {
  11605. res.set_content("echo " + req.body, "text/plain");
  11606. });
  11607. auto port = svr.bind_to_any_port(HOST);
  11608. thread t = thread([&] { svr.listen_after_bind(); });
  11609. auto se = detail::scope_exit([&] {
  11610. svr.stop();
  11611. t.join();
  11612. });
  11613. svr.wait_until_ready();
  11614. client(port);
  11615. }
  11616. static std::string
  11617. send_pipelined_requests(const std::vector<std::string> &parts) {
  11618. Server svr;
  11619. std::string res;
  11620. serve_pipelining_routes(svr, [&](int port) {
  11621. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  11622. });
  11623. return res;
  11624. }
  11625. static void expect_in_order(const std::string &res,
  11626. const std::vector<std::string> &bodies) {
  11627. size_t pos = 0;
  11628. for (const auto &body : bodies) {
  11629. pos = res.find(body, pos);
  11630. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  11631. pos += body.size();
  11632. }
  11633. }
  11634. TEST(KeepAliveTest, PipelinedRequests) {
  11635. auto res = send_pipelined_requests(
  11636. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11637. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11638. "Content-Length: 4\r\n\r\nbody"
  11639. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11640. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  11641. }
  11642. // The second request starts in the server's buffer and ends on the socket.
  11643. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  11644. auto res =
  11645. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11646. "GET /hi/2 HTTP/1.1\r\nHo",
  11647. "st: localhost\r\nConnection: close\r\n\r\n"});
  11648. expect_in_order(res, {"hi 1", "hi 2"});
  11649. }
  11650. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  11651. // CRLF after a body does not turn into a 400 for the next request.
  11652. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  11653. auto res = send_pipelined_requests(
  11654. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  11655. "Content-Length: 4\r\n\r\nbody\r\n"
  11656. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  11657. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  11658. expect_in_order(res, {"echo body", "hi 2"});
  11659. }
  11660. // Where an unparsable request ends is unknown, so what follows it in the buffer
  11661. // must not be served as the next request.
  11662. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  11663. auto res = send_pipelined_requests(
  11664. {"INVALID REQUEST LINE\r\n\r\n"
  11665. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  11666. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  11667. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  11668. }
  11669. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11670. // Over TLS, the next request is held by the TLS library as already decrypted
  11671. // data rather than on the socket.
  11672. TEST(KeepAliveTest, SSLPipelinedRequests) {
  11673. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11674. std::string res;
  11675. serve_pipelining_routes(svr, [&](int port) {
  11676. // One part, so all three requests arrive in one TLS record
  11677. EXPECT_TRUE(send_ssl_request_in_parts(
  11678. 2,
  11679. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11680. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  11681. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  11682. &res, port));
  11683. });
  11684. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  11685. }
  11686. #endif
  11687. TEST(KeepAliveTest, Issue1041) {
  11688. Server svr;
  11689. svr.set_keep_alive_timeout(3);
  11690. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11691. res.set_content("Hello World!", "text/plain");
  11692. });
  11693. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11694. auto se = detail::scope_exit([&] {
  11695. svr.stop();
  11696. listen_thread.join();
  11697. ASSERT_FALSE(svr.is_running());
  11698. });
  11699. svr.wait_until_ready();
  11700. Client cli(HOST, PORT);
  11701. cli.set_keep_alive(true);
  11702. auto result = cli.Get("/hi");
  11703. ASSERT_TRUE(result);
  11704. EXPECT_EQ(StatusCode::OK_200, result->status);
  11705. std::this_thread::sleep_for(std::chrono::seconds(5));
  11706. result = cli.Get("/hi");
  11707. ASSERT_TRUE(result);
  11708. EXPECT_EQ(StatusCode::OK_200, result->status);
  11709. }
  11710. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  11711. Server svr;
  11712. svr.set_keep_alive_max_count(0);
  11713. std::set<int> remote_ports;
  11714. svr.Get("/hi", [&](const Request &req, Response &res) {
  11715. remote_ports.insert(req.remote_port);
  11716. res.set_content("hi", "text/plain");
  11717. });
  11718. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11719. auto se = detail::scope_exit([&] {
  11720. svr.stop();
  11721. listen_thread.join();
  11722. ASSERT_FALSE(svr.is_running());
  11723. });
  11724. svr.wait_until_ready();
  11725. Client cli(HOST, PORT);
  11726. cli.set_keep_alive(true);
  11727. for (int i = 0; i < 3; i++) {
  11728. auto res = cli.Get("/hi");
  11729. ASSERT_TRUE(res);
  11730. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11731. }
  11732. // All three over one connection
  11733. EXPECT_EQ(1u, remote_ports.size());
  11734. }
  11735. // Forward declaration (see the base64_encode note).
  11736. namespace httplib {
  11737. namespace detail {
  11738. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  11739. } // namespace detail
  11740. } // namespace httplib
  11741. // RFC 9112 9.2: an unsolicited 408 must not be read as the next response
  11742. static void expect_no_reuse_with_unread_data(bool use_tls, bool same_write) {
  11743. #ifndef _WIN32
  11744. signal(SIGPIPE, SIG_IGN);
  11745. #endif
  11746. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11747. ASSERT_NE(INVALID_SOCKET, srv);
  11748. auto srv_se = detail::scope_exit([&] { detail::close_socket(srv); });
  11749. default_socket_options(srv);
  11750. sockaddr_in addr{};
  11751. addr.sin_family = AF_INET;
  11752. addr.sin_port = 0;
  11753. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11754. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11755. ASSERT_EQ(0, ::listen(srv, 2));
  11756. socklen_t addr_len = sizeof(addr);
  11757. ASSERT_EQ(0,
  11758. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len));
  11759. auto port = ntohs(addr.sin_port);
  11760. struct Peer {
  11761. socket_t sock = INVALID_SOCKET;
  11762. #ifdef CPPHTTPLIB_SSL_ENABLED
  11763. tls::session_t session = nullptr;
  11764. #endif
  11765. };
  11766. #ifdef CPPHTTPLIB_SSL_ENABLED
  11767. tls::ctx_t ctx = nullptr;
  11768. if (use_tls) {
  11769. ctx = tls::create_server_context();
  11770. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  11771. nullptr);
  11772. }
  11773. auto ctx_se = detail::scope_exit([&] {
  11774. if (ctx) { tls::free_context(ctx); }
  11775. });
  11776. #endif
  11777. auto close_peer = [](Peer &peer) {
  11778. #ifdef CPPHTTPLIB_SSL_ENABLED
  11779. if (peer.session) { tls::free_session(peer.session); }
  11780. #endif
  11781. if (peer.sock != INVALID_SOCKET) { detail::close_socket(peer.sock); }
  11782. };
  11783. auto accept_peer = [&]() {
  11784. Peer peer;
  11785. if (detail::select_read(srv, 5, 0) <= 0) { return peer; }
  11786. peer.sock = ::accept(srv, nullptr, nullptr);
  11787. if (peer.sock == INVALID_SOCKET) { return peer; }
  11788. detail::set_socket_opt_time(peer.sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11789. #ifdef CPPHTTPLIB_SSL_ENABLED
  11790. if (use_tls) {
  11791. peer.session = tls::create_session(ctx, peer.sock);
  11792. tls::TlsError err;
  11793. if (!tls::accept_nonblocking(peer.session, peer.sock, 5, 0, &err,
  11794. nullptr)) {
  11795. close_peer(peer);
  11796. return Peer();
  11797. }
  11798. }
  11799. #endif
  11800. return peer;
  11801. };
  11802. auto read_some = [](const Peer &peer, char *buf, size_t len) -> ssize_t {
  11803. #ifdef CPPHTTPLIB_SSL_ENABLED
  11804. tls::TlsError err;
  11805. if (peer.session) { return tls::read(peer.session, buf, len, err); }
  11806. #endif
  11807. return detail::read_socket(peer.sock, buf, len, 0);
  11808. };
  11809. auto read_head = [&](const Peer &peer) {
  11810. std::string head;
  11811. char buf[1024];
  11812. while (head.find("\r\n\r\n") == std::string::npos) {
  11813. auto n = read_some(peer, buf, sizeof(buf));
  11814. if (n <= 0) { break; }
  11815. head.append(buf, static_cast<size_t>(n));
  11816. }
  11817. };
  11818. auto send_text = [](const Peer &peer, const std::string &text) {
  11819. #ifdef CPPHTTPLIB_SSL_ENABLED
  11820. tls::TlsError err;
  11821. if (peer.session) {
  11822. tls::write(peer.session, text.data(), text.size(), err);
  11823. return;
  11824. }
  11825. #endif
  11826. detail::send_socket(peer.sock, text.data(), text.size(), 0);
  11827. };
  11828. const std::string first = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nfirst";
  11829. const std::string stray = "HTTP/1.1 408 Request Timeout\r\n"
  11830. "Connection: close\r\nContent-Length: 0\r\n\r\n";
  11831. // Sent once the first response is read, so that it lands on an idle socket
  11832. std::promise<void> first_response_read;
  11833. auto first_response_read_future = first_response_read.get_future();
  11834. auto server_thread = std::thread([&] {
  11835. auto peer1 = accept_peer();
  11836. if (peer1.sock == INVALID_SOCKET) { return; }
  11837. read_head(peer1);
  11838. if (same_write) {
  11839. send_text(peer1, first + stray);
  11840. } else {
  11841. send_text(peer1, first);
  11842. first_response_read_future.wait_for(std::chrono::seconds(5));
  11843. send_text(peer1, stray);
  11844. }
  11845. // peer1 stays open, so only the unread data can tell the client
  11846. auto peer2 = accept_peer();
  11847. if (peer2.sock != INVALID_SOCKET) {
  11848. read_head(peer2);
  11849. send_text(peer2, "HTTP/1.1 200 OK\r\nContent-Length: 6\r\n"
  11850. "Connection: close\r\n\r\nsecond");
  11851. close_peer(peer2);
  11852. }
  11853. close_peer(peer1);
  11854. });
  11855. auto server_se = detail::scope_exit([&] { server_thread.join(); });
  11856. Client cli((use_tls ? "https://127.0.0.1:" : "http://127.0.0.1:") +
  11857. std::to_string(port));
  11858. #ifdef CPPHTTPLIB_SSL_ENABLED
  11859. cli.enable_server_certificate_verification(false);
  11860. #endif
  11861. cli.set_keep_alive(true);
  11862. cli.set_read_timeout(5, 0);
  11863. auto res = cli.Get("/1");
  11864. first_response_read.set_value();
  11865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11866. EXPECT_EQ("first", res->body);
  11867. if (!same_write) { ASSERT_GT(detail::select_read(cli.socket(), 5, 0), 0); }
  11868. res = cli.Get("/2");
  11869. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11870. EXPECT_EQ(StatusCode::OK_200, res->status);
  11871. EXPECT_EQ("second", res->body);
  11872. }
  11873. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithUnreadData) {
  11874. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/false);
  11875. }
  11876. TEST(KeepAliveTest, ClientDoesNotReuseConnectionWithDataPastResponse) {
  11877. expect_no_reuse_with_unread_data(/*use_tls=*/false, /*same_write=*/true);
  11878. }
  11879. #ifdef CPPHTTPLIB_SSL_ENABLED
  11880. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithUnreadData) {
  11881. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/false);
  11882. }
  11883. TEST(KeepAliveTest, SSLClientDoesNotReuseConnectionWithDataPastResponse) {
  11884. expect_no_reuse_with_unread_data(/*use_tls=*/true, /*same_write=*/true);
  11885. }
  11886. #endif
  11887. TEST(KeepAliveTest, Issue1959) {
  11888. Server svr;
  11889. svr.set_keep_alive_timeout(5);
  11890. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11891. res.set_content("a", "text/plain");
  11892. });
  11893. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11894. auto se = detail::scope_exit([&] {
  11895. if (!svr.is_running()) return;
  11896. svr.stop();
  11897. listen_thread.join();
  11898. ASSERT_FALSE(svr.is_running());
  11899. });
  11900. svr.wait_until_ready();
  11901. Client cli("localhost", PORT);
  11902. cli.set_keep_alive(true);
  11903. using namespace std::chrono;
  11904. auto start = steady_clock::now();
  11905. cli.Get("/a");
  11906. svr.stop();
  11907. listen_thread.join();
  11908. auto end = steady_clock::now();
  11909. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11910. EXPECT_LT(elapsed, 5000);
  11911. }
  11912. #ifdef CPPHTTPLIB_SSL_ENABLED
  11913. TEST(KeepAliveTest, SSLClientReconnection) {
  11914. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11915. ASSERT_TRUE(svr.is_valid());
  11916. svr.set_keep_alive_timeout(1);
  11917. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11918. res.set_content("Hello World!", "text/plain");
  11919. });
  11920. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11921. auto se = detail::scope_exit([&] {
  11922. svr.stop();
  11923. listen_thread.join();
  11924. ASSERT_FALSE(svr.is_running());
  11925. });
  11926. svr.wait_until_ready();
  11927. SSLClient cli(HOST, PORT);
  11928. cli.enable_server_certificate_verification(false);
  11929. cli.set_keep_alive(true);
  11930. auto result = cli.Get("/hi");
  11931. ASSERT_TRUE(result);
  11932. EXPECT_EQ(StatusCode::OK_200, result->status);
  11933. result = cli.Get("/hi");
  11934. ASSERT_TRUE(result);
  11935. EXPECT_EQ(StatusCode::OK_200, result->status);
  11936. std::this_thread::sleep_for(std::chrono::seconds(2));
  11937. // Recoonect
  11938. result = cli.Get("/hi");
  11939. ASSERT_TRUE(result);
  11940. EXPECT_EQ(StatusCode::OK_200, result->status);
  11941. result = cli.Get("/hi");
  11942. ASSERT_TRUE(result);
  11943. EXPECT_EQ(StatusCode::OK_200, result->status);
  11944. }
  11945. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11946. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11947. ASSERT_TRUE(svr.is_valid());
  11948. svr.set_keep_alive_timeout(1);
  11949. std::string content = "reconnect";
  11950. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11951. res.set_content("Hello World!", "text/plain");
  11952. });
  11953. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11954. auto se = detail::scope_exit([&] {
  11955. svr.stop();
  11956. listen_thread.join();
  11957. ASSERT_FALSE(svr.is_running());
  11958. });
  11959. svr.wait_until_ready();
  11960. SSLClient cli(HOST, PORT);
  11961. cli.enable_server_certificate_verification(false);
  11962. cli.set_keep_alive(true);
  11963. auto result = cli.Post(
  11964. "/hi", content.size(),
  11965. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11966. sink.write(content.c_str(), content.size());
  11967. return true;
  11968. },
  11969. "text/plain");
  11970. ASSERT_TRUE(result);
  11971. EXPECT_EQ(200, result->status);
  11972. std::this_thread::sleep_for(std::chrono::seconds(2));
  11973. // Recoonect
  11974. result = cli.Post(
  11975. "/hi", content.size(),
  11976. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11977. sink.write(content.c_str(), content.size());
  11978. return true;
  11979. },
  11980. "text/plain");
  11981. ASSERT_TRUE(result);
  11982. EXPECT_EQ(200, result->status);
  11983. result = cli.Post(
  11984. "/hi", content.size(),
  11985. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11986. sink.write(content.c_str(), content.size());
  11987. return true;
  11988. },
  11989. "text/plain");
  11990. ASSERT_TRUE(result);
  11991. EXPECT_EQ(200, result->status);
  11992. }
  11993. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11994. using namespace httplib::tls;
  11995. {
  11996. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11997. ASSERT_TRUE(svr.is_valid());
  11998. svr.Get("/sni", [&](const Request &req, Response &res) {
  11999. std::string expected = req.sni();
  12000. EXPECT_EQ(expected, req.get_param_value("expected"));
  12001. res.set_content("ok", "text/plain");
  12002. });
  12003. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  12004. auto se = detail::scope_exit([&] {
  12005. svr.stop();
  12006. listen_thread.join();
  12007. ASSERT_FALSE(svr.is_running());
  12008. });
  12009. svr.wait_until_ready();
  12010. {
  12011. SSLClient cli("localhost", PORT);
  12012. cli.enable_server_certificate_verification(false);
  12013. auto res = cli.Get("/sni?expected=localhost");
  12014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12015. }
  12016. {
  12017. SSLClient cli("::1", PORT);
  12018. cli.enable_server_certificate_verification(false);
  12019. auto res = cli.Get("/sni?expected=");
  12020. // NOTE: This may fail if the server is listening on IPv4 only
  12021. // (e.g., when localhost resolves to 127.0.0.1 only)
  12022. if (res) {
  12023. EXPECT_EQ(StatusCode::OK_200, res->status);
  12024. } else {
  12025. EXPECT_EQ(Error::Connection, res.error());
  12026. }
  12027. }
  12028. }
  12029. }
  12030. // The SNI of a failed handshake does not reach the next connection that the
  12031. // same worker thread serves
  12032. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  12033. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12034. ASSERT_TRUE(svr.is_valid());
  12035. svr.new_task_queue = [] { return new ThreadPool(1); };
  12036. svr.Get("/sni", [](const Request &req, Response &res) {
  12037. res.set_content(req.sni(), "text/plain");
  12038. });
  12039. auto port = svr.bind_to_any_port("127.0.0.1");
  12040. ASSERT_LT(0, port);
  12041. thread t = thread([&] { svr.listen_after_bind(); });
  12042. auto se = detail::scope_exit([&] {
  12043. svr.stop();
  12044. t.join();
  12045. ASSERT_FALSE(svr.is_running());
  12046. });
  12047. svr.wait_until_ready();
  12048. {
  12049. // Sends SNI, then rejects the server certificate, which the CA did not sign
  12050. SSLClient cli("localhost", port);
  12051. cli.set_direct_hostname_addr_map({{"localhost", "127.0.0.1"}});
  12052. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  12053. auto res = cli.Get("/sni");
  12054. ASSERT_FALSE(res);
  12055. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12056. }
  12057. // An IP host sends no SNI (RFC 6066)
  12058. SSLClient cli("127.0.0.1", port);
  12059. cli.enable_server_certificate_verification(false);
  12060. auto res = cli.Get("/sni");
  12061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12062. EXPECT_EQ("", res->body);
  12063. }
  12064. #endif
  12065. TEST(ClientProblemDetectionTest, ContentProvider) {
  12066. Server svr;
  12067. size_t content_length = 1024 * 1024;
  12068. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12069. res.set_content_provider(
  12070. content_length, "text/plain",
  12071. [&](size_t offset, size_t length, DataSink &sink) {
  12072. auto out_len = std::min(length, static_cast<size_t>(1024));
  12073. std::string out(out_len, '@');
  12074. sink.write(out.data(), out_len);
  12075. return offset < 4096;
  12076. },
  12077. [](bool success) { ASSERT_FALSE(success); });
  12078. });
  12079. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  12080. res.set_content_provider(
  12081. 0, "text/plain",
  12082. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  12083. EXPECT_TRUE(false);
  12084. return true;
  12085. },
  12086. [](bool success) { ASSERT_FALSE(success); });
  12087. });
  12088. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12089. auto se = detail::scope_exit([&] {
  12090. svr.stop();
  12091. listen_thread.join();
  12092. ASSERT_FALSE(svr.is_running());
  12093. });
  12094. svr.wait_until_ready();
  12095. Client cli("localhost", PORT);
  12096. {
  12097. auto res = cli.Get("/hi", [&](const char * /*data*/,
  12098. size_t /*data_length*/) { return false; });
  12099. ASSERT_FALSE(res);
  12100. }
  12101. {
  12102. auto res = cli.Get("/empty", [&](const char * /*data*/,
  12103. size_t /*data_length*/) { return false; });
  12104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12105. }
  12106. }
  12107. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  12108. // A provider that reports success without writing anything and without
  12109. // calling done() used to be handed the same offset and length again on every
  12110. // pass, so it spun for as long as the peer stayed connected.
  12111. Server svr;
  12112. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12113. res.set_content("ok", "text/plain");
  12114. });
  12115. auto port = svr.bind_to_any_port(HOST);
  12116. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  12117. auto se = detail::scope_exit([&] {
  12118. svr.stop();
  12119. listen_thread.join();
  12120. ASSERT_FALSE(svr.is_running());
  12121. });
  12122. svr.wait_until_ready();
  12123. std::atomic<int> call_count{0};
  12124. Client cli(HOST, port);
  12125. auto res = cli.Post(
  12126. "/", 1024,
  12127. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  12128. // Give up after enough passes to show the spin, so that losing the
  12129. // check below fails this test instead of hanging it.
  12130. return ++call_count < 100;
  12131. },
  12132. "text/plain");
  12133. ASSERT_FALSE(res);
  12134. EXPECT_EQ(Error::Write, res.error());
  12135. EXPECT_EQ(1, call_count.load());
  12136. }
  12137. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  12138. // A writer only has to assign `write`. The other three used to be left as
  12139. // empty std::functions, so a provider calling one threw
  12140. // std::bad_function_call out of the thread running it and took the whole
  12141. // process down.
  12142. DataSink sink;
  12143. std::string written;
  12144. sink.write = [&](const char *data, size_t data_len) {
  12145. written.append(data, data_len);
  12146. return true;
  12147. };
  12148. EXPECT_TRUE(sink.is_writable());
  12149. sink.done();
  12150. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12151. EXPECT_TRUE(written.empty());
  12152. }
  12153. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  12154. // A sink that cannot carry trailers still has to finish.
  12155. DataSink sink;
  12156. auto done_count = 0;
  12157. sink.done = [&]() { done_count++; };
  12158. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  12159. EXPECT_EQ(1, done_count);
  12160. }
  12161. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  12162. Server svr;
  12163. const std::string body(4096, 'x');
  12164. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12165. res.set_content_provider(body.size(), "text/plain",
  12166. [&](size_t offset, size_t length, DataSink &sink) {
  12167. sink.write(body.data() + offset, length);
  12168. sink.done();
  12169. return true;
  12170. });
  12171. });
  12172. auto port = svr.bind_to_any_port(HOST);
  12173. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12174. auto se = detail::scope_exit([&] {
  12175. svr.stop();
  12176. listen_thread.join();
  12177. ASSERT_FALSE(svr.is_running());
  12178. });
  12179. svr.wait_until_ready();
  12180. Client cli(HOST, port);
  12181. auto res = cli.Get("/");
  12182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12183. EXPECT_EQ(StatusCode::OK_200, res->status);
  12184. EXPECT_EQ(body, res->body);
  12185. }
  12186. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  12187. Server svr;
  12188. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12189. res.set_content_provider(
  12190. 1024, "text/plain",
  12191. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12192. sink.write("hello", 5);
  12193. sink.done(); // short of the 1024 bytes the response promised
  12194. return true;
  12195. });
  12196. });
  12197. auto port = svr.bind_to_any_port(HOST);
  12198. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12199. auto se = detail::scope_exit([&] {
  12200. svr.stop();
  12201. listen_thread.join();
  12202. ASSERT_FALSE(svr.is_running());
  12203. });
  12204. svr.wait_until_ready();
  12205. Client cli(HOST, port);
  12206. cli.set_read_timeout(5, 0);
  12207. // The response is short of its Content-Length, so the client cannot read a
  12208. // complete body. What matters is that this returns at all: a no-op done()
  12209. // would leave the writer looping over a provider that never makes progress.
  12210. auto res = cli.Get("/");
  12211. EXPECT_FALSE(res);
  12212. }
  12213. // Read as the next response by a peer that sees it after a framed body.
  12214. static const std::string smuggled_response =
  12215. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  12216. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  12217. Server svr;
  12218. svr.Get("/", [](const Request & /*req*/, Response &res) {
  12219. res.set_content_provider(
  12220. 5, "text/plain",
  12221. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12222. auto data = "AAAAA" + smuggled_response;
  12223. sink.write(data.data(), data.size());
  12224. return true;
  12225. });
  12226. });
  12227. thread t = thread([&] { svr.listen(HOST, PORT); });
  12228. auto se = detail::scope_exit([&] {
  12229. svr.stop();
  12230. t.join();
  12231. ASSERT_FALSE(svr.is_running());
  12232. });
  12233. svr.wait_until_ready();
  12234. std::string resp;
  12235. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12236. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  12237. resp.clear();
  12238. ASSERT_TRUE(send_request(
  12239. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  12240. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  12241. }
  12242. TEST(NoContentTest, BodyIsNotSent) {
  12243. Server svr;
  12244. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  12245. res.status = StatusCode::NoContent_204;
  12246. res.set_content(smuggled_response, "text/plain");
  12247. });
  12248. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  12249. res.status = StatusCode::NotModified_304;
  12250. res.set_chunked_content_provider(
  12251. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  12252. sink.write(smuggled_response.data(), smuggled_response.size());
  12253. sink.done();
  12254. return true;
  12255. });
  12256. });
  12257. thread t = thread([&] { svr.listen(HOST, PORT); });
  12258. auto se = detail::scope_exit([&] {
  12259. svr.stop();
  12260. t.join();
  12261. ASSERT_FALSE(svr.is_running());
  12262. });
  12263. svr.wait_until_ready();
  12264. for (auto path : {"/204", "/304"}) {
  12265. std::string resp;
  12266. ASSERT_TRUE(send_request(
  12267. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  12268. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  12269. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  12270. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  12271. }
  12272. }
  12273. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  12274. Server svr;
  12275. std::atomic<bool> smuggled(false);
  12276. svr.Post("/", [](const Request & /*req*/, Response &res) {
  12277. res.set_content("ok", "text/plain");
  12278. });
  12279. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  12280. smuggled = true;
  12281. });
  12282. auto port = svr.bind_to_any_port(HOST);
  12283. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12284. auto se = detail::scope_exit([&] {
  12285. svr.stop();
  12286. listen_thread.join();
  12287. ASSERT_FALSE(svr.is_running());
  12288. });
  12289. svr.wait_until_ready();
  12290. // What follows the body would be read as the next request.
  12291. Client cli(HOST, port);
  12292. auto res = cli.Post(
  12293. "/", 5,
  12294. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12295. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  12296. sink.write(data.data(), data.size());
  12297. return true;
  12298. },
  12299. "text/plain");
  12300. ASSERT_FALSE(res);
  12301. EXPECT_EQ(Error::Write, res.error());
  12302. EXPECT_FALSE(smuggled);
  12303. }
  12304. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12305. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  12306. // The compressed path builds the whole body before connecting, so this
  12307. // fails client-side and never reaches a server.
  12308. Client cli(HOST, PORT);
  12309. cli.set_compress(true);
  12310. auto res = cli.Post(
  12311. "/", 1024,
  12312. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  12313. sink.write("hello", 5);
  12314. sink.done(); // short of the 1024 bytes the request announced
  12315. return true;
  12316. },
  12317. "text/plain");
  12318. ASSERT_FALSE(res);
  12319. EXPECT_EQ(Error::Write, res.error());
  12320. }
  12321. TEST(ClientRequestFramingTest, CompressedBodyReplacesCallerContentLength) {
  12322. Server svr;
  12323. std::string received;
  12324. size_t content_length_count = 0;
  12325. bool has_transfer_encoding = true;
  12326. svr.Post("/echo", [&](const Request &req, Response &res) {
  12327. received = req.body;
  12328. content_length_count = req.get_header_value_count("Content-Length");
  12329. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12330. res.set_content("ok", "text/plain");
  12331. });
  12332. svr.Get("/next", [](const Request &, Response &res) {
  12333. res.set_content("next", "text/plain");
  12334. });
  12335. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12336. auto se = detail::scope_exit([&] {
  12337. svr.stop();
  12338. listen_thread.join();
  12339. ASSERT_FALSE(svr.is_running());
  12340. });
  12341. svr.wait_until_ready();
  12342. Client cli(HOST, PORT);
  12343. cli.set_keep_alive(true);
  12344. cli.set_compress(true);
  12345. const std::string body = "hello world";
  12346. Headers headers = {{"Content-Length", std::to_string(body.size())}};
  12347. auto res = cli.Post("/echo", headers, body, "text/plain");
  12348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12349. EXPECT_EQ(StatusCode::OK_200, res->status);
  12350. EXPECT_EQ(body, received);
  12351. EXPECT_EQ(1u, content_length_count);
  12352. EXPECT_FALSE(has_transfer_encoding);
  12353. // The rest of a truncated body would be read as this request
  12354. auto res2 = cli.Get("/next");
  12355. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  12356. EXPECT_EQ(StatusCode::OK_200, res2->status);
  12357. EXPECT_EQ("next", res2->body);
  12358. }
  12359. #endif
  12360. TEST(ClientRequestFramingTest, ChunkedProviderDropsCallerContentLength) {
  12361. Server svr;
  12362. std::string received;
  12363. size_t content_length_count = 1;
  12364. bool has_transfer_encoding = false;
  12365. svr.Post("/echo", [&](const Request &req, Response &res) {
  12366. received = req.body;
  12367. content_length_count = req.get_header_value_count("Content-Length");
  12368. has_transfer_encoding = req.has_header("Transfer-Encoding");
  12369. res.set_content("ok", "text/plain");
  12370. });
  12371. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12372. auto se = detail::scope_exit([&] {
  12373. svr.stop();
  12374. listen_thread.join();
  12375. ASSERT_FALSE(svr.is_running());
  12376. });
  12377. svr.wait_until_ready();
  12378. Client cli(HOST, PORT);
  12379. cli.set_keep_alive(true);
  12380. const std::string body = "hello world";
  12381. Headers headers = {{"Content-Length", "5"}};
  12382. auto res = cli.Post(
  12383. "/echo", headers,
  12384. [&](size_t /*offset*/, DataSink &sink) {
  12385. sink.write(body.data(), body.size());
  12386. sink.done();
  12387. return true;
  12388. },
  12389. "text/plain");
  12390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12391. EXPECT_EQ(StatusCode::OK_200, res->status);
  12392. EXPECT_EQ(body, received);
  12393. EXPECT_EQ(0u, content_length_count);
  12394. EXPECT_TRUE(has_transfer_encoding);
  12395. }
  12396. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  12397. Server svr;
  12398. svr.set_error_handler([](Request const &, Response &res) -> void {
  12399. res.set_chunked_content_provider(
  12400. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12401. sink.os << "hello";
  12402. sink.os << "world";
  12403. sink.done();
  12404. return true;
  12405. });
  12406. });
  12407. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12408. auto se = detail::scope_exit([&] {
  12409. svr.stop();
  12410. listen_thread.join();
  12411. ASSERT_FALSE(svr.is_running());
  12412. });
  12413. svr.wait_until_ready();
  12414. Client cli("localhost", PORT);
  12415. auto res = cli.Get("/");
  12416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12417. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12418. EXPECT_EQ("helloworld", res->body);
  12419. }
  12420. // A body set after a content provider must replace it, not be sent through it.
  12421. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  12422. Server svr;
  12423. svr.set_mount_point("/", "./www");
  12424. svr.set_file_request_handler([](const Request &req, Response &res) {
  12425. if (req.path == "/dir/test.html") {
  12426. res.status = StatusCode::Forbidden_403;
  12427. res.set_content(std::string(5000, 'D'), "text/plain");
  12428. } else if (req.path == "/file") {
  12429. res.status = StatusCode::Forbidden_403;
  12430. res.body = "Denied";
  12431. }
  12432. });
  12433. auto port = svr.bind_to_any_port(HOST);
  12434. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12435. auto se = detail::scope_exit([&] {
  12436. svr.stop();
  12437. t.join();
  12438. ASSERT_FALSE(svr.is_running());
  12439. });
  12440. svr.wait_until_ready();
  12441. Client cli(HOST, port);
  12442. {
  12443. auto res = cli.Get("/dir/test.html");
  12444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12445. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12446. EXPECT_EQ(std::string(5000, 'D'), res->body);
  12447. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  12448. }
  12449. {
  12450. auto res = cli.Get("/file");
  12451. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12452. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  12453. EXPECT_EQ("Denied", res->body);
  12454. }
  12455. {
  12456. auto res = cli.Get("/dir/index.html");
  12457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12458. EXPECT_EQ(StatusCode::OK_200, res->status);
  12459. EXPECT_EQ(0U, res->body.find("<html>"));
  12460. }
  12461. }
  12462. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12463. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  12464. Server svr;
  12465. std::vector<bool> released;
  12466. std::mutex released_mutex;
  12467. auto releaser = [&](bool success) {
  12468. std::lock_guard<std::mutex> guard(released_mutex);
  12469. released.push_back(success);
  12470. };
  12471. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  12472. return sink.write(&"hello"[offset], length);
  12473. };
  12474. svr.Get("/sized", [&](const Request &, Response &res) {
  12475. res.status = StatusCode::NotFound_404;
  12476. res.set_content_provider(5, "text/plain", provider, releaser);
  12477. });
  12478. svr.Get("/chunked", [&](const Request &, Response &res) {
  12479. res.status = StatusCode::ServiceUnavailable_503;
  12480. res.set_chunked_content_provider(
  12481. "text/plain",
  12482. [](size_t, DataSink &sink) {
  12483. sink.os << "chunk";
  12484. sink.done();
  12485. return true;
  12486. },
  12487. releaser);
  12488. });
  12489. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  12490. res.set_content_provider(5, "text/plain", provider, releaser);
  12491. throw std::runtime_error("after the provider");
  12492. });
  12493. svr.set_error_handler([](const Request &req, Response &res) {
  12494. // Leave the exception handler's content to it.
  12495. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  12496. res.set_content(std::string(1000, 'E'), "text/html");
  12497. return Server::HandlerResponse::Handled;
  12498. });
  12499. svr.set_exception_handler(
  12500. [](const Request &, Response &res, std::exception_ptr) {
  12501. res.status = StatusCode::InternalServerError_500;
  12502. res.set_content(std::string(1000, 'X'), "text/html");
  12503. });
  12504. auto port = svr.bind_to_any_port(HOST);
  12505. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12506. auto se = detail::scope_exit([&] {
  12507. svr.stop();
  12508. t.join();
  12509. ASSERT_FALSE(svr.is_running());
  12510. });
  12511. svr.wait_until_ready();
  12512. Client cli(HOST, port);
  12513. {
  12514. auto res = cli.Get("/sized");
  12515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12516. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  12517. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12518. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  12519. }
  12520. {
  12521. auto res = cli.Get("/chunked");
  12522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12523. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  12524. EXPECT_EQ(std::string(1000, 'E'), res->body);
  12525. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  12526. }
  12527. {
  12528. auto res = cli.Get("/throw");
  12529. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12530. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  12531. EXPECT_EQ(std::string(1000, 'X'), res->body);
  12532. }
  12533. std::lock_guard<std::mutex> guard(released_mutex);
  12534. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  12535. }
  12536. #endif
  12537. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  12538. Server svr;
  12539. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  12540. return sink.write(&"abc"[offset], length);
  12541. };
  12542. svr.Get("/file-then-body", [](const Request &, Response &res) {
  12543. res.set_file_content("./www/dir/test.html");
  12544. res.set_content("body", "text/plain");
  12545. });
  12546. svr.Get("/body-then-file", [](const Request &, Response &res) {
  12547. res.set_content(std::string(100, 'B'), "text/plain");
  12548. res.set_file_content("./www/dir/test.html");
  12549. });
  12550. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  12551. res.set_content(std::string(100, 'B'), "text/plain");
  12552. res.set_content_provider(3, "text/x-provider", abc);
  12553. });
  12554. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  12555. res.set_content_provider(3, "text/x-provider", abc);
  12556. res.set_content(std::string(100, 'B'), "text/plain");
  12557. });
  12558. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  12559. res.set_content_provider(3, "text/x-provider", abc);
  12560. res.set_file_content("./www/dir/test.html", "text/x-file");
  12561. });
  12562. svr.Get("/file-then-header", [](const Request &, Response &res) {
  12563. res.set_file_content("./www/dir/test.html");
  12564. res.set_header("Content-Type", "text/x-handler");
  12565. });
  12566. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  12567. res.set_content_provider(3, "text/plain", abc);
  12568. res.body = "direct";
  12569. });
  12570. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  12571. res.set_file_content("./www/dir/test.html");
  12572. res.body = "direct";
  12573. });
  12574. auto port = svr.bind_to_any_port(HOST);
  12575. auto t = std::thread([&]() { svr.listen_after_bind(); });
  12576. auto se = detail::scope_exit([&] {
  12577. svr.stop();
  12578. t.join();
  12579. ASSERT_FALSE(svr.is_running());
  12580. });
  12581. svr.wait_until_ready();
  12582. Client cli(HOST, port);
  12583. auto expect_body = [&](const char *path, const std::string &body,
  12584. const std::string &type) {
  12585. // Uncompressed, so Content-Length can be compared with the body.
  12586. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  12587. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  12588. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12589. EXPECT_EQ(body, res->body) << path;
  12590. EXPECT_EQ(std::to_string(body.size()),
  12591. res->get_header_value("Content-Length"))
  12592. << path;
  12593. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  12594. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  12595. };
  12596. expect_body("/file-then-body", "body", "text/plain");
  12597. expect_body("/body-then-file", "test.html", "text/html");
  12598. expect_body("/body-then-provider", "abc", "text/x-provider");
  12599. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  12600. expect_body("/provider-then-file", "test.html", "text/x-file");
  12601. expect_body("/file-then-header", "test.html", "text/x-handler");
  12602. expect_body("/provider-then-direct-body", "direct", "text/plain");
  12603. expect_body("/file-then-direct-body", "direct", "text/plain");
  12604. // Ranges are checked against the body, not the dropped provider.
  12605. {
  12606. auto res = cli.Get("/provider-then-direct-body",
  12607. Headers{{make_range_header({{1, 2}})}});
  12608. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12609. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12610. EXPECT_EQ("ir", res->body);
  12611. }
  12612. {
  12613. auto res = cli.Get("/file-then-direct-body",
  12614. Headers{{make_range_header({{7, 8}})}});
  12615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12616. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  12617. }
  12618. }
  12619. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  12620. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  12621. const char *path = "./truncated_while_served.txt";
  12622. const size_t size = 32 * 1024 * 1024;
  12623. {
  12624. std::ofstream f(path, std::ios::binary);
  12625. f << std::string(size, 'x');
  12626. }
  12627. auto se_file = detail::scope_exit([&] { std::remove(path); });
  12628. // Over TLS, where the bytes are encrypted in this process rather than
  12629. // copied by send().
  12630. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12631. svr.Get("/file", [&](const Request &, Response &res) {
  12632. res.set_file_content(path, "text/plain");
  12633. });
  12634. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12635. auto se = detail::scope_exit([&] {
  12636. svr.stop();
  12637. thread.join();
  12638. ASSERT_FALSE(svr.is_running());
  12639. });
  12640. svr.wait_until_ready();
  12641. // The file shrinks once the first bytes are in, as a rewrite in place
  12642. // would, and reading the mapping past its new end used to raise SIGBUS.
  12643. SSLClient cli(HOST, PORT);
  12644. cli.enable_server_certificate_verification(false);
  12645. size_t received = 0;
  12646. auto res = cli.Get("/file", [&](const char *, size_t len) {
  12647. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  12648. received += len;
  12649. return true;
  12650. });
  12651. EXPECT_FALSE(res);
  12652. EXPECT_LT(received, size);
  12653. }
  12654. #endif
  12655. // Forward declaration (see the base64_encode note).
  12656. namespace httplib {
  12657. namespace detail {
  12658. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  12659. const std::string &content_type,
  12660. EncodingType encoding);
  12661. } // namespace detail
  12662. } // namespace httplib
  12663. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  12664. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  12665. ASSERT_TRUE(mm->is_open());
  12666. Response res;
  12667. detail::set_file_content_provider(res, mm, "text/html",
  12668. detail::EncodingType::None);
  12669. std::string out;
  12670. DataSink sink;
  12671. sink.write = [&](const char *d, size_t l) {
  12672. out.append(d, l);
  12673. return true;
  12674. };
  12675. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  12676. EXPECT_EQ("test.html", out);
  12677. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  12678. EXPECT_EQ("test.html", out);
  12679. }
  12680. TEST(LongPollingTest, ClientCloseDetection) {
  12681. Server svr;
  12682. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12683. res.set_chunked_content_provider(
  12684. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12685. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12686. sink.os << "hello";
  12687. auto count = 10;
  12688. while (count > 0 && sink.is_writable()) {
  12689. this_thread::sleep_for(chrono::milliseconds(10));
  12690. count--;
  12691. }
  12692. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  12693. return true;
  12694. });
  12695. });
  12696. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12697. auto se = detail::scope_exit([&] {
  12698. svr.stop();
  12699. listen_thread.join();
  12700. ASSERT_FALSE(svr.is_running());
  12701. });
  12702. svr.wait_until_ready();
  12703. Client cli("localhost", PORT);
  12704. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12705. EXPECT_EQ("hello", string(data, data_length));
  12706. return false; // close the socket immediately.
  12707. });
  12708. ASSERT_FALSE(res);
  12709. }
  12710. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  12711. Server svr;
  12712. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  12713. res.set_chunked_content_provider(
  12714. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  12715. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  12716. sink.os << "hello";
  12717. EXPECT_TRUE(sink.os.good());
  12718. // Wait for the client to close the connection
  12719. auto count = 10;
  12720. while (count > 0 && sink.is_writable()) {
  12721. this_thread::sleep_for(chrono::milliseconds(10));
  12722. count--;
  12723. }
  12724. // After client disconnect, write repeatedly until the socket
  12725. // write actually fails (small writes may be absorbed by the
  12726. // kernel buffer)
  12727. std::string chunk(1024, 'x');
  12728. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  12729. sink.os << chunk;
  12730. }
  12731. EXPECT_TRUE(sink.os.fail());
  12732. return true;
  12733. });
  12734. });
  12735. auto port = svr.bind_to_any_port("localhost");
  12736. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12737. auto se = detail::scope_exit([&] {
  12738. svr.stop();
  12739. listen_thread.join();
  12740. ASSERT_FALSE(svr.is_running());
  12741. });
  12742. svr.wait_until_ready();
  12743. Client cli("localhost", port);
  12744. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  12745. EXPECT_EQ("hello", string(data, data_length));
  12746. return false; // close the socket immediately.
  12747. });
  12748. ASSERT_FALSE(res);
  12749. }
  12750. TEST(GetWithParametersTest, GetWithParameters) {
  12751. Server svr;
  12752. svr.Get("/", [&](const Request &req, Response &) {
  12753. EXPECT_EQ("world", req.get_param_value("hello"));
  12754. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12755. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12756. });
  12757. svr.Get("/params", [&](const Request &req, Response &) {
  12758. EXPECT_EQ("world", req.get_param_value("hello"));
  12759. EXPECT_EQ("world2", req.get_param_value("hello2"));
  12760. EXPECT_EQ("world3", req.get_param_value("hello3"));
  12761. });
  12762. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  12763. EXPECT_EQ("resource-id", req.matches[1]);
  12764. EXPECT_EQ("foo", req.get_param_value("param1"));
  12765. EXPECT_EQ("bar", req.get_param_value("param2"));
  12766. });
  12767. svr.Get("/users/:id", [&](const Request &req, Response &) {
  12768. EXPECT_EQ("user-id", req.path_params.at("id"));
  12769. EXPECT_EQ("foo", req.get_param_value("param1"));
  12770. EXPECT_EQ("bar", req.get_param_value("param2"));
  12771. });
  12772. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  12773. auto se = detail::scope_exit([&] {
  12774. svr.stop();
  12775. listen_thread.join();
  12776. ASSERT_FALSE(svr.is_running());
  12777. });
  12778. svr.wait_until_ready();
  12779. {
  12780. Client cli(HOST, PORT);
  12781. Params params;
  12782. params.emplace("hello", "world");
  12783. params.emplace("hello2", "world2");
  12784. params.emplace("hello3", "world3");
  12785. auto res = cli.Get("/", params, Headers{});
  12786. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12787. EXPECT_EQ(StatusCode::OK_200, res->status);
  12788. }
  12789. {
  12790. Client cli(HOST, PORT);
  12791. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  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("/resources/resource-id?param1=foo&param2=bar");
  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("/users/user-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. TEST(GetWithParametersTest, GetWithParameters2) {
  12809. Server svr;
  12810. svr.Get("/", [&](const Request &req, Response &res) {
  12811. auto text = req.get_param_value("hello");
  12812. res.set_content(text, "text/plain");
  12813. });
  12814. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12815. auto se = detail::scope_exit([&] {
  12816. svr.stop();
  12817. listen_thread.join();
  12818. ASSERT_FALSE(svr.is_running());
  12819. });
  12820. svr.wait_until_ready();
  12821. Client cli("localhost", PORT);
  12822. Params params;
  12823. params.emplace("hello", "world");
  12824. std::string body;
  12825. auto res = cli.Get("/", params, Headers{},
  12826. [&](const char *data, size_t data_length) {
  12827. body.append(data, data_length);
  12828. return true;
  12829. });
  12830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12831. EXPECT_EQ(StatusCode::OK_200, res->status);
  12832. EXPECT_EQ("world", body);
  12833. }
  12834. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  12835. Server svr;
  12836. svr.Get("/search", [&](const Request &req, Response &res) {
  12837. auto q = req.get_param_value("q");
  12838. res.set_content(q, "text/plain");
  12839. });
  12840. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12841. auto se = detail::scope_exit([&] {
  12842. svr.stop();
  12843. listen_thread.join();
  12844. ASSERT_FALSE(svr.is_running());
  12845. });
  12846. svr.wait_until_ready();
  12847. Client cli("localhost", PORT);
  12848. // Verify that Get(path, params) works without requiring Headers argument
  12849. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  12850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12851. EXPECT_EQ(StatusCode::OK_200, res->status);
  12852. EXPECT_EQ("cpp-httplib", res->body);
  12853. }
  12854. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  12855. auto host = "httpbingo.org";
  12856. auto path = std::string{"/range/32"};
  12857. #ifdef CPPHTTPLIB_SSL_ENABLED
  12858. SSLClient cli(host);
  12859. #else
  12860. Client cli(host);
  12861. #endif
  12862. cli.set_default_headers({make_range_header({{1, 10}})});
  12863. cli.set_connection_timeout(5);
  12864. {
  12865. auto res = retry_service_failures([&] { return cli.Get(path); });
  12866. SKIP_ON_SERVICE_FAILURE(res);
  12867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12868. EXPECT_EQ("bcdefghijk", res->body);
  12869. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12870. }
  12871. {
  12872. auto res = retry_service_failures([&] { return cli.Get(path); });
  12873. SKIP_ON_SERVICE_FAILURE(res);
  12874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12875. EXPECT_EQ("bcdefghijk", res->body);
  12876. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  12877. }
  12878. }
  12879. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  12880. Server svr;
  12881. svr.set_default_headers({{"Hello", "World"}});
  12882. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  12883. res.set_content("ok", "text/plain");
  12884. });
  12885. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12886. auto se = detail::scope_exit([&] {
  12887. svr.stop();
  12888. listen_thread.join();
  12889. ASSERT_FALSE(svr.is_running());
  12890. });
  12891. svr.wait_until_ready();
  12892. Client cli("localhost", PORT);
  12893. auto res = cli.Get("/");
  12894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12895. EXPECT_EQ(StatusCode::OK_200, res->status);
  12896. EXPECT_EQ("ok", res->body);
  12897. EXPECT_EQ("World", res->get_header_value("Hello"));
  12898. }
  12899. #ifdef CPPHTTPLIB_SSL_ENABLED
  12900. TEST(KeepAliveTest, ReadTimeoutSSL) {
  12901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12902. ASSERT_TRUE(svr.is_valid());
  12903. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  12904. std::this_thread::sleep_for(std::chrono::seconds(2));
  12905. res.set_content("a", "text/plain");
  12906. });
  12907. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  12908. res.set_content("b", "text/plain");
  12909. });
  12910. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  12911. auto se = detail::scope_exit([&] {
  12912. svr.stop();
  12913. listen_thread.join();
  12914. ASSERT_FALSE(svr.is_running());
  12915. });
  12916. svr.wait_until_ready();
  12917. SSLClient cli("localhost", PORT);
  12918. cli.enable_server_certificate_verification(false);
  12919. cli.set_keep_alive(true);
  12920. cli.set_read_timeout(std::chrono::seconds(1));
  12921. auto resa = cli.Get("/a");
  12922. ASSERT_TRUE(!resa);
  12923. EXPECT_EQ(Error::Read, resa.error());
  12924. auto resb = cli.Get("/b");
  12925. ASSERT_TRUE(resb);
  12926. EXPECT_EQ(StatusCode::OK_200, resb->status);
  12927. EXPECT_EQ("b", resb->body);
  12928. }
  12929. // Closing an idle keep-alive connection sends close_notify and returns. The
  12930. // server must not wait for the client's close_notify: an idle client never
  12931. // sends one, so the worker would be held until the read timeout expires, and
  12932. // stop() would wait for it.
  12933. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  12934. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12935. ASSERT_TRUE(svr.is_valid());
  12936. svr.set_keep_alive_timeout(1);
  12937. svr.set_read_timeout(10, 0);
  12938. svr.Get("/", [](const Request &, Response &res) {
  12939. res.set_content("ok", "text/plain");
  12940. });
  12941. auto port = svr.bind_to_any_port(HOST);
  12942. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  12943. auto se = detail::scope_exit([&] {
  12944. if (listen_thread.joinable()) {
  12945. svr.stop();
  12946. listen_thread.join();
  12947. }
  12948. });
  12949. svr.wait_until_ready();
  12950. SSLClient cli(HOST, port);
  12951. cli.enable_server_certificate_verification(false);
  12952. cli.set_keep_alive(true);
  12953. auto res = cli.Get("/");
  12954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12955. EXPECT_EQ(StatusCode::OK_200, res->status);
  12956. // Stay idle past the keep-alive timeout so the server closes the connection.
  12957. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12958. auto start = std::chrono::steady_clock::now();
  12959. svr.stop();
  12960. listen_thread.join();
  12961. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12962. std::chrono::steady_clock::now() - start)
  12963. .count();
  12964. EXPECT_LT(elapsed, 3000);
  12965. }
  12966. #endif
  12967. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12968. protected:
  12969. ServerTestWithAI_PASSIVE()
  12970. : cli_(HOST, PORT)
  12971. #ifdef CPPHTTPLIB_SSL_ENABLED
  12972. ,
  12973. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12974. #endif
  12975. {
  12976. #ifdef CPPHTTPLIB_SSL_ENABLED
  12977. cli_.enable_server_certificate_verification(false);
  12978. #endif
  12979. }
  12980. virtual void SetUp() {
  12981. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12982. res.set_content("Hello World!", "text/plain");
  12983. });
  12984. t_ = thread(
  12985. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12986. svr_.wait_until_ready();
  12987. }
  12988. virtual void TearDown() {
  12989. svr_.stop();
  12990. t_.join();
  12991. }
  12992. #ifdef CPPHTTPLIB_SSL_ENABLED
  12993. SSLClient cli_;
  12994. SSLServer svr_;
  12995. #else
  12996. Client cli_;
  12997. Server svr_;
  12998. #endif
  12999. thread t_;
  13000. };
  13001. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  13002. auto res = cli_.Get("/hi");
  13003. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13004. EXPECT_EQ(StatusCode::OK_200, res->status);
  13005. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  13006. EXPECT_EQ("Hello World!", res->body);
  13007. }
  13008. class ServerUpDownTest : public ::testing::Test {
  13009. protected:
  13010. ServerUpDownTest() : cli_(HOST, PORT) {}
  13011. virtual void SetUp() {
  13012. t_ = thread([&]() {
  13013. svr_.bind_to_any_port(HOST);
  13014. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  13015. ASSERT_TRUE(svr_.listen_after_bind());
  13016. });
  13017. svr_.wait_until_ready();
  13018. }
  13019. virtual void TearDown() {
  13020. svr_.stop();
  13021. t_.join();
  13022. }
  13023. Client cli_;
  13024. Server svr_;
  13025. thread t_;
  13026. };
  13027. TEST_F(ServerUpDownTest, QuickStartStop) {
  13028. // Should not crash, especially when run with
  13029. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  13030. }
  13031. class PayloadMaxLengthTest : public ::testing::Test {
  13032. protected:
  13033. PayloadMaxLengthTest()
  13034. : cli_(HOST, PORT)
  13035. #ifdef CPPHTTPLIB_SSL_ENABLED
  13036. ,
  13037. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13038. #endif
  13039. {
  13040. #ifdef CPPHTTPLIB_SSL_ENABLED
  13041. cli_.enable_server_certificate_verification(false);
  13042. #endif
  13043. }
  13044. virtual void SetUp() {
  13045. svr_.set_payload_max_length(8);
  13046. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13047. res.set_content("test", "text/plain");
  13048. });
  13049. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13050. svr_.wait_until_ready();
  13051. }
  13052. virtual void TearDown() {
  13053. svr_.stop();
  13054. t_.join();
  13055. }
  13056. #ifdef CPPHTTPLIB_SSL_ENABLED
  13057. SSLClient cli_;
  13058. SSLServer svr_;
  13059. #else
  13060. Client cli_;
  13061. Server svr_;
  13062. #endif
  13063. thread t_;
  13064. };
  13065. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  13066. auto res = cli_.Post("/test", "123456789", "text/plain");
  13067. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13068. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13069. res = cli_.Post("/test", "12345678", "text/plain");
  13070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13071. EXPECT_EQ(StatusCode::OK_200, res->status);
  13072. }
  13073. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  13074. // Test chunked encoding with payload exceeding the 8-byte limit
  13075. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  13076. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  13077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13078. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13079. }
  13080. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  13081. // Test chunked encoding with payload within the 8-byte limit
  13082. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  13083. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  13084. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13085. EXPECT_EQ(StatusCode::OK_200, res->status);
  13086. }
  13087. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  13088. // Test using send_request to send chunked data exceeding payload limit
  13089. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  13090. "Host: " +
  13091. std::string(HOST) + ":" + std::to_string(PORT) +
  13092. "\r\n"
  13093. "Transfer-Encoding: chunked\r\n"
  13094. "Connection: close\r\n"
  13095. "\r\n"
  13096. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  13097. "0123456789\r\n"
  13098. "0\r\n" // End chunk
  13099. "\r\n";
  13100. std::string response;
  13101. bool result = send_request(1, chunked_request, &response);
  13102. if (!result) {
  13103. // If send_request fails, it might be because the server closed the
  13104. // connection due to payload limit enforcement, which is acceptable
  13105. SUCCEED()
  13106. << "Server rejected oversized chunked request (connection closed)";
  13107. } else {
  13108. // If we got a response, check if it's an error response or connection was
  13109. // closed early Short response length indicates connection was closed due to
  13110. // payload limit
  13111. if (response.length() <= 10) {
  13112. SUCCEED() << "Server closed connection for oversized chunked request";
  13113. } else {
  13114. // Check for error status codes
  13115. EXPECT_TRUE(response.find("413") != std::string::npos ||
  13116. response.find("Payload Too Large") != std::string::npos ||
  13117. response.find("400") != std::string::npos);
  13118. }
  13119. }
  13120. }
  13121. class LargePayloadMaxLengthTest : public ::testing::Test {
  13122. protected:
  13123. LargePayloadMaxLengthTest()
  13124. : cli_(HOST, PORT)
  13125. #ifdef CPPHTTPLIB_SSL_ENABLED
  13126. ,
  13127. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  13128. #endif
  13129. {
  13130. #ifdef CPPHTTPLIB_SSL_ENABLED
  13131. cli_.enable_server_certificate_verification(false);
  13132. #endif
  13133. }
  13134. virtual void SetUp() {
  13135. // Set 10MB payload limit
  13136. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  13137. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  13138. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  13139. res.set_content("Large payload test", "text/plain");
  13140. });
  13141. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  13142. svr_.wait_until_ready();
  13143. }
  13144. virtual void TearDown() {
  13145. svr_.stop();
  13146. t_.join();
  13147. }
  13148. #ifdef CPPHTTPLIB_SSL_ENABLED
  13149. SSLClient cli_;
  13150. SSLServer svr_;
  13151. #else
  13152. Client cli_;
  13153. Server svr_;
  13154. #endif
  13155. thread t_;
  13156. };
  13157. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  13158. // Test chunked encoding with payload within 10MB limit
  13159. std::string medium_payload(5 * 1024 * 1024,
  13160. 'A'); // 5MB payload, within 10MB limit
  13161. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  13162. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13163. EXPECT_EQ(StatusCode::OK_200, res->status);
  13164. }
  13165. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  13166. // Test chunked encoding with payload exceeding 10MB limit
  13167. std::string large_payload(12 * 1024 * 1024,
  13168. 'B'); // 12MB payload, exceeds 10MB limit
  13169. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  13170. // Server may either return 413 or close the connection
  13171. if (res) {
  13172. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13173. } else {
  13174. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  13175. }
  13176. }
  13177. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  13178. Server svr;
  13179. svr.Get("/", [](const Request &, Response &res) {
  13180. // Claims the most the client accepts, far more than it sends, then drops
  13181. // the connection.
  13182. res.set_content_provider(std::string().max_size(), "text/plain",
  13183. [](size_t, size_t, DataSink &sink) {
  13184. sink.write("abc", 3);
  13185. return false;
  13186. });
  13187. });
  13188. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13189. auto se = detail::scope_exit([&] {
  13190. svr.stop();
  13191. thread.join();
  13192. ASSERT_FALSE(svr.is_running());
  13193. });
  13194. svr.wait_until_ready();
  13195. Client cli(HOST, PORT);
  13196. cli.set_payload_max_length(0);
  13197. EXPECT_FALSE(cli.Get("/"));
  13198. }
  13199. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  13200. // Stream API does, not as a plain read failure
  13201. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  13202. Server svr;
  13203. svr.Get("/big", [](const Request &, Response &res) {
  13204. res.set_content(std::string(100000, 'b'), "text/plain");
  13205. });
  13206. auto port = svr.bind_to_any_port(HOST);
  13207. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  13208. auto se = detail::scope_exit([&] {
  13209. svr.stop();
  13210. thread.join();
  13211. });
  13212. svr.wait_until_ready();
  13213. Client cli(HOST, port);
  13214. cli.set_payload_max_length(1000);
  13215. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  13216. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13217. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  13218. [](const char *, size_t) { return true; });
  13219. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13220. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13221. // Small on the wire, over the limit once decompressed
  13222. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  13223. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  13224. #endif
  13225. }
  13226. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13227. // `payload_max_length` is not enforced on decompressed body in ContentReader
  13228. // path.
  13229. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  13230. Server svr;
  13231. const size_t LIMIT = 64 * 1024; // 64KB
  13232. svr.set_payload_max_length(LIMIT);
  13233. size_t total = 0;
  13234. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  13235. const ContentReader &content_reader) {
  13236. content_reader([&](const char * /*data*/, size_t len) {
  13237. total += len;
  13238. return true;
  13239. });
  13240. res.status = 200;
  13241. res.set_content("stream_ok", "text/plain");
  13242. });
  13243. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  13244. auto se = detail::scope_exit([&] {
  13245. svr.stop();
  13246. thread.join();
  13247. ASSERT_FALSE(svr.is_running());
  13248. });
  13249. svr.wait_until_ready();
  13250. // Prepare 256KB raw data and gzip-compress it
  13251. std::string raw(256 * 1024, 'A');
  13252. std::string gz;
  13253. {
  13254. z_stream zs{};
  13255. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  13256. Z_DEFAULT_STRATEGY);
  13257. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  13258. zs.avail_in = static_cast<uInt>(raw.size());
  13259. char outbuf[4096];
  13260. int ret;
  13261. do {
  13262. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  13263. zs.avail_out = sizeof(outbuf);
  13264. ret = deflate(&zs, Z_FINISH);
  13265. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  13266. } while (ret != Z_STREAM_END);
  13267. deflateEnd(&zs);
  13268. }
  13269. Client cli(HOST, PORT);
  13270. cli.set_connection_timeout(std::chrono::seconds(5));
  13271. Headers headers = {{"Content-Encoding", "gzip"}};
  13272. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  13273. "application/octet-stream");
  13274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13275. // Server must reject oversized decompressed payloads with 413.
  13276. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  13277. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  13278. EXPECT_LE(total, LIMIT);
  13279. }
  13280. #endif
  13281. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  13282. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  13283. // the payload must be passed through untouched instead of being rejected.
  13284. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  13285. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13286. Server svr;
  13287. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  13288. res.set_content(body, "image/jpeg");
  13289. res.set_header("Content-Encoding", "UTF-8");
  13290. });
  13291. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  13292. res.set_content(body, "image/jpeg");
  13293. res.set_header("Content-Encoding", "identity");
  13294. });
  13295. svr.Post("/echo", [](const Request &req, Response &res) {
  13296. res.set_content(req.body, "image/jpeg");
  13297. });
  13298. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13299. auto se = detail::scope_exit([&] {
  13300. svr.stop();
  13301. t.join();
  13302. ASSERT_FALSE(svr.is_running());
  13303. });
  13304. svr.wait_until_ready();
  13305. Client cli(HOST, PORT);
  13306. {
  13307. auto res = cli.Get("/image");
  13308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13309. EXPECT_EQ(StatusCode::OK_200, res->status);
  13310. EXPECT_EQ(body, res->body);
  13311. }
  13312. {
  13313. auto res = cli.Get("/identity");
  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. // The same applies to a request body reaching the server.
  13320. Headers headers = {{"Content-Encoding", "UTF-8"}};
  13321. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  13322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13323. EXPECT_EQ(StatusCode::OK_200, res->status);
  13324. EXPECT_EQ(body, res->body);
  13325. }
  13326. }
  13327. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  13328. // gzip-encoded response even when the build has no zlib support.
  13329. static const char GZIPPED_HELLO_WORLD[] = {
  13330. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  13331. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  13332. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  13333. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  13334. // A content coding is a whole token, not something the field value merely
  13335. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  13336. // as "fibre" look like Brotli, and turned a multi-coding value like
  13337. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  13338. // it was never meant to see.
  13339. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  13340. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13341. Server svr;
  13342. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  13343. res.set_content(body, "image/jpeg");
  13344. res.set_header("Content-Encoding", "fibre");
  13345. });
  13346. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  13347. res.set_content(body, "image/jpeg");
  13348. res.set_header("Content-Encoding", "gzip, br");
  13349. });
  13350. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  13351. res.set_content(body, "image/jpeg");
  13352. res.set_header("Content-Encoding", "x-zstd-ish");
  13353. });
  13354. auto port = svr.bind_to_any_port(HOST);
  13355. thread t = thread([&]() { svr.listen_after_bind(); });
  13356. auto se = detail::scope_exit([&] {
  13357. svr.stop();
  13358. t.join();
  13359. ASSERT_FALSE(svr.is_running());
  13360. });
  13361. svr.wait_until_ready();
  13362. Client cli(HOST, port);
  13363. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  13364. auto res = cli.Get(path);
  13365. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13366. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13367. // Not a coding we recognize, so the payload comes back untouched
  13368. EXPECT_EQ(body, res->body) << path;
  13369. }
  13370. }
  13371. // A content coding cpp-httplib recognizes but was not built with must be
  13372. // reported as such. Handing the still-compressed payload back to the caller
  13373. // would silently corrupt it.
  13374. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  13375. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13376. Server svr;
  13377. // "image/jpeg" keeps the server from applying a content coding of its own,
  13378. // so the hand-crafted Content-Encoding below survives.
  13379. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  13380. res.set_content(gzipped, "image/jpeg");
  13381. res.set_header("Content-Encoding", "gzip");
  13382. });
  13383. // Content codings are case-insensitive (RFC 9110 8.4.1).
  13384. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  13385. res.set_content(gzipped, "image/jpeg");
  13386. res.set_header("Content-Encoding", "GZIP");
  13387. });
  13388. thread t = thread([&]() { svr.listen(HOST, PORT); });
  13389. auto se = detail::scope_exit([&] {
  13390. svr.stop();
  13391. t.join();
  13392. ASSERT_FALSE(svr.is_running());
  13393. });
  13394. svr.wait_until_ready();
  13395. Client cli(HOST, PORT);
  13396. {
  13397. auto res = cli.Get("/gzipped");
  13398. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13399. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13400. EXPECT_EQ("Hello World!", res->body);
  13401. #else
  13402. ASSERT_FALSE(res);
  13403. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13404. #endif
  13405. }
  13406. {
  13407. // open_stream() must behave the same way.
  13408. auto handle = cli.open_stream("GET", "/gzipped");
  13409. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13410. ASSERT_TRUE(handle.is_valid());
  13411. std::string received;
  13412. char buf[256];
  13413. ssize_t n;
  13414. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  13415. received.append(buf, static_cast<size_t>(n));
  13416. }
  13417. EXPECT_EQ("Hello World!", received);
  13418. #else
  13419. EXPECT_FALSE(handle.is_valid());
  13420. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  13421. #endif
  13422. }
  13423. {
  13424. // A differently-cased coding must not be mistaken for an unknown one, or
  13425. // the body would be handed back still compressed.
  13426. auto res = cli.Get("/gzipped-uppercase");
  13427. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13429. EXPECT_EQ("Hello World!", res->body);
  13430. #else
  13431. ASSERT_FALSE(res);
  13432. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  13433. #endif
  13434. }
  13435. }
  13436. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  13437. // A handler serving pre-compressed content (e.g. build-time gzipped static
  13438. // assets) sets Content-Encoding itself. The server used to pick a coding from
  13439. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  13440. // body a second time and appending a second Content-Encoding field line, so
  13441. // clients that decode one coding per listed value handed back raw gzip bytes.
  13442. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  13443. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13444. Server svr;
  13445. // text/plain is a compressible type, so only the pre-set Content-Encoding
  13446. // keeps the server from applying a coding of its own.
  13447. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13448. res.set_content(gzipped, "text/plain");
  13449. res.set_header("Content-Encoding", "gzip");
  13450. });
  13451. auto port = svr.bind_to_any_port(HOST);
  13452. thread t = thread([&]() { svr.listen_after_bind(); });
  13453. auto se = detail::scope_exit([&] {
  13454. svr.stop();
  13455. t.join();
  13456. ASSERT_FALSE(svr.is_running());
  13457. });
  13458. svr.wait_until_ready();
  13459. Client cli(HOST, port);
  13460. Headers headers = {{"Accept-Encoding", "gzip"}};
  13461. auto res = cli.Get("/pre-gzipped", headers);
  13462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13463. EXPECT_EQ(StatusCode::OK_200, res->status);
  13464. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13465. EXPECT_EQ("Hello World!", res->body);
  13466. }
  13467. // set_compress(false) sends every handler response as it is, buffered or
  13468. // streamed
  13469. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  13470. const std::string text(1000, 'a');
  13471. Server svr;
  13472. svr.set_compress(false);
  13473. svr.Get("/buffered", [&](const Request &, Response &res) {
  13474. res.set_content(text, "text/plain");
  13475. });
  13476. svr.Get("/streamed", [&](const Request &, Response &res) {
  13477. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  13478. sink.write(text.data(), text.size());
  13479. sink.done();
  13480. return true;
  13481. });
  13482. });
  13483. auto port = svr.bind_to_any_port(HOST);
  13484. ASSERT_LT(0, port);
  13485. thread t = thread([&] { svr.listen_after_bind(); });
  13486. auto se = detail::scope_exit([&] {
  13487. svr.stop();
  13488. t.join();
  13489. ASSERT_FALSE(svr.is_running());
  13490. });
  13491. svr.wait_until_ready();
  13492. Client cli(HOST, port);
  13493. cli.set_decompress(false);
  13494. for (auto path : {"/buffered", "/streamed"}) {
  13495. SCOPED_TRACE(path);
  13496. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  13497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13498. EXPECT_FALSE(res->has_header("Content-Encoding"));
  13499. EXPECT_EQ(text, res->body);
  13500. }
  13501. }
  13502. // A chunked provider settles its coding where the headers are written and
  13503. // reuses it at write time. Both ends of that have to hold: a handler's own
  13504. // Content-Encoding suppresses the coding, and a response without one is still
  13505. // compressed as it always was.
  13506. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  13507. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  13508. const std::string plain = "Hello World! Hello World! Hello World!";
  13509. Server svr;
  13510. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  13511. res.set_header("Content-Encoding", "gzip");
  13512. res.set_chunked_content_provider(
  13513. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  13514. sink.write(gzipped.data(), gzipped.size());
  13515. sink.done();
  13516. return true;
  13517. });
  13518. });
  13519. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  13520. res.set_chunked_content_provider(
  13521. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  13522. sink.write(plain.data(), plain.size());
  13523. sink.done();
  13524. return true;
  13525. });
  13526. });
  13527. auto port = svr.bind_to_any_port(HOST);
  13528. thread t = thread([&]() { svr.listen_after_bind(); });
  13529. auto se = detail::scope_exit([&] {
  13530. svr.stop();
  13531. t.join();
  13532. ASSERT_FALSE(svr.is_running());
  13533. });
  13534. svr.wait_until_ready();
  13535. Client cli(HOST, port);
  13536. Headers headers = {{"Accept-Encoding", "gzip"}};
  13537. {
  13538. auto res = cli.Get("/pre-gzipped", headers);
  13539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13540. EXPECT_EQ(StatusCode::OK_200, res->status);
  13541. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  13542. EXPECT_EQ("Hello World!", res->body);
  13543. }
  13544. {
  13545. auto res = cli.Get("/negotiated", headers);
  13546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13547. EXPECT_EQ(StatusCode::OK_200, res->status);
  13548. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  13549. EXPECT_EQ(plain, res->body);
  13550. }
  13551. }
  13552. #endif
  13553. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  13554. // the same message as the comma-joined one, so both have to be read the same
  13555. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  13556. // single gzip coding, and a body the sender says was encoded twice was handed
  13557. // back after one pass, still compressed but presented as decoded.
  13558. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  13559. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  13560. Server svr;
  13561. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  13562. res.set_content(body, "image/jpeg");
  13563. res.headers.emplace("Content-Encoding", "gzip");
  13564. res.headers.emplace("Content-Encoding", "gzip");
  13565. });
  13566. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  13567. res.set_content(body, "image/jpeg");
  13568. res.set_header("Content-Encoding", "gzip, gzip");
  13569. });
  13570. auto port = svr.bind_to_any_port(HOST);
  13571. thread t = thread([&]() { svr.listen_after_bind(); });
  13572. auto se = detail::scope_exit([&] {
  13573. svr.stop();
  13574. t.join();
  13575. ASSERT_FALSE(svr.is_running());
  13576. });
  13577. svr.wait_until_ready();
  13578. Client cli(HOST, port);
  13579. // Two codings is not something cpp-httplib decodes, so both representations
  13580. // take the pass-through path rather than one of them being gunzipped once.
  13581. for (const char *path : {"/split", "/joined"}) {
  13582. auto res = cli.Get(path);
  13583. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  13584. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  13585. EXPECT_EQ(body, res->body) << path;
  13586. }
  13587. }
  13588. // Regression test for DoS vulnerability: a malicious server sending a response
  13589. // without Content-Length header must not cause unbounded memory consumption on
  13590. // the client side. The client should stop reading after a reasonable limit,
  13591. // similar to the server-side set_payload_max_length protection.
  13592. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  13593. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13594. #ifndef _WIN32
  13595. signal(SIGPIPE, SIG_IGN);
  13596. #endif
  13597. auto server_thread = std::thread([] {
  13598. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  13599. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13600. default_socket_options(srv);
  13601. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13602. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13603. sockaddr_in addr{};
  13604. addr.sin_family = AF_INET;
  13605. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13606. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13607. int opt = 1;
  13608. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13609. #ifdef _WIN32
  13610. reinterpret_cast<const char *>(&opt),
  13611. #else
  13612. &opt,
  13613. #endif
  13614. sizeof(opt));
  13615. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13616. ::listen(srv, 1);
  13617. sockaddr_in cli_addr{};
  13618. socklen_t cli_len = sizeof(cli_addr);
  13619. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13620. if (cli != INVALID_SOCKET) {
  13621. char buf[4096];
  13622. ::recv(cli, buf, sizeof(buf), 0);
  13623. // Malicious response: no Content-Length, no chunked encoding
  13624. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13625. "Connection: close\r\n"
  13626. "\r\n";
  13627. ::send(cli,
  13628. #ifdef _WIN32
  13629. static_cast<const char *>(response_header.c_str()),
  13630. static_cast<int>(response_header.size()),
  13631. #else
  13632. response_header.c_str(), response_header.size(),
  13633. #endif
  13634. 0);
  13635. // Send 10MB of data
  13636. std::string chunk(64 * 1024, 'A');
  13637. size_t total_sent = 0;
  13638. while (total_sent < MALICIOUS_DATA_SIZE) {
  13639. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  13640. auto sent = ::send(cli,
  13641. #ifdef _WIN32
  13642. static_cast<const char *>(chunk.c_str()),
  13643. static_cast<int>(to_send),
  13644. #else
  13645. chunk.c_str(), to_send,
  13646. #endif
  13647. 0);
  13648. if (sent <= 0) break;
  13649. total_sent += static_cast<size_t>(sent);
  13650. }
  13651. detail::close_socket(cli);
  13652. }
  13653. detail::close_socket(srv);
  13654. });
  13655. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13656. size_t total_read = 0;
  13657. {
  13658. Client cli("127.0.0.1", PORT + 2);
  13659. cli.set_read_timeout(5, 0);
  13660. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13661. auto stream = cli.open_stream("GET", "/malicious");
  13662. ASSERT_TRUE(stream.is_valid());
  13663. char buffer[64 * 1024];
  13664. ssize_t n;
  13665. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13666. total_read += static_cast<size_t>(n);
  13667. }
  13668. } // StreamHandle and Client destroyed here, closing the socket
  13669. server_thread.join();
  13670. // With set_payload_max_length, the client must stop reading before consuming
  13671. // all 10MB. The read loop should be cut off at or near the configured limit.
  13672. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  13673. << "Client read " << total_read << " bytes, exceeding the configured "
  13674. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  13675. }
  13676. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  13677. // the entire response body without truncation.
  13678. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  13679. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  13680. #ifndef _WIN32
  13681. signal(SIGPIPE, SIG_IGN);
  13682. #endif
  13683. auto server_thread = std::thread([] {
  13684. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13685. default_socket_options(srv);
  13686. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13687. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13688. sockaddr_in addr{};
  13689. addr.sin_family = AF_INET;
  13690. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13691. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13692. int opt = 1;
  13693. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13694. #ifdef _WIN32
  13695. reinterpret_cast<const char *>(&opt),
  13696. #else
  13697. &opt,
  13698. #endif
  13699. sizeof(opt));
  13700. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13701. ::listen(srv, 1);
  13702. sockaddr_in cli_addr{};
  13703. socklen_t cli_len = sizeof(cli_addr);
  13704. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13705. if (cli != INVALID_SOCKET) {
  13706. char buf[4096];
  13707. ::recv(cli, buf, sizeof(buf), 0);
  13708. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13709. "Connection: close\r\n"
  13710. "\r\n";
  13711. ::send(cli,
  13712. #ifdef _WIN32
  13713. static_cast<const char *>(response_header.c_str()),
  13714. static_cast<int>(response_header.size()),
  13715. #else
  13716. response_header.c_str(), response_header.size(),
  13717. #endif
  13718. 0);
  13719. std::string chunk(64 * 1024, 'A');
  13720. size_t total_sent = 0;
  13721. while (total_sent < DATA_SIZE) {
  13722. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13723. auto sent = ::send(cli,
  13724. #ifdef _WIN32
  13725. static_cast<const char *>(chunk.c_str()),
  13726. static_cast<int>(to_send),
  13727. #else
  13728. chunk.c_str(), to_send,
  13729. #endif
  13730. 0);
  13731. if (sent <= 0) break;
  13732. total_sent += static_cast<size_t>(sent);
  13733. }
  13734. #ifdef _WIN32
  13735. ::shutdown(cli, SD_SEND);
  13736. #else
  13737. ::shutdown(cli, SHUT_WR);
  13738. #endif
  13739. // Drain until the client closes its end, ensuring all data is delivered
  13740. char drain[1024];
  13741. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13742. detail::close_socket(cli);
  13743. }
  13744. detail::close_socket(srv);
  13745. });
  13746. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13747. size_t total_read = 0;
  13748. {
  13749. Client cli("127.0.0.1", PORT + 2);
  13750. cli.set_read_timeout(5, 0);
  13751. cli.set_payload_max_length(0); // 0 means no limit
  13752. auto stream = cli.open_stream("GET", "/data");
  13753. ASSERT_TRUE(stream.is_valid());
  13754. char buffer[64 * 1024];
  13755. ssize_t n;
  13756. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13757. total_read += static_cast<size_t>(n);
  13758. }
  13759. }
  13760. server_thread.join();
  13761. EXPECT_EQ(total_read, DATA_SIZE)
  13762. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  13763. << " bytes without truncation, but only read " << total_read << " bytes.";
  13764. }
  13765. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  13766. // enormous Content-Length must not cause the client to pre-allocate a huge
  13767. // response body buffer. The reservation is capped at payload_max_length_, and
  13768. // the read itself fails when the body exceeds the limit.
  13769. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  13770. #ifndef _WIN32
  13771. signal(SIGPIPE, SIG_IGN);
  13772. #endif
  13773. auto server_thread = std::thread([] {
  13774. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13775. default_socket_options(srv);
  13776. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13777. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13778. sockaddr_in addr{};
  13779. addr.sin_family = AF_INET;
  13780. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13781. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13782. int opt = 1;
  13783. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13784. #ifdef _WIN32
  13785. reinterpret_cast<const char *>(&opt),
  13786. #else
  13787. &opt,
  13788. #endif
  13789. sizeof(opt));
  13790. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13791. ::listen(srv, 1);
  13792. sockaddr_in cli_addr{};
  13793. socklen_t cli_len = sizeof(cli_addr);
  13794. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13795. if (cli != INVALID_SOCKET) {
  13796. char buf[4096];
  13797. ::recv(cli, buf, sizeof(buf), 0);
  13798. // Malicious response: claim a 20GB body but send only a tiny payload.
  13799. std::string response = "HTTP/1.1 200 OK\r\n"
  13800. "Content-Length: 20000000000\r\n"
  13801. "\r\n"
  13802. "abc";
  13803. ::send(cli,
  13804. #ifdef _WIN32
  13805. static_cast<const char *>(response.c_str()),
  13806. static_cast<int>(response.size()),
  13807. #else
  13808. response.c_str(), response.size(),
  13809. #endif
  13810. 0);
  13811. detail::close_socket(cli);
  13812. }
  13813. detail::close_socket(srv);
  13814. });
  13815. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13816. {
  13817. Client cli("127.0.0.1", PORT + 2);
  13818. cli.set_read_timeout(5, 0);
  13819. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  13820. // result in a 20GB pre-allocation. The Get() call is expected to fail
  13821. // (server claims more bytes than payload_max_length permits), but it must
  13822. // not exhaust memory before getting there.
  13823. auto res = cli.Get("/malicious");
  13824. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  13825. }
  13826. server_thread.join();
  13827. }
  13828. // Verify that content_receiver bypasses the default payload_max_length,
  13829. // allowing streaming downloads larger than 100MB without requiring an explicit
  13830. // set_payload_max_length call.
  13831. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  13832. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13833. #ifndef _WIN32
  13834. signal(SIGPIPE, SIG_IGN);
  13835. #endif
  13836. auto server_thread = std::thread([] {
  13837. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13838. default_socket_options(srv);
  13839. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13840. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13841. sockaddr_in addr{};
  13842. addr.sin_family = AF_INET;
  13843. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13844. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13845. int opt = 1;
  13846. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13847. #ifdef _WIN32
  13848. reinterpret_cast<const char *>(&opt),
  13849. #else
  13850. &opt,
  13851. #endif
  13852. sizeof(opt));
  13853. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13854. ::listen(srv, 1);
  13855. sockaddr_in cli_addr{};
  13856. socklen_t cli_len = sizeof(cli_addr);
  13857. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13858. if (cli != INVALID_SOCKET) {
  13859. char buf[4096];
  13860. ::recv(cli, buf, sizeof(buf), 0);
  13861. // Response with Content-Length larger than default 100MB limit
  13862. auto content_length = std::to_string(DATA_SIZE);
  13863. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13864. "Content-Length: " +
  13865. content_length +
  13866. "\r\n"
  13867. "Connection: close\r\n"
  13868. "\r\n";
  13869. ::send(cli,
  13870. #ifdef _WIN32
  13871. static_cast<const char *>(response_header.c_str()),
  13872. static_cast<int>(response_header.size()),
  13873. #else
  13874. response_header.c_str(), response_header.size(),
  13875. #endif
  13876. 0);
  13877. std::string chunk(64 * 1024, 'A');
  13878. size_t total_sent = 0;
  13879. while (total_sent < DATA_SIZE) {
  13880. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13881. auto sent = ::send(cli,
  13882. #ifdef _WIN32
  13883. static_cast<const char *>(chunk.c_str()),
  13884. static_cast<int>(to_send),
  13885. #else
  13886. chunk.c_str(), to_send,
  13887. #endif
  13888. 0);
  13889. if (sent <= 0) break;
  13890. total_sent += static_cast<size_t>(sent);
  13891. }
  13892. detail::close_socket(cli);
  13893. }
  13894. detail::close_socket(srv);
  13895. });
  13896. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13897. size_t total_received = 0;
  13898. {
  13899. Client cli("127.0.0.1", PORT + 2);
  13900. cli.set_read_timeout(10, 0);
  13901. // Do NOT call set_payload_max_length — use the default 100MB limit
  13902. auto res =
  13903. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13904. total_received += data_length;
  13905. return true;
  13906. });
  13907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13908. EXPECT_EQ(StatusCode::OK_200, res->status);
  13909. }
  13910. server_thread.join();
  13911. EXPECT_EQ(total_received, DATA_SIZE)
  13912. << "With content_receiver, the client should read all " << DATA_SIZE
  13913. << " bytes despite the default 100MB payload_max_length, but only read "
  13914. << total_received << " bytes.";
  13915. }
  13916. // Verify that an explicit set_payload_max_length smaller than the response is
  13917. // enforced even when a content_receiver is used.
  13918. TEST(ClientVulnerabilityTest,
  13919. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  13920. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13921. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  13922. #ifndef _WIN32
  13923. signal(SIGPIPE, SIG_IGN);
  13924. #endif
  13925. auto server_thread = std::thread([] {
  13926. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13927. default_socket_options(srv);
  13928. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13929. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13930. sockaddr_in addr{};
  13931. addr.sin_family = AF_INET;
  13932. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13933. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13934. int opt = 1;
  13935. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13936. #ifdef _WIN32
  13937. reinterpret_cast<const char *>(&opt),
  13938. #else
  13939. &opt,
  13940. #endif
  13941. sizeof(opt));
  13942. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13943. ::listen(srv, 1);
  13944. sockaddr_in cli_addr{};
  13945. socklen_t cli_len = sizeof(cli_addr);
  13946. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13947. if (cli != INVALID_SOCKET) {
  13948. char buf[4096];
  13949. ::recv(cli, buf, sizeof(buf), 0);
  13950. auto content_length = std::to_string(DATA_SIZE);
  13951. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13952. "Content-Length: " +
  13953. content_length +
  13954. "\r\n"
  13955. "Connection: close\r\n"
  13956. "\r\n";
  13957. ::send(cli,
  13958. #ifdef _WIN32
  13959. static_cast<const char *>(response_header.c_str()),
  13960. static_cast<int>(response_header.size()),
  13961. #else
  13962. response_header.c_str(), response_header.size(),
  13963. #endif
  13964. 0);
  13965. std::string chunk(64 * 1024, 'A');
  13966. size_t total_sent = 0;
  13967. while (total_sent < DATA_SIZE) {
  13968. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13969. auto sent = ::send(cli,
  13970. #ifdef _WIN32
  13971. static_cast<const char *>(chunk.c_str()),
  13972. static_cast<int>(to_send),
  13973. #else
  13974. chunk.c_str(), to_send,
  13975. #endif
  13976. 0);
  13977. if (sent <= 0) break;
  13978. total_sent += static_cast<size_t>(sent);
  13979. }
  13980. detail::close_socket(cli);
  13981. }
  13982. detail::close_socket(srv);
  13983. });
  13984. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13985. size_t total_received = 0;
  13986. {
  13987. Client cli("127.0.0.1", PORT + 2);
  13988. cli.set_read_timeout(10, 0);
  13989. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13990. auto res =
  13991. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13992. total_received += data_length;
  13993. return true;
  13994. });
  13995. // Should fail because 200MB exceeds the explicit 150MB limit
  13996. EXPECT_FALSE(res);
  13997. }
  13998. server_thread.join();
  13999. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  14000. << "Client with content_receiver should respect the explicit "
  14001. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  14002. << total_received << " bytes.";
  14003. }
  14004. // Verify that an explicit set_payload_max_length larger than the response
  14005. // allows the content_receiver to read all data successfully.
  14006. TEST(ClientVulnerabilityTest,
  14007. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  14008. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  14009. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  14010. #ifndef _WIN32
  14011. signal(SIGPIPE, SIG_IGN);
  14012. #endif
  14013. auto server_thread = std::thread([] {
  14014. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14015. default_socket_options(srv);
  14016. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14017. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14018. sockaddr_in addr{};
  14019. addr.sin_family = AF_INET;
  14020. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  14021. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14022. int opt = 1;
  14023. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14024. #ifdef _WIN32
  14025. reinterpret_cast<const char *>(&opt),
  14026. #else
  14027. &opt,
  14028. #endif
  14029. sizeof(opt));
  14030. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14031. ::listen(srv, 1);
  14032. sockaddr_in cli_addr{};
  14033. socklen_t cli_len = sizeof(cli_addr);
  14034. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14035. if (cli != INVALID_SOCKET) {
  14036. char buf[4096];
  14037. ::recv(cli, buf, sizeof(buf), 0);
  14038. auto content_length = std::to_string(DATA_SIZE);
  14039. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14040. "Content-Length: " +
  14041. content_length +
  14042. "\r\n"
  14043. "Connection: close\r\n"
  14044. "\r\n";
  14045. ::send(cli,
  14046. #ifdef _WIN32
  14047. static_cast<const char *>(response_header.c_str()),
  14048. static_cast<int>(response_header.size()),
  14049. #else
  14050. response_header.c_str(), response_header.size(),
  14051. #endif
  14052. 0);
  14053. std::string chunk(64 * 1024, 'A');
  14054. size_t total_sent = 0;
  14055. while (total_sent < DATA_SIZE) {
  14056. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  14057. auto sent = ::send(cli,
  14058. #ifdef _WIN32
  14059. static_cast<const char *>(chunk.c_str()),
  14060. static_cast<int>(to_send),
  14061. #else
  14062. chunk.c_str(), to_send,
  14063. #endif
  14064. 0);
  14065. if (sent <= 0) break;
  14066. total_sent += static_cast<size_t>(sent);
  14067. }
  14068. #ifdef _WIN32
  14069. ::shutdown(cli, SD_SEND);
  14070. #else
  14071. ::shutdown(cli, SHUT_WR);
  14072. #endif
  14073. char drain[1024];
  14074. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  14075. detail::close_socket(cli);
  14076. }
  14077. detail::close_socket(srv);
  14078. });
  14079. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14080. size_t total_received = 0;
  14081. {
  14082. Client cli("127.0.0.1", PORT + 2);
  14083. cli.set_read_timeout(10, 0);
  14084. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  14085. auto res =
  14086. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  14087. total_received += data_length;
  14088. return true;
  14089. });
  14090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14091. EXPECT_EQ(StatusCode::OK_200, res->status);
  14092. }
  14093. server_thread.join();
  14094. EXPECT_EQ(total_received, DATA_SIZE)
  14095. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  14096. << " bytes (larger than " << DATA_SIZE
  14097. << " bytes response), content_receiver should read all data, but only "
  14098. "read "
  14099. << total_received << " bytes.";
  14100. }
  14101. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  14102. // Regression test for "zip bomb" attack on the client side: a malicious server
  14103. // sends a small gzip-compressed response that decompresses to a huge payload.
  14104. // The client must enforce payload_max_length on the decompressed size.
  14105. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  14106. constexpr size_t DECOMPRESSED_SIZE =
  14107. 10 * 1024 * 1024; // 10MB after decompression
  14108. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  14109. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  14110. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  14111. std::string compressed;
  14112. {
  14113. httplib::detail::gzip_compressor compressor;
  14114. bool ok =
  14115. compressor.compress(uncompressed.data(), uncompressed.size(),
  14116. /*last=*/true, [&](const char *buf, size_t len) {
  14117. compressed.append(buf, len);
  14118. return true;
  14119. });
  14120. ASSERT_TRUE(ok);
  14121. }
  14122. // Sanity: compressed data should be much smaller than the decompressed size
  14123. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  14124. #ifndef _WIN32
  14125. signal(SIGPIPE, SIG_IGN);
  14126. #endif
  14127. // Set up the listening socket in the main thread so the server is guaranteed
  14128. // to be ready before the client connects (eliminates race condition).
  14129. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14130. default_socket_options(srv);
  14131. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  14132. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  14133. sockaddr_in addr{};
  14134. addr.sin_family = AF_INET;
  14135. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  14136. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14137. int opt = 1;
  14138. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  14139. #ifdef _WIN32
  14140. reinterpret_cast<const char *>(&opt),
  14141. #else
  14142. &opt,
  14143. #endif
  14144. sizeof(opt));
  14145. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14146. ASSERT_EQ(0, ::listen(srv, 1));
  14147. auto server_thread = std::thread([&compressed, srv] {
  14148. sockaddr_in cli_addr{};
  14149. socklen_t cli_len = sizeof(cli_addr);
  14150. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14151. if (cli != INVALID_SOCKET) {
  14152. // Read the full HTTP request (until \r\n\r\n)
  14153. char buf[4096];
  14154. size_t total = 0;
  14155. while (total < sizeof(buf)) {
  14156. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  14157. if (n <= 0) break;
  14158. total += static_cast<size_t>(n);
  14159. // Check for end of headers
  14160. if (total >= 4) {
  14161. std::string req(buf, total);
  14162. if (req.find("\r\n\r\n") != std::string::npos) break;
  14163. }
  14164. }
  14165. // Malicious response: gzip-compressed body, no Content-Length
  14166. std::string response_header = "HTTP/1.1 200 OK\r\n"
  14167. "Content-Encoding: gzip\r\n"
  14168. "Connection: close\r\n"
  14169. "\r\n";
  14170. ::send(cli,
  14171. #ifdef _WIN32
  14172. static_cast<const char *>(response_header.c_str()),
  14173. static_cast<int>(response_header.size()),
  14174. #else
  14175. response_header.c_str(), response_header.size(),
  14176. #endif
  14177. 0);
  14178. // Send the compressed payload (small on the wire, huge when decompressed)
  14179. size_t total_sent = 0;
  14180. while (total_sent < compressed.size()) {
  14181. auto to_send = std::min(compressed.size() - total_sent,
  14182. static_cast<size_t>(64 * 1024));
  14183. auto sent =
  14184. ::send(cli,
  14185. #ifdef _WIN32
  14186. static_cast<const char *>(compressed.c_str() + total_sent),
  14187. static_cast<int>(to_send),
  14188. #else
  14189. compressed.c_str() + total_sent, to_send,
  14190. #endif
  14191. 0);
  14192. if (sent <= 0) break;
  14193. total_sent += static_cast<size_t>(sent);
  14194. }
  14195. detail::close_socket(cli);
  14196. }
  14197. });
  14198. auto se = detail::scope_exit([&] {
  14199. detail::close_socket(srv);
  14200. server_thread.join();
  14201. });
  14202. size_t total_decompressed = 0;
  14203. {
  14204. Client cli("127.0.0.1", PORT + 3);
  14205. cli.set_read_timeout(5, 0);
  14206. cli.set_decompress(true);
  14207. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  14208. auto stream = cli.open_stream("GET", "/zipbomb");
  14209. ASSERT_TRUE(stream.is_valid());
  14210. char buffer[64 * 1024];
  14211. ssize_t n;
  14212. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  14213. total_decompressed += static_cast<size_t>(n);
  14214. }
  14215. }
  14216. // The decompressed size must be capped by payload_max_length. Without
  14217. // protection, the client would decompress the full 10MB from a tiny
  14218. // compressed payload, enabling a zip bomb DoS attack.
  14219. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  14220. << "Client decompressed " << total_decompressed
  14221. << " bytes from a gzip response. The decompressed size should be "
  14222. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  14223. }
  14224. #endif
  14225. TEST(HostAndPortPropertiesTest, NoSSL) {
  14226. httplib::Client cli("www.google.com", 1234);
  14227. ASSERT_EQ("www.google.com", cli.host());
  14228. ASSERT_EQ(1234, cli.port());
  14229. }
  14230. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  14231. httplib::Client cli("www.google.com:1234");
  14232. ASSERT_EQ("www.google.com", cli.host());
  14233. ASSERT_EQ(1234, cli.port());
  14234. }
  14235. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  14236. // Port number that overflows int — should not crash, client becomes invalid
  14237. httplib::Client cli("http://www.google.com:99999999999999999999");
  14238. ASSERT_FALSE(cli.is_valid());
  14239. }
  14240. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  14241. // Port 99999 exceeds valid range (1-65535) — should not crash
  14242. httplib::Client cli("http://www.google.com:99999");
  14243. ASSERT_FALSE(cli.is_valid());
  14244. auto res = cli.Get("/");
  14245. EXPECT_FALSE(res);
  14246. EXPECT_EQ(Error::Connection, res.error());
  14247. }
  14248. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  14249. httplib::Client cli("http://user:pass@localhost:1234");
  14250. ASSERT_FALSE(cli.is_valid());
  14251. EXPECT_FALSE(cli.Get("/"));
  14252. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  14253. }
  14254. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  14255. httplib::Client cli("http://www.google.com:80abc");
  14256. ASSERT_FALSE(cli.is_valid());
  14257. }
  14258. #ifdef CPPHTTPLIB_SSL_ENABLED
  14259. TEST(HostAndPortPropertiesTest, SSL) {
  14260. httplib::SSLClient cli("www.google.com");
  14261. ASSERT_EQ("www.google.com", cli.host());
  14262. ASSERT_EQ(443, cli.port());
  14263. }
  14264. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  14265. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  14266. std::string cert;
  14267. read_file(CA_CERT_FILE, cert);
  14268. httplib::SSLClient httplib_client("www.google.com");
  14269. // Load CA store first time
  14270. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14271. // Load CA store second time (update)
  14272. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  14273. // Verify client is still valid and can make connections
  14274. httplib_client.enable_server_certificate_verification(true);
  14275. auto res = httplib_client.Get("/");
  14276. // Any status: Google may redirect or rate-limit CI runners.
  14277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14278. }
  14279. TEST(SSLClientTest, ServerNameIndication_Online) {
  14280. auto host = "httpbingo.org";
  14281. auto path = std::string{"/get"};
  14282. SSLClient cli(host, 443);
  14283. auto res = retry_service_failures([&] { return cli.Get(path); });
  14284. SKIP_ON_SERVICE_FAILURE(res);
  14285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14286. ASSERT_EQ(StatusCode::OK_200, res->status);
  14287. }
  14288. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  14289. // Use a site that will cause SSL verification failure due to self-signed cert
  14290. SSLClient cli("self-signed.badssl.com", 443);
  14291. cli.enable_server_certificate_verification(true);
  14292. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14293. SKIP_ON_SERVICE_FAILURE(res);
  14294. ASSERT_TRUE(!res);
  14295. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14296. // Verify backend error is captured for SSLServerVerification
  14297. // This occurs when certificate verification fails
  14298. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  14299. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  14300. EXPECT_NE(0UL, res.ssl_backend_error());
  14301. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  14302. res.ssl_error());
  14303. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14304. #if !defined(_WIN32) || \
  14305. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14306. // On non-Windows or when Windows Schannel is disabled, the error comes
  14307. // from OpenSSL's verification
  14308. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  14309. res.ssl_backend_error());
  14310. #endif
  14311. #endif
  14312. }
  14313. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  14314. // Use a site where hostname doesn't match the certificate
  14315. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  14316. SSLClient cli("wrong.host.badssl.com", 443);
  14317. cli.enable_server_certificate_verification(true);
  14318. cli.enable_server_hostname_verification(true);
  14319. auto res = retry_service_failures([&] { return cli.Get("/"); });
  14320. SKIP_ON_SERVICE_FAILURE(res);
  14321. ASSERT_TRUE(!res);
  14322. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  14323. // Verify backend error is captured for hostname verification failure
  14324. EXPECT_NE(0UL, res.ssl_backend_error());
  14325. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  14326. res.ssl_error());
  14327. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14328. #if !defined(_WIN32) || \
  14329. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14330. // On non-Windows or when Windows Schannel is disabled, the error comes
  14331. // from OpenSSL's hostname verification
  14332. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  14333. res.ssl_backend_error());
  14334. #endif
  14335. #endif
  14336. }
  14337. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  14338. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  14339. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  14340. SSLClient cli("www.google.com", 443);
  14341. cli.enable_server_certificate_verification(true);
  14342. auto res = cli.Get("/");
  14343. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14344. }
  14345. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  14346. SSLClient cli("www.google.com", 443);
  14347. cli.enable_server_certificate_verification(true);
  14348. cli.enable_windows_certificate_verification(false);
  14349. auto res = cli.Get("/");
  14350. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  14351. }
  14352. // The server sends an intermediate cross-signed by a root Windows trusts,
  14353. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  14354. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  14355. SSLClient cli("accounts.spotify.com", 443);
  14356. auto res = cli.Get("/");
  14357. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  14358. << " ssl_backend_error=" << res.ssl_backend_error();
  14359. }
  14360. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  14361. // policy status, which no backend reports for a self-signed certificate.
  14362. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  14363. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14364. ASSERT_TRUE(svr.is_valid());
  14365. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14366. auto se = detail::scope_exit([&] {
  14367. svr.stop();
  14368. t.join();
  14369. ASSERT_FALSE(svr.is_running());
  14370. });
  14371. svr.wait_until_ready();
  14372. SSLClient cli("127.0.0.1", PORT);
  14373. cli.set_connection_timeout(30);
  14374. auto res = cli.Get("/");
  14375. ASSERT_FALSE(res);
  14376. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14377. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  14378. }
  14379. TEST(WebSocketSSLVerifyTest, WindowsCertificateVerification) {
  14380. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14381. ASSERT_TRUE(svr.is_valid());
  14382. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14383. auto se = detail::scope_exit([&] {
  14384. svr.stop();
  14385. t.join();
  14386. ASSERT_FALSE(svr.is_running());
  14387. });
  14388. svr.wait_until_ready();
  14389. auto url = "wss://127.0.0.1:" + std::to_string(PORT) + "/";
  14390. {
  14391. ws::WebSocketClient client(url);
  14392. auto res = client.connect();
  14393. ASSERT_FALSE(res);
  14394. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14395. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14396. res.ssl_backend_error());
  14397. }
  14398. {
  14399. ws::WebSocketClient client(url);
  14400. client.enable_windows_certificate_verification(false);
  14401. auto res = client.connect();
  14402. ASSERT_FALSE(res);
  14403. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14404. EXPECT_NE(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT),
  14405. res.ssl_backend_error());
  14406. }
  14407. }
  14408. #endif
  14409. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  14410. Client cli("https://google.com");
  14411. auto res = cli.Get("/");
  14412. // Any status: Google may redirect or rate-limit CI runners.
  14413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14414. }
  14415. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  14416. SSLClient cli("google.com");
  14417. cli.set_ca_cert_path(CA_CERT_FILE);
  14418. auto res = cli.Get("/");
  14419. // Any status: Google may redirect or rate-limit CI runners.
  14420. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14421. }
  14422. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  14423. SSLClient cli("google.com");
  14424. cli.enable_server_certificate_verification(true);
  14425. cli.set_ca_cert_path("hello");
  14426. auto res = cli.Get("/");
  14427. ASSERT_TRUE(!res);
  14428. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  14429. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  14430. // should be set
  14431. EXPECT_EQ(0, res.ssl_error());
  14432. // Verify backend error is captured for SSLLoadingCerts
  14433. // This error occurs when loading CA certificates fails
  14434. EXPECT_NE(0UL, res.ssl_backend_error());
  14435. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  14436. // OpenSSL specific error codes:
  14437. // > openssl errstr 0x80000002
  14438. // error:80000002:system library::No such file or directory
  14439. // > openssl errstr 0xA000126
  14440. // error:0A000126:SSL routines::unexpected eof while reading
  14441. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  14442. res.ssl_backend_error() == 0xA000126);
  14443. #endif
  14444. }
  14445. TEST(SSLClientTest, ServerCertificateVerification4) {
  14446. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14447. ASSERT_TRUE(svr.is_valid());
  14448. svr.Get("/test", [&](const Request &, Response &res) {
  14449. res.set_content("test", "text/plain");
  14450. svr.stop();
  14451. ASSERT_TRUE(true);
  14452. });
  14453. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  14454. auto se = detail::scope_exit([&] {
  14455. t.join();
  14456. ASSERT_FALSE(svr.is_running());
  14457. });
  14458. svr.wait_until_ready();
  14459. SSLClient cli("127.0.0.1", PORT);
  14460. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  14461. cli.enable_server_certificate_verification(true);
  14462. cli.set_connection_timeout(30);
  14463. auto res = cli.Get("/test");
  14464. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14465. ASSERT_EQ(StatusCode::OK_200, res->status);
  14466. }
  14467. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  14468. std::string cert;
  14469. read_file(CA_CERT_FILE, cert);
  14470. SSLClient cli("google.com");
  14471. cli.load_ca_cert_store(cert.data(), cert.size());
  14472. const auto res = cli.Get("/");
  14473. // Any status: Google may redirect or rate-limit CI runners.
  14474. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14475. }
  14476. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  14477. // clang-format off
  14478. static constexpr char cert[] =
  14479. "GlobalSign Root CA\n"
  14480. "==================\n"
  14481. "-----BEGIN CERTIFICATE-----\n"
  14482. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  14483. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  14484. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  14485. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  14486. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  14487. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  14488. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  14489. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  14490. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  14491. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  14492. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  14493. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  14494. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  14495. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  14496. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  14497. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  14498. "-----END CERTIFICATE-----\n";
  14499. // clang-format on
  14500. SSLClient cli("google.com");
  14501. cli.load_ca_cert_store(cert, sizeof(cert));
  14502. const auto res = cli.Get("/");
  14503. // Any status: Google may redirect or rate-limit CI runners.
  14504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14505. }
  14506. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  14507. SSLClient cli("www.youtube.com");
  14508. cli.set_ca_cert_path(CA_CERT_FILE);
  14509. cli.enable_server_certificate_verification(true);
  14510. cli.set_follow_location(true);
  14511. auto res = cli.Get("/");
  14512. // Any status: Google may redirect or rate-limit CI runners.
  14513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14514. }
  14515. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  14516. SSLClient cli("wWw.YouTube.Com");
  14517. cli.set_ca_cert_path(CA_CERT_FILE);
  14518. cli.enable_server_certificate_verification(true);
  14519. cli.enable_server_hostname_verification(true);
  14520. cli.set_follow_location(true);
  14521. auto res = cli.Get("/");
  14522. // Any status: Google may redirect or rate-limit CI runners.
  14523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14524. }
  14525. TEST(SSLClientTest, HostNameMatchCase_Online) {
  14526. SSLClient cli("gOoGlE.COm");
  14527. cli.enable_server_certificate_verification(true);
  14528. cli.enable_server_hostname_verification(true);
  14529. cli.set_follow_location(true);
  14530. auto res = cli.Get("/");
  14531. // Any status: Google may redirect or rate-limit CI runners.
  14532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14533. }
  14534. TEST(SSLClientTest, Issue2004_Online) {
  14535. Client client("https://google.com");
  14536. client.set_follow_location(true);
  14537. auto res = client.Get("/");
  14538. // Any status: Google may redirect or rate-limit CI runners.
  14539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14540. }
  14541. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  14542. // Create SSLClient with invalid cert/key to make is_valid() return false
  14543. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  14544. "nonexistent_key.pem");
  14545. // is_valid() should be false due to cert loading failure
  14546. ASSERT_FALSE(cli.is_valid());
  14547. auto res = cli.Get("/");
  14548. ASSERT_FALSE(res);
  14549. EXPECT_EQ(Error::SSLConnection, res.error());
  14550. }
  14551. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  14552. // Test for Issue #2251: SSL error not properly reported when client cert
  14553. // and key paths are swapped or mismatched
  14554. // This simulates the scenario where user accidentally swaps the cert and key
  14555. // files
  14556. // Using client cert file as private key and vice versa (completely wrong)
  14557. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  14558. // Should fail validation due to cert/key mismatch
  14559. ASSERT_FALSE(cli.is_valid());
  14560. // Attempt to make a request should fail with proper error
  14561. auto res = cli.Get("/");
  14562. ASSERT_FALSE(res);
  14563. EXPECT_EQ(Error::SSLConnection, res.error());
  14564. // SSL error should be recorded in the Result object (this is the key fix for
  14565. // Issue #2251)
  14566. auto backend_error = res.ssl_backend_error();
  14567. EXPECT_NE(0u, backend_error);
  14568. }
  14569. // Tests cert/key mismatch detection at the TLS context level
  14570. TEST(TlsApiTest, ClientCertKeyMismatch) {
  14571. // Test that using mismatched cert/key causes connection failure.
  14572. // We verify this at the SSLClient level rather than through internal
  14573. // TLS API functions.
  14574. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  14575. cli.enable_server_certificate_verification(false);
  14576. cli.set_connection_timeout(2);
  14577. // The mismatch should cause a connection or handshake error
  14578. auto res = cli.Get("/test");
  14579. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  14580. // Either way, the request should fail
  14581. EXPECT_FALSE(res);
  14582. }
  14583. #endif
  14584. #if 0
  14585. TEST(SSLClientTest, SetInterfaceWithINET6) {
  14586. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  14587. ASSERT_TRUE(cli != nullptr);
  14588. cli->set_address_family(AF_INET6);
  14589. cli->set_interface("en0");
  14590. auto res = cli->Get("/get");
  14591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14592. ASSERT_EQ(StatusCode::OK_200, res->status);
  14593. }
  14594. #endif
  14595. // Client certificate tests - work with all TLS backends
  14596. #ifdef CPPHTTPLIB_SSL_ENABLED
  14597. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  14598. void ClientCertPresent(
  14599. const std::string &client_cert_file,
  14600. const std::string &client_private_key_file,
  14601. const std::string &client_encrypted_private_key_pass = std::string(),
  14602. const ClientCertServerSetup &setup = nullptr) {
  14603. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14604. ASSERT_TRUE(svr.is_valid());
  14605. if (setup) { setup(svr); }
  14606. svr.Get("/test", [&](const Request &req, Response &res) {
  14607. res.set_content("test", "text/plain");
  14608. auto cert = req.peer_cert();
  14609. ASSERT_TRUE(static_cast<bool>(cert));
  14610. std::string common_name = cert.subject_cn();
  14611. EXPECT_EQ("Common Name", common_name);
  14612. });
  14613. auto port = svr.bind_to_any_port(HOST);
  14614. ASSERT_LT(0, port);
  14615. thread t = thread([&]() { svr.listen_after_bind(); });
  14616. auto se = detail::scope_exit([&] {
  14617. svr.stop();
  14618. t.join();
  14619. ASSERT_FALSE(svr.is_running());
  14620. });
  14621. svr.wait_until_ready();
  14622. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  14623. client_encrypted_private_key_pass);
  14624. cli.enable_server_certificate_verification(false);
  14625. cli.set_connection_timeout(30);
  14626. auto res = cli.Get("/test");
  14627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14628. ASSERT_EQ(StatusCode::OK_200, res->status);
  14629. }
  14630. TEST(SSLClientServerTest, ClientCertPresent) {
  14631. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14632. }
  14633. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  14634. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14635. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14636. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14637. }
  14638. // Expects svr, which must require client certificates, to reject a client
  14639. // that has none
  14640. void RejectsClientWithoutCert(SSLServer &svr) {
  14641. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  14642. auto port = svr.bind_to_any_port(HOST);
  14643. ASSERT_LT(0, port);
  14644. thread t = thread([&]() { svr.listen_after_bind(); });
  14645. auto se = detail::scope_exit([&] {
  14646. svr.stop();
  14647. t.join();
  14648. ASSERT_FALSE(svr.is_running());
  14649. });
  14650. svr.wait_until_ready();
  14651. SSLClient cli(HOST, port);
  14652. cli.set_connection_timeout(30);
  14653. // Skip the server certificate check, so that the request fails because the
  14654. // client certificate is missing rather than because cert.pem is not trusted
  14655. cli.enable_server_certificate_verification(false);
  14656. auto res = cli.Get("/test");
  14657. ASSERT_FALSE(res);
  14658. // The server rejects the client during the handshake, or on TLS 1.3 right
  14659. // after it, which the client notices on its first write or read
  14660. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  14661. res.error() == Error::Write || res.error() == Error::Read)
  14662. << to_string(res.error());
  14663. if (res.error() == Error::SSLConnection) {
  14664. EXPECT_NE(0UL, res.ssl_backend_error());
  14665. }
  14666. // A rejection noticed on the write keeps the TLS error the write hit
  14667. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  14668. }
  14669. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  14670. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14671. ASSERT_TRUE(svr.is_valid());
  14672. if (setup) { setup(svr); }
  14673. RejectsClientWithoutCert(svr);
  14674. }
  14675. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  14676. // A server that requires client certificates must keep requiring them after
  14677. // setup changes it, and keep accepting a client that has one
  14678. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  14679. ClientCertMissing(setup);
  14680. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  14681. setup);
  14682. }
  14683. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  14684. ClientCertStillRequired([](SSLServer &svr) {
  14685. ASSERT_TRUE(tls::set_verify_callback(
  14686. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14687. });
  14688. }
  14689. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  14690. ClientCertStillRequired([](SSLServer &svr) {
  14691. ASSERT_TRUE(tls::set_verify_callback(
  14692. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  14693. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  14694. });
  14695. }
  14696. // The client verifies the server certificate during the handshake, so a
  14697. // server that fails the check never gets the client certificate, even when a
  14698. // verifier of the client's own accepts it
  14699. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  14700. struct Case {
  14701. const char *trusted_ca;
  14702. const char *host;
  14703. Error error;
  14704. };
  14705. // cert2.pem names localhost: the first client does not trust it, and the
  14706. // second trusts it but asks for another name
  14707. for (const auto &c :
  14708. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  14709. Case{SERVER_CERT2_FILE, "example.com",
  14710. Error::SSLServerHostnameVerification}}) {
  14711. for (auto with_verifier : {false, true}) {
  14712. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  14713. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  14714. CLIENT_CA_CERT_FILE);
  14715. ASSERT_TRUE(svr.is_valid());
  14716. std::atomic<bool> got_client_cert{false};
  14717. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  14718. [&](const tls::VerifyContext &) {
  14719. got_client_cert = true;
  14720. return true;
  14721. }));
  14722. auto port = svr.bind_to_any_port("127.0.0.1");
  14723. ASSERT_LT(0, port);
  14724. thread t = thread([&] { svr.listen_after_bind(); });
  14725. svr.wait_until_ready();
  14726. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14727. cli.set_direct_hostname_addr_map({{c.host, "127.0.0.1"}});
  14728. cli.set_ca_cert_path(c.trusted_ca);
  14729. if (with_verifier) {
  14730. cli.set_server_certificate_verifier(
  14731. [](const tls::VerifyContext &) { return true; });
  14732. }
  14733. auto res = cli.Get("/");
  14734. EXPECT_FALSE(res);
  14735. EXPECT_EQ(c.error, res.error());
  14736. svr.stop();
  14737. t.join();
  14738. EXPECT_FALSE(got_client_cert);
  14739. }
  14740. }
  14741. }
  14742. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  14743. std::string cert_pem, key_pem, ca_pem;
  14744. read_file(SERVER_CERT_FILE, cert_pem);
  14745. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  14746. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  14747. ASSERT_TRUE(
  14748. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  14749. }
  14750. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  14751. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14752. ASSERT_TRUE(svr.is_valid());
  14753. UpdateCertsPemWithClientCA(svr);
  14754. RejectsClientWithoutCert(svr);
  14755. }
  14756. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  14757. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  14758. }
  14759. // A TLS error from one request must not show up in a later request's Result
  14760. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  14761. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14762. ASSERT_TRUE(svr.is_valid());
  14763. svr.Get("/test", [](const Request &, Response &res) {
  14764. res.set_content("test", "text/plain");
  14765. });
  14766. auto port = svr.bind_to_any_port(HOST);
  14767. ASSERT_LT(0, port);
  14768. thread t = thread([&]() { svr.listen_after_bind(); });
  14769. auto se = detail::scope_exit([&] {
  14770. svr.stop();
  14771. t.join();
  14772. ASSERT_FALSE(svr.is_running());
  14773. });
  14774. svr.wait_until_ready();
  14775. SSLClient cli(HOST, port);
  14776. cli.set_connection_timeout(30);
  14777. cli.enable_server_hostname_verification(false);
  14778. // cert.pem is not trusted, so the handshake fails
  14779. ASSERT_FALSE(cli.Get("/test"));
  14780. cli.enable_server_certificate_verification(false);
  14781. auto res = cli.Get("/test");
  14782. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14783. EXPECT_EQ(0, res.ssl_error());
  14784. EXPECT_EQ(0UL, res.ssl_backend_error());
  14785. }
  14786. // PEM memory-based constructor tests (works with all TLS backends).
  14787. // exact_size passes each PEM in a buffer of its own size, with no NUL
  14788. // terminator after it.
  14789. void PemMemoryClientCertPresent(
  14790. const std::string &client_cert_file,
  14791. const std::string &client_private_key_file,
  14792. const std::string &client_encrypted_private_key_pass = std::string(),
  14793. bool exact_size = false) {
  14794. // Read PEM files into memory
  14795. std::string server_cert_pem, server_key_pem;
  14796. std::string client_ca_pem;
  14797. std::string client_cert_pem, client_key_pem;
  14798. read_file(SERVER_CERT_FILE, server_cert_pem);
  14799. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14800. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14801. read_file(client_cert_file, client_cert_pem);
  14802. read_file(client_private_key_file, client_key_pem);
  14803. std::list<std::vector<char>> exact_copies;
  14804. auto data = [&](const std::string &pem) -> const char * {
  14805. if (!exact_size) { return pem.c_str(); }
  14806. exact_copies.emplace_back(pem.begin(), pem.end());
  14807. return exact_copies.back().data();
  14808. };
  14809. // Create server with PEM memory
  14810. SSLServer::PemMemory server_pem = {
  14811. data(server_cert_pem),
  14812. server_cert_pem.size(),
  14813. data(server_key_pem),
  14814. server_key_pem.size(),
  14815. data(client_ca_pem),
  14816. client_ca_pem.size(),
  14817. nullptr // no password for server key
  14818. };
  14819. SSLServer svr(server_pem);
  14820. ASSERT_TRUE(svr.is_valid());
  14821. svr.Get("/test", [&](const Request &req, Response &res) {
  14822. res.set_content("test", "text/plain");
  14823. auto cert = req.peer_cert();
  14824. ASSERT_TRUE(static_cast<bool>(cert));
  14825. EXPECT_EQ("Common Name", cert.subject_cn());
  14826. });
  14827. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14828. auto se = detail::scope_exit([&] {
  14829. svr.stop();
  14830. t.join();
  14831. ASSERT_FALSE(svr.is_running());
  14832. });
  14833. svr.wait_until_ready();
  14834. // Create client with PEM memory
  14835. const char *password = client_encrypted_private_key_pass.empty()
  14836. ? nullptr
  14837. : client_encrypted_private_key_pass.c_str();
  14838. SSLClient::PemMemory client_pem = {
  14839. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  14840. client_key_pem.size(), password};
  14841. SSLClient cli(HOST, PORT, client_pem);
  14842. cli.enable_server_certificate_verification(false);
  14843. cli.set_connection_timeout(30);
  14844. auto res = cli.Get("/test");
  14845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14846. ASSERT_EQ(StatusCode::OK_200, res->status);
  14847. }
  14848. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  14849. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14850. }
  14851. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  14852. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  14853. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  14854. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  14855. }
  14856. // A server built from PEM memory with a client CA requires client certificates,
  14857. // also when the CA is a NUL-terminated string passed with a length of 0
  14858. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  14859. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14860. read_file(SERVER_CERT_FILE, server_cert_pem);
  14861. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14862. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14863. SSLServer::PemMemory server_pem = {
  14864. server_cert_pem.c_str(),
  14865. server_cert_pem.size(),
  14866. server_key_pem.c_str(),
  14867. server_key_pem.size(),
  14868. client_ca_pem.c_str(),
  14869. client_ca_pem.size(),
  14870. nullptr // no password for server key
  14871. };
  14872. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  14873. SCOPED_TRACE(client_ca_pem_len);
  14874. server_pem.client_ca_pem_len = client_ca_pem_len;
  14875. SSLServer svr(server_pem);
  14876. ASSERT_TRUE(svr.is_valid());
  14877. RejectsClientWithoutCert(svr);
  14878. }
  14879. // An empty CA fails to load instead of turning the check off
  14880. server_pem.client_ca_pem = "";
  14881. server_pem.client_ca_pem_len = 0;
  14882. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14883. }
  14884. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  14885. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  14886. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  14887. true);
  14888. }
  14889. // A length shorter than the PEM cuts it short, so it no longer loads
  14890. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  14891. std::string cert, key;
  14892. read_file(SERVER_CERT_FILE, cert);
  14893. read_file(SERVER_PRIVATE_KEY_FILE, key);
  14894. for (auto cut_cert : {true, false}) {
  14895. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  14896. auto key_len = cut_cert ? key.size() : key.size() / 2;
  14897. SSLServer::PemMemory server_pem = {
  14898. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  14899. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  14900. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  14901. key_len, nullptr};
  14902. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  14903. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  14904. key.c_str(), key_len, nullptr};
  14905. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  14906. }
  14907. }
  14908. TEST(SSLClientServerTest, SSLConnectTimeout) {
  14909. class NoListenSSLServer : public SSLServer {
  14910. public:
  14911. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  14912. const char *client_ca_cert_file_path,
  14913. const char *client_ca_cert_dir_path = nullptr)
  14914. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  14915. client_ca_cert_dir_path),
  14916. stop_(false) {}
  14917. std::atomic_bool stop_;
  14918. private:
  14919. bool process_and_close_socket(socket_t /*sock*/) override {
  14920. // Don't create SSL context
  14921. while (!stop_.load()) {
  14922. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  14923. }
  14924. return true;
  14925. }
  14926. };
  14927. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14928. CLIENT_CA_CERT_FILE);
  14929. ASSERT_TRUE(svr.is_valid());
  14930. // Keep-alive parking would bypass the override.
  14931. svr.set_keep_alive_parking(false);
  14932. svr.Get("/test", [&](const Request &, Response &res) {
  14933. res.set_content("test", "text/plain");
  14934. });
  14935. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14936. auto se = detail::scope_exit([&] {
  14937. svr.stop_ = true;
  14938. svr.stop();
  14939. t.join();
  14940. ASSERT_FALSE(svr.is_running());
  14941. });
  14942. svr.wait_until_ready();
  14943. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14944. cli.enable_server_certificate_verification(false);
  14945. cli.set_connection_timeout(1);
  14946. auto res = cli.Get("/test");
  14947. ASSERT_TRUE(!res);
  14948. EXPECT_EQ(Error::SSLConnection, res.error());
  14949. // Timeout results in WantRead error code (maps to backend-specific value)
  14950. EXPECT_NE(0, res.ssl_error());
  14951. }
  14952. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  14953. // Test SSLServer with client certificate verification using the standard
  14954. // constructor (ContextSetupCallback is tested by backend-specific tests)
  14955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  14956. CLIENT_CA_CERT_DIR);
  14957. ASSERT_TRUE(svr.is_valid());
  14958. svr.Get("/test", [&](const Request &req, Response &res) {
  14959. res.set_content("test", "text/plain");
  14960. auto cert = req.peer_cert();
  14961. ASSERT_TRUE(static_cast<bool>(cert));
  14962. auto common_name = cert.subject_cn();
  14963. EXPECT_EQ("Common Name", common_name);
  14964. });
  14965. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14966. auto se = detail::scope_exit([&] {
  14967. svr.stop();
  14968. t.join();
  14969. ASSERT_FALSE(svr.is_running());
  14970. });
  14971. svr.wait_until_ready();
  14972. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14973. cli.enable_server_certificate_verification(false);
  14974. cli.set_connection_timeout(30);
  14975. auto res = cli.Get("/test");
  14976. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14977. ASSERT_EQ(StatusCode::OK_200, res->status);
  14978. }
  14979. // Test verify_hostname on every backend: a host is named by a SAN only
  14980. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14981. using namespace httplib::tls;
  14982. // We need a running server to test against
  14983. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14984. ASSERT_TRUE(svr.is_valid());
  14985. svr.Get("/test", [](const Request &, Response &res) {
  14986. res.set_content("ok", "text/plain");
  14987. });
  14988. thread t([&]() { svr.listen(HOST, PORT); });
  14989. auto se = detail::scope_exit([&] {
  14990. svr.stop();
  14991. t.join();
  14992. });
  14993. svr.wait_until_ready();
  14994. bool verify_callback_called = false;
  14995. bool verify_result_wrong = false;
  14996. SSLClient cli(HOST, PORT);
  14997. cli.enable_server_certificate_verification(true);
  14998. cli.set_ca_cert_path(CA_CERT_FILE);
  14999. cli.set_connection_timeout(5);
  15000. // Note: Test certificate has CN="Common Name", not "localhost"
  15001. bool verify_result_cn = false;
  15002. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15003. verify_callback_called = true;
  15004. if (!ctx.cert) return false;
  15005. // Test 1: "Common Name" is the CN of our test server cert, which has no SAN
  15006. verify_result_cn = ctx.check_hostname("Common Name");
  15007. // Test 2: wrong hostname should not match
  15008. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  15009. return true; // Accept for the purpose of this test
  15010. });
  15011. auto res = cli.Get("/test");
  15012. // The request may succeed or fail depending on cert configuration
  15013. // but the callback should have been called
  15014. ASSERT_TRUE(verify_callback_called)
  15015. << "Verify callback should have been called";
  15016. EXPECT_FALSE(verify_result_cn)
  15017. << "verify_hostname must not match the certificate CN (no SAN)";
  15018. // Wrong hostname should not match
  15019. EXPECT_FALSE(verify_result_wrong)
  15020. << "verify_hostname should not match 'wronghost.example.com'";
  15021. }
  15022. // A DNS name in the CN must not authenticate a host (RFC 9525), whichever
  15023. // backend verifies it.
  15024. TEST(SSLClientServerTest, TlsVerifyHostnameDnsNotMatchedByCommonName) {
  15025. // Certificate CN is "localhost" and it carries no SAN.
  15026. SSLServer svr(SERVER_CERT_DNS_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15027. ASSERT_TRUE(svr.is_valid());
  15028. svr.Get("/test", [](const Request &, Response &res) {
  15029. res.set_content("ok", "text/plain");
  15030. });
  15031. auto port = svr.bind_to_any_port(HOST);
  15032. thread t([&]() { svr.listen_after_bind(); });
  15033. auto se = detail::scope_exit([&] {
  15034. svr.stop();
  15035. t.join();
  15036. });
  15037. svr.wait_until_ready();
  15038. SSLClient cli("localhost", port);
  15039. cli.set_ca_cert_path(SERVER_CERT_DNS_CN_FILE);
  15040. cli.enable_server_certificate_verification(true);
  15041. cli.set_connection_timeout(5);
  15042. auto res = cli.Get("/test");
  15043. ASSERT_FALSE(res);
  15044. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  15045. // The same certificate is accepted once host name verification is off, so the
  15046. // failure above is the host name and not the chain.
  15047. cli.enable_server_hostname_verification(false);
  15048. res = cli.Get("/test");
  15049. ASSERT_TRUE(res) << to_string(res.error());
  15050. EXPECT_EQ(StatusCode::OK_200, res->status);
  15051. }
  15052. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  15053. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  15054. // X509_check_ip behavior and must hold for every backend.
  15055. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  15056. using namespace httplib::tls;
  15057. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  15058. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  15059. ASSERT_TRUE(svr.is_valid());
  15060. svr.Get("/test", [](const Request &, Response &res) {
  15061. res.set_content("ok", "text/plain");
  15062. });
  15063. thread t([&]() { svr.listen(HOST, PORT); });
  15064. auto se = detail::scope_exit([&] {
  15065. svr.stop();
  15066. t.join();
  15067. });
  15068. svr.wait_until_ready();
  15069. bool verify_callback_called = false;
  15070. bool ip_matched_via_cn = true;
  15071. SSLClient cli(HOST, PORT);
  15072. cli.enable_server_certificate_verification(true);
  15073. cli.set_ca_cert_path(CA_CERT_FILE);
  15074. cli.set_connection_timeout(5);
  15075. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15076. verify_callback_called = true;
  15077. if (!ctx.cert) return false;
  15078. // The IP appears only in the CN, so it must NOT be accepted.
  15079. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  15080. return true; // Accept for the purpose of this test
  15081. });
  15082. cli.Get("/test");
  15083. ASSERT_TRUE(verify_callback_called)
  15084. << "Verify callback should have been called";
  15085. EXPECT_FALSE(ip_matched_via_cn)
  15086. << "An IP host must not be authenticated via the certificate CN";
  15087. }
  15088. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  15089. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  15090. using namespace httplib::tls;
  15091. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  15092. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  15093. ASSERT_TRUE(svr.is_valid());
  15094. svr.Get("/test", [](const Request &, Response &res) {
  15095. res.set_content("ok", "text/plain");
  15096. });
  15097. thread t([&]() { svr.listen(HOST, PORT); });
  15098. auto se = detail::scope_exit([&] {
  15099. svr.stop();
  15100. t.join();
  15101. });
  15102. svr.wait_until_ready();
  15103. bool verify_callback_called = false;
  15104. bool san_matched = false;
  15105. bool wrong_ipv6_matched = true;
  15106. bool cn_ipv6_matched = true;
  15107. SSLClient cli(HOST, PORT);
  15108. cli.enable_server_certificate_verification(true);
  15109. cli.set_ca_cert_path(CA_CERT_FILE);
  15110. cli.set_connection_timeout(5);
  15111. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15112. verify_callback_called = true;
  15113. if (!ctx.cert) return false;
  15114. // Matches the IPv6 iPAddress SAN.
  15115. san_matched = ctx.check_hostname("2001:db8::1");
  15116. // A different IPv6 address must not match.
  15117. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  15118. // "::1" lives only in the CN, so it must not be accepted.
  15119. cn_ipv6_matched = ctx.check_hostname("::1");
  15120. return true; // Accept for the purpose of this test
  15121. });
  15122. cli.Get("/test");
  15123. ASSERT_TRUE(verify_callback_called)
  15124. << "Verify callback should have been called";
  15125. EXPECT_TRUE(san_matched)
  15126. << "verify_hostname should match an IPv6 iPAddress SAN";
  15127. EXPECT_FALSE(wrong_ipv6_matched)
  15128. << "verify_hostname should not match a non-matching IPv6 address";
  15129. EXPECT_FALSE(cn_ipv6_matched)
  15130. << "An IPv6 host must not be authenticated via the certificate CN";
  15131. }
  15132. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  15133. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  15134. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  15135. using namespace httplib::tls;
  15136. // SANs: DNS:a.zz, IP:42.46.122.122
  15137. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15138. ASSERT_TRUE(svr.is_valid());
  15139. svr.Get("/test", [](const Request &, Response &res) {
  15140. res.set_content("ok", "text/plain");
  15141. });
  15142. auto port = svr.bind_to_any_port(HOST);
  15143. thread t([&]() { svr.listen_after_bind(); });
  15144. auto se = detail::scope_exit([&] {
  15145. svr.stop();
  15146. t.join();
  15147. });
  15148. svr.wait_until_ready();
  15149. bool verify_callback_called = false;
  15150. bool dns_san_matched = false;
  15151. bool ip_san_matched = false;
  15152. bool ip_matched_via_dns_san = true;
  15153. bool dns_matched_via_ip_san = true;
  15154. bool cn_matched_next_to_dns_san = true;
  15155. SSLClient cli(HOST, port);
  15156. cli.enable_server_certificate_verification(true);
  15157. cli.set_ca_cert_path(CA_CERT_FILE);
  15158. cli.set_connection_timeout(5);
  15159. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15160. verify_callback_called = true;
  15161. if (!ctx.cert) return false;
  15162. dns_san_matched = ctx.check_hostname("a.zz");
  15163. ip_san_matched = ctx.check_hostname("42.46.122.122");
  15164. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  15165. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  15166. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  15167. return true; // Accept for the purpose of this test
  15168. });
  15169. cli.Get("/test");
  15170. ASSERT_TRUE(verify_callback_called)
  15171. << "Verify callback should have been called";
  15172. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  15173. EXPECT_TRUE(ip_san_matched)
  15174. << "verify_hostname should match an iPAddress SAN";
  15175. EXPECT_FALSE(ip_matched_via_dns_san)
  15176. << "An IP host must not be authenticated via a dNSName SAN";
  15177. EXPECT_FALSE(dns_matched_via_ip_san)
  15178. << "A DNS host must not be authenticated via an iPAddress SAN";
  15179. EXPECT_FALSE(cn_matched_next_to_dns_san)
  15180. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  15181. }
  15182. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  15183. // "www.*.example.test" names one host and not every host under example.test.
  15184. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  15185. using namespace httplib::tls;
  15186. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  15187. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  15188. ASSERT_TRUE(svr.is_valid());
  15189. svr.Get("/test", [](const Request &, Response &res) {
  15190. res.set_content("ok", "text/plain");
  15191. });
  15192. auto port = svr.bind_to_any_port(HOST);
  15193. thread t([&]() { svr.listen_after_bind(); });
  15194. auto se = detail::scope_exit([&] {
  15195. svr.stop();
  15196. t.join();
  15197. });
  15198. svr.wait_until_ready();
  15199. bool verify_callback_called = false;
  15200. bool leftmost_wildcard_matched = false;
  15201. bool wildcard_spanned_labels = true;
  15202. bool inner_wildcard_matched = true;
  15203. SSLClient cli(HOST, port);
  15204. cli.enable_server_certificate_verification(true);
  15205. cli.set_ca_cert_path(CA_CERT_FILE);
  15206. cli.set_connection_timeout(5);
  15207. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15208. verify_callback_called = true;
  15209. if (!ctx.cert) return false;
  15210. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  15211. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  15212. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  15213. return true; // Accept for the purpose of this test
  15214. });
  15215. cli.Get("/test");
  15216. ASSERT_TRUE(verify_callback_called)
  15217. << "Verify callback should have been called";
  15218. EXPECT_TRUE(leftmost_wildcard_matched)
  15219. << "A leftmost wildcard should match a single label";
  15220. EXPECT_FALSE(wildcard_spanned_labels)
  15221. << "A wildcard label must not match more than one label";
  15222. EXPECT_FALSE(inner_wildcard_matched)
  15223. << "A wildcard outside the leftmost label must not be honoured";
  15224. }
  15225. // sans() must report each SAN entry under its own type.
  15226. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  15227. using namespace httplib::tls;
  15228. // SANs: DNS:a.zz, IP:42.46.122.122
  15229. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  15230. ASSERT_TRUE(svr.is_valid());
  15231. svr.Get("/test", [](const Request &, Response &res) {
  15232. res.set_content("ok", "text/plain");
  15233. });
  15234. auto port = svr.bind_to_any_port(HOST);
  15235. thread t([&]() { svr.listen_after_bind(); });
  15236. auto se = detail::scope_exit([&] {
  15237. svr.stop();
  15238. t.join();
  15239. });
  15240. svr.wait_until_ready();
  15241. bool verify_callback_called = false;
  15242. std::vector<SanEntry> sans;
  15243. SSLClient cli(HOST, port);
  15244. cli.enable_server_certificate_verification(true);
  15245. cli.set_ca_cert_path(CA_CERT_FILE);
  15246. cli.set_connection_timeout(5);
  15247. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15248. verify_callback_called = true;
  15249. if (!ctx.cert) return false;
  15250. sans = ctx.sans();
  15251. return true; // Accept for the purpose of this test
  15252. });
  15253. cli.Get("/test");
  15254. ASSERT_TRUE(verify_callback_called)
  15255. << "Verify callback should have been called";
  15256. auto has_san = [&](SanType type, const std::string &value) {
  15257. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  15258. return san.type == type && san.value == value;
  15259. });
  15260. };
  15261. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  15262. << "sans() should report the dNSName SAN";
  15263. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  15264. << "sans() should report the iPAddress SAN";
  15265. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  15266. << "sans() must not report the dNSName SAN as an address";
  15267. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  15268. << "sans() must not report the iPAddress SAN as a DNS name";
  15269. }
  15270. #endif
  15271. // mbedTLS-specific callback constructor test
  15272. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  15273. #ifdef CPPHTTPLIB_SSL_ENABLED
  15274. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  15275. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15276. ASSERT_TRUE(svr.is_valid());
  15277. // Set up a handler to verify client certificate is present
  15278. bool client_cert_verified = false;
  15279. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15280. // Verify that client certificate was provided
  15281. client_cert_verified = true;
  15282. res.set_content("success", "text/plain");
  15283. });
  15284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15285. auto se = detail::scope_exit([&] {
  15286. svr.stop();
  15287. t.join();
  15288. ASSERT_FALSE(svr.is_running());
  15289. });
  15290. svr.wait_until_ready();
  15291. // Client with certificate
  15292. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15293. cli.enable_server_certificate_verification(false);
  15294. cli.set_connection_timeout(30);
  15295. auto res = cli.Get("/test");
  15296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15297. ASSERT_EQ(StatusCode::OK_200, res->status);
  15298. ASSERT_TRUE(client_cert_verified);
  15299. EXPECT_EQ("success", res->body);
  15300. }
  15301. #endif
  15302. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  15303. // backends
  15304. #ifdef CPPHTTPLIB_SSL_ENABLED
  15305. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  15306. using namespace httplib::tls;
  15307. // Test that when client CA cert file is provided,
  15308. // the server properly requests and validates client certificates
  15309. // Create a server with client authentication
  15310. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  15311. ASSERT_TRUE(svr.is_valid());
  15312. bool handler_called = false;
  15313. svr.Get("/test", [&](const Request &req, Response &res) {
  15314. handler_called = true;
  15315. // Verify that a client certificate was provided
  15316. auto cert = req.peer_cert();
  15317. ASSERT_TRUE(static_cast<bool>(cert));
  15318. // Get the issuer name
  15319. std::string issuer_str = cert.issuer_name();
  15320. ASSERT_FALSE(issuer_str.empty());
  15321. // The client certificate should be issued by our test CA
  15322. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  15323. res.set_content("authenticated", "text/plain");
  15324. });
  15325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15326. auto se = detail::scope_exit([&] {
  15327. svr.stop();
  15328. t.join();
  15329. ASSERT_FALSE(svr.is_running());
  15330. });
  15331. svr.wait_until_ready();
  15332. // Connect with a client certificate issued by the CA
  15333. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15334. cli.enable_server_certificate_verification(false);
  15335. cli.set_connection_timeout(30);
  15336. auto res = cli.Get("/test");
  15337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15338. ASSERT_EQ(StatusCode::OK_200, res->status);
  15339. ASSERT_TRUE(handler_called);
  15340. EXPECT_EQ("authenticated", res->body);
  15341. }
  15342. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  15343. using namespace httplib::tls;
  15344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15345. ASSERT_TRUE(svr.is_valid());
  15346. svr.Get("/test", [](const Request &, Response &res) {
  15347. res.set_content("ok", "text/plain");
  15348. });
  15349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15350. auto se = detail::scope_exit([&] {
  15351. svr.stop();
  15352. t.join();
  15353. });
  15354. svr.wait_until_ready();
  15355. SSLClient cli(HOST, PORT);
  15356. cli.enable_server_certificate_verification(false);
  15357. cli.set_connection_timeout(30);
  15358. bool cert_checked = false;
  15359. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15360. if (ctx.cert) {
  15361. auto sans = ctx.sans();
  15362. // Test certificate may or may not have SANs - just verify the API
  15363. // works If SANs exist, verify the types are valid
  15364. for (const auto &san : sans) {
  15365. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  15366. san.type == SanType::EMAIL || san.type == SanType::URI ||
  15367. san.type == SanType::OTHER);
  15368. EXPECT_FALSE(san.value.empty());
  15369. }
  15370. cert_checked = true;
  15371. }
  15372. return true;
  15373. });
  15374. auto res = cli.Get("/test");
  15375. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15376. EXPECT_TRUE(cert_checked);
  15377. }
  15378. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  15379. using namespace httplib::tls;
  15380. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15381. ASSERT_TRUE(svr.is_valid());
  15382. svr.Get("/test", [](const Request &, Response &res) {
  15383. res.set_content("ok", "text/plain");
  15384. });
  15385. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15386. auto se = detail::scope_exit([&] {
  15387. svr.stop();
  15388. t.join();
  15389. });
  15390. svr.wait_until_ready();
  15391. SSLClient cli(HOST, PORT);
  15392. cli.enable_server_certificate_verification(false);
  15393. cli.set_connection_timeout(30);
  15394. bool validity_checked = false;
  15395. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15396. if (ctx.cert) {
  15397. time_t not_before = 0, not_after = 0;
  15398. bool result = ctx.validity(not_before, not_after);
  15399. EXPECT_TRUE(result);
  15400. // Verify that not_before < now < not_after for a valid cert
  15401. time_t now = time(nullptr);
  15402. EXPECT_LT(not_before, now);
  15403. EXPECT_GT(not_after, now);
  15404. validity_checked = true;
  15405. }
  15406. return true;
  15407. });
  15408. auto res = cli.Get("/test");
  15409. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15410. EXPECT_TRUE(validity_checked);
  15411. }
  15412. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  15413. using namespace httplib::tls;
  15414. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15415. ASSERT_TRUE(svr.is_valid());
  15416. svr.Get("/test", [](const Request &, Response &res) {
  15417. res.set_content("ok", "text/plain");
  15418. });
  15419. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15420. auto se = detail::scope_exit([&] {
  15421. svr.stop();
  15422. t.join();
  15423. });
  15424. svr.wait_until_ready();
  15425. SSLClient cli(HOST, PORT);
  15426. cli.enable_server_certificate_verification(false);
  15427. cli.set_connection_timeout(30);
  15428. bool serial_checked = false;
  15429. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15430. if (ctx.cert) {
  15431. std::string serial = ctx.serial();
  15432. EXPECT_FALSE(serial.empty());
  15433. // Serial should be a hex string
  15434. for (char c : serial) {
  15435. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  15436. (c >= 'a' && c <= 'f'));
  15437. }
  15438. serial_checked = true;
  15439. }
  15440. return true;
  15441. });
  15442. auto res = cli.Get("/test");
  15443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15444. EXPECT_TRUE(serial_checked);
  15445. }
  15446. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  15447. // Test 1: Valid CA file - no error should be recorded
  15448. {
  15449. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  15450. CLIENT_CA_CERT_FILE);
  15451. ASSERT_TRUE(svr.is_valid());
  15452. // With valid setup, last_ssl_error should be 0
  15453. EXPECT_EQ(0, svr.ssl_last_error());
  15454. }
  15455. // Test 2: Invalid CA file content
  15456. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  15457. {
  15458. // Create a temporary file with completely invalid content
  15459. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  15460. {
  15461. std::ofstream ofs(temp_invalid_ca);
  15462. ofs << "This is not a certificate file at all\n";
  15463. ofs << "Just plain text content\n";
  15464. }
  15465. // Create server with invalid CA file
  15466. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  15467. // Clean up temporary file
  15468. std::remove(temp_invalid_ca);
  15469. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  15470. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  15471. // Note: SSL_CTX_load_verify_locations typically fails first,
  15472. // but our error handling code path is still exercised
  15473. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  15474. }
  15475. }
  15476. TEST(VerifyCallbackTest, VerifyContextFields) {
  15477. using namespace httplib::tls;
  15478. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15479. ASSERT_TRUE(svr.is_valid());
  15480. svr.Get("/test", [](const Request &, Response &res) {
  15481. res.set_content("ok", "text/plain");
  15482. });
  15483. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15484. auto se = detail::scope_exit([&] {
  15485. svr.stop();
  15486. t.join();
  15487. });
  15488. svr.wait_until_ready();
  15489. SSLClient cli(HOST, PORT);
  15490. cli.enable_server_certificate_verification(false);
  15491. cli.set_connection_timeout(30);
  15492. int callback_count = 0;
  15493. bool saw_leaf_cert = false;
  15494. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  15495. if (ctx.cert) {
  15496. callback_count++;
  15497. // We should see at least one certificate (the leaf)
  15498. std::string cn = ctx.subject_cn();
  15499. if (!cn.empty()) { saw_leaf_cert = true; }
  15500. // Verify context fields are populated
  15501. EXPECT_NE(ctx.session, nullptr);
  15502. EXPECT_GE(ctx.depth, 0);
  15503. }
  15504. return true;
  15505. });
  15506. auto res = cli.Get("/test");
  15507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15508. EXPECT_GT(callback_count, 0);
  15509. EXPECT_TRUE(saw_leaf_cert);
  15510. }
  15511. // A verifier that accepts runs alongside the built-in verification, and is the
  15512. // only check once that is turned off.
  15513. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  15514. using namespace httplib::tls;
  15515. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15516. ASSERT_TRUE(svr.is_valid());
  15517. svr.Get("/test", [](const Request &, Response &res) {
  15518. res.set_content("ok", "text/plain");
  15519. });
  15520. auto port = svr.bind_to_any_port(HOST);
  15521. thread t([&]() { svr.listen_after_bind(); });
  15522. auto se = detail::scope_exit([&] {
  15523. svr.stop();
  15524. t.join();
  15525. });
  15526. svr.wait_until_ready();
  15527. SSLClient cli(HOST, port);
  15528. cli.enable_server_hostname_verification(false);
  15529. auto calls = 0;
  15530. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  15531. calls++;
  15532. return true;
  15533. });
  15534. // cert.pem is not trusted
  15535. auto res = cli.Get("/test");
  15536. ASSERT_FALSE(res);
  15537. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15538. EXPECT_GT(calls, 0);
  15539. cli.enable_server_certificate_verification(false);
  15540. res = cli.Get("/test");
  15541. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15542. EXPECT_EQ("ok", res->body);
  15543. }
  15544. // A verifier belongs to the client that set it, not to the thread that set it.
  15545. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  15546. using namespace httplib::tls;
  15547. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15548. ASSERT_TRUE(svr.is_valid());
  15549. svr.Get("/test", [](const Request &, Response &res) {
  15550. res.set_content("ok", "text/plain");
  15551. });
  15552. auto port = svr.bind_to_any_port(HOST);
  15553. thread t([&]() { svr.listen_after_bind(); });
  15554. auto se = detail::scope_exit([&] {
  15555. svr.stop();
  15556. t.join();
  15557. });
  15558. svr.wait_until_ready();
  15559. auto rejecting_calls = 0;
  15560. SSLClient rejecting(HOST, port);
  15561. rejecting.enable_server_certificate_verification(false);
  15562. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  15563. rejecting_calls++;
  15564. return false;
  15565. });
  15566. auto accepting_calls = 0;
  15567. SSLClient accepting(HOST, port);
  15568. accepting.enable_server_certificate_verification(false);
  15569. // Set on another thread than the requests below.
  15570. thread([&]() {
  15571. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  15572. accepting_calls++;
  15573. return true;
  15574. });
  15575. }).join();
  15576. // Requested on another thread than the verifier was set on.
  15577. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  15578. EXPECT_GT(rejecting_calls, 0);
  15579. auto res = accepting.Get("/test");
  15580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15581. EXPECT_GT(accepting_calls, 0);
  15582. }
  15583. // A verifier replaced while a handshake runs it lives until it returns.
  15584. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  15585. using namespace httplib::tls;
  15586. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15587. ASSERT_TRUE(svr.is_valid());
  15588. svr.Get("/test", [](const Request &, Response &res) {
  15589. res.set_content("ok", "text/plain");
  15590. });
  15591. auto port = svr.bind_to_any_port(HOST);
  15592. thread t([&]() { svr.listen_after_bind(); });
  15593. auto se = detail::scope_exit([&] {
  15594. svr.stop();
  15595. t.join();
  15596. });
  15597. svr.wait_until_ready();
  15598. SSLClient cli(HOST, port);
  15599. cli.enable_server_certificate_verification(false);
  15600. std::promise<void> entered;
  15601. std::promise<void> replaced;
  15602. auto replaced_future = replaced.get_future();
  15603. auto first_call = true;
  15604. // Long enough to live on the heap
  15605. std::string expected(64, 'v');
  15606. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  15607. if (first_call) {
  15608. first_call = false;
  15609. entered.set_value();
  15610. replaced_future.wait();
  15611. }
  15612. return expected == std::string(64, 'v');
  15613. });
  15614. thread request([&]() {
  15615. auto res = cli.Get("/test");
  15616. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  15617. });
  15618. entered.get_future().wait();
  15619. cli.set_server_certificate_verifier(
  15620. [](const VerifyContext &) { return true; });
  15621. replaced.set_value();
  15622. request.join();
  15623. }
  15624. // VerifyContext::session is the same handle the other tls:: functions take.
  15625. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  15626. using namespace httplib::tls;
  15627. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15628. ASSERT_TRUE(svr.is_valid());
  15629. svr.Get("/test", [](const Request &, Response &res) {
  15630. res.set_content("ok", "text/plain");
  15631. });
  15632. auto port = svr.bind_to_any_port(HOST);
  15633. thread t([&]() { svr.listen_after_bind(); });
  15634. auto se = detail::scope_exit([&] {
  15635. svr.stop();
  15636. t.join();
  15637. });
  15638. svr.wait_until_ready();
  15639. SSLClient cli(HOST, port);
  15640. cli.enable_server_certificate_verification(false);
  15641. session_t verifier_session = nullptr;
  15642. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  15643. verifier_session = ctx.session;
  15644. return true;
  15645. });
  15646. session_t session_verifier_session = nullptr;
  15647. cli.set_session_verifier([&](session_t session) {
  15648. session_verifier_session = session;
  15649. return SSLVerifierResponse::NoDecisionMade;
  15650. });
  15651. auto res = cli.Get("/test");
  15652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15653. EXPECT_NE(nullptr, verifier_session);
  15654. EXPECT_EQ(session_verifier_session, verifier_session);
  15655. }
  15656. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  15657. using httplib::tls::TlsError;
  15658. // Test that verify_error_to_string returns empty for success
  15659. std::string success_str = TlsError::verify_error_to_string(0);
  15660. EXPECT_TRUE(success_str.empty());
  15661. // Test that verify_error_to_string returns non-empty for error codes
  15662. // Using a common error code (certificate expired)
  15663. std::string error_str =
  15664. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  15665. EXPECT_FALSE(error_str.empty());
  15666. }
  15667. TEST(SessionVerifierTest, CertificateAccepted) {
  15668. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15669. ASSERT_TRUE(svr.is_valid());
  15670. svr.Get("/test", [](const Request &, Response &res) {
  15671. res.set_content("ok", "text/plain");
  15672. });
  15673. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15674. auto se = detail::scope_exit([&] {
  15675. svr.stop();
  15676. t.join();
  15677. });
  15678. svr.wait_until_ready();
  15679. SSLClient cli(HOST, PORT);
  15680. cli.enable_server_certificate_verification(false);
  15681. cli.set_connection_timeout(30);
  15682. bool callback_called = false;
  15683. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15684. EXPECT_NE(session, nullptr);
  15685. callback_called = true;
  15686. return SSLVerifierResponse::CertificateAccepted;
  15687. });
  15688. auto res = cli.Get("/test");
  15689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15690. EXPECT_EQ(200, res->status);
  15691. EXPECT_TRUE(callback_called);
  15692. }
  15693. TEST(SessionVerifierTest, CertificateRejected) {
  15694. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15695. ASSERT_TRUE(svr.is_valid());
  15696. svr.Get("/test", [](const Request &, Response &res) {
  15697. res.set_content("ok", "text/plain");
  15698. });
  15699. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15700. auto se = detail::scope_exit([&] {
  15701. svr.stop();
  15702. t.join();
  15703. });
  15704. svr.wait_until_ready();
  15705. SSLClient cli(HOST, PORT);
  15706. cli.enable_server_certificate_verification(false);
  15707. cli.set_connection_timeout(30);
  15708. bool callback_called = false;
  15709. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15710. EXPECT_NE(session, nullptr);
  15711. callback_called = true;
  15712. return SSLVerifierResponse::CertificateRejected;
  15713. });
  15714. auto res = cli.Get("/test");
  15715. EXPECT_FALSE(res);
  15716. EXPECT_TRUE(callback_called);
  15717. }
  15718. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  15719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15720. ASSERT_TRUE(svr.is_valid());
  15721. svr.Get("/test", [](const Request &, Response &res) {
  15722. res.set_content("ok", "text/plain");
  15723. });
  15724. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15725. auto se = detail::scope_exit([&] {
  15726. svr.stop();
  15727. t.join();
  15728. });
  15729. svr.wait_until_ready();
  15730. // NoDecisionMade with verification disabled should succeed (no default check)
  15731. SSLClient cli(HOST, PORT);
  15732. cli.enable_server_certificate_verification(false);
  15733. cli.set_connection_timeout(30);
  15734. bool callback_called = false;
  15735. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15736. EXPECT_NE(session, nullptr);
  15737. callback_called = true;
  15738. return SSLVerifierResponse::NoDecisionMade;
  15739. });
  15740. auto res = cli.Get("/test");
  15741. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15742. EXPECT_EQ(200, res->status);
  15743. EXPECT_TRUE(callback_called);
  15744. }
  15745. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  15746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15747. ASSERT_TRUE(svr.is_valid());
  15748. svr.Get("/test", [](const Request &, Response &res) {
  15749. res.set_content("ok", "text/plain");
  15750. });
  15751. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  15752. auto se = detail::scope_exit([&] {
  15753. svr.stop();
  15754. t.join();
  15755. });
  15756. svr.wait_until_ready();
  15757. // NoDecisionMade with verification enabled should fail (self-signed cert).
  15758. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  15759. // so we only check that the request fails, not whether the callback was
  15760. // called.
  15761. SSLClient cli(HOST, PORT);
  15762. cli.enable_server_certificate_verification(true);
  15763. cli.set_connection_timeout(30);
  15764. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  15765. EXPECT_NE(session, nullptr);
  15766. return SSLVerifierResponse::NoDecisionMade;
  15767. });
  15768. auto res = cli.Get("/test");
  15769. EXPECT_FALSE(res);
  15770. }
  15771. TEST(SSLClientServerTest, ClientCAListFromPem) {
  15772. // Test SSL server using PemMemory constructor with client CA certificates
  15773. // Read PEM files
  15774. std::string server_cert_pem, server_key_pem, client_ca_pem;
  15775. read_file(SERVER_CERT_FILE, server_cert_pem);
  15776. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  15777. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  15778. // Create SSLServer with PemMemory constructor including client CA
  15779. SSLServer::PemMemory server_pem = {
  15780. server_cert_pem.c_str(),
  15781. server_cert_pem.size(),
  15782. server_key_pem.c_str(),
  15783. server_key_pem.size(),
  15784. client_ca_pem.c_str(),
  15785. client_ca_pem.size(),
  15786. nullptr // no password for server key
  15787. };
  15788. SSLServer svr(server_pem);
  15789. ASSERT_TRUE(svr.is_valid());
  15790. // No SSL error should be recorded for valid setup
  15791. EXPECT_EQ(0, svr.ssl_last_error());
  15792. // Set up server endpoints
  15793. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  15794. res.set_content("ok", "text/plain");
  15795. });
  15796. // Start server in a thread
  15797. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  15798. svr.wait_until_ready();
  15799. // Connect with client certificate (using constructor with paths)
  15800. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15801. cli.enable_server_certificate_verification(false);
  15802. auto res = cli.Get("/test-pem-ca");
  15803. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15804. EXPECT_EQ(200, res->status);
  15805. EXPECT_EQ("ok", res->body);
  15806. svr.stop();
  15807. server_thread.join();
  15808. }
  15809. #endif
  15810. #ifdef _WIN32
  15811. TEST(CleanupTest, WSACleanup) {
  15812. int ret = WSACleanup();
  15813. ASSERT_EQ(0, ret);
  15814. }
  15815. #endif
  15816. #ifndef CPPHTTPLIB_SSL_ENABLED
  15817. TEST(NoSSLSupport, SimpleInterface) {
  15818. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  15819. }
  15820. #endif
  15821. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  15822. TEST(InvalidScheme, SimpleInterface) {
  15823. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  15824. }
  15825. #endif
  15826. TEST(NoScheme, SimpleInterface) {
  15827. Client cli("yahoo.com:80");
  15828. ASSERT_TRUE(cli.is_valid());
  15829. }
  15830. TEST(SendAPI, SimpleInterface_Online) {
  15831. Client cli("http://yahoo.com");
  15832. Request req;
  15833. req.method = "GET";
  15834. req.path = "/";
  15835. auto res = cli.send(req);
  15836. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15837. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15838. }
  15839. TEST(SendAPI, WithParamsInRequest) {
  15840. Server svr;
  15841. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  15842. EXPECT_TRUE(req.has_param("test"));
  15843. EXPECT_EQ("test_value", req.get_param_value("test"));
  15844. });
  15845. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  15846. auto se = detail::scope_exit([&] {
  15847. svr.stop();
  15848. t.join();
  15849. ASSERT_FALSE(svr.is_running());
  15850. });
  15851. svr.wait_until_ready();
  15852. Client cli(HOST, PORT);
  15853. {
  15854. Request req;
  15855. req.method = "GET";
  15856. req.path = "/";
  15857. req.params.emplace("test", "test_value");
  15858. auto res = cli.send(req);
  15859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15860. }
  15861. {
  15862. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  15863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15864. }
  15865. }
  15866. TEST(ClientImplMethods, GetSocketTest) {
  15867. httplib::Server svr;
  15868. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  15869. res.status = StatusCode::OK_200;
  15870. });
  15871. auto port = svr.bind_to_any_port("127.0.0.1");
  15872. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  15873. auto se = detail::scope_exit([&] {
  15874. svr.stop();
  15875. thread.join();
  15876. ASSERT_FALSE(svr.is_running());
  15877. });
  15878. svr.wait_until_ready();
  15879. {
  15880. httplib::Client cli("127.0.0.1", port);
  15881. cli.set_keep_alive(true);
  15882. // Use the behavior of cpp-httplib of opening the connection
  15883. // only when the first request happens. If that changes,
  15884. // this test would be obsolete.
  15885. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  15886. // This also implicitly tests the server. But other tests would fail much
  15887. // earlier than this one to be considered.
  15888. auto res = cli.Get("/");
  15889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15890. EXPECT_EQ(StatusCode::OK_200, res->status);
  15891. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  15892. }
  15893. }
  15894. #ifdef CPPHTTPLIB_SSL_ENABLED
  15895. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  15896. Client cli("http://yahoo.com");
  15897. auto res = cli.Get("/");
  15898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15899. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15900. cli.set_follow_location(true);
  15901. res = cli.Get("/");
  15902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15903. EXPECT_EQ(StatusCode::OK_200, res->status);
  15904. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15905. }
  15906. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  15907. Client cli("https://yahoo.com");
  15908. auto res = cli.Get("/");
  15909. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15910. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15911. cli.set_follow_location(true);
  15912. res = cli.Get("/");
  15913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15914. EXPECT_EQ(StatusCode::OK_200, res->status);
  15915. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15916. }
  15917. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  15918. Client cli("https://yahoo.com");
  15919. auto res = cli.Get("/");
  15920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15921. ASSERT_FALSE(!res);
  15922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15923. ASSERT_FALSE(res == nullptr);
  15924. ASSERT_TRUE(res != nullptr);
  15925. EXPECT_EQ(Error::Success, res.error());
  15926. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  15927. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  15928. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  15929. cli.set_follow_location(true);
  15930. res = cli.Get("/");
  15931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15932. EXPECT_EQ(Error::Success, res.error());
  15933. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  15934. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  15935. EXPECT_EQ(StatusCode::OK_200, res->status);
  15936. EXPECT_EQ("https://www.yahoo.com/", res->location);
  15937. }
  15938. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  15939. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  15940. Client cli("https://cdnjs.cloudflare.com");
  15941. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  15942. Headers{{"Accept-Encoding", "br"}});
  15943. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15944. EXPECT_EQ(StatusCode::OK_200, res->status);
  15945. EXPECT_EQ(287630U, res->body.size());
  15946. EXPECT_EQ("application/javascript; charset=utf-8",
  15947. res->get_header_value("Content-Type"));
  15948. }
  15949. #endif
  15950. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  15951. #undef REDIR_HOST // Silence compiler warning
  15952. #define REDIR_HOST "https://httpbingo.org"
  15953. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  15954. Client cli(REDIR_HOST);
  15955. cli.set_follow_location(true);
  15956. auto res = retry_service_failures([&] {
  15957. return cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  15958. });
  15959. SKIP_ON_SERVICE_FAILURE(res);
  15960. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15961. EXPECT_EQ(StatusCode::OK_200, res->status);
  15962. }
  15963. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  15964. Client cli(REDIR_HOST);
  15965. cli.set_follow_location(true);
  15966. Params params;
  15967. params.emplace("url", "http://example.com");
  15968. params.emplace("status_code", "302");
  15969. auto res = retry_service_failures(
  15970. [&] { return cli.Get(REDIR_PATH, params, Headers{}); });
  15971. SKIP_ON_SERVICE_FAILURE(res);
  15972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15973. EXPECT_EQ(StatusCode::OK_200, res->status);
  15974. }
  15975. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  15976. Client cli(REDIR_HOST);
  15977. cli.set_follow_location(true);
  15978. Params params;
  15979. params.emplace("url", "http://example.com");
  15980. auto res = retry_service_failures([&] {
  15981. return cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  15982. });
  15983. SKIP_ON_SERVICE_FAILURE(res);
  15984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15985. EXPECT_EQ(StatusCode::OK_200, res->status);
  15986. }
  15987. TEST(HttpToHttpsRedirectTest, CertFile) {
  15988. auto ssl_port = PORT + 1;
  15989. Server svr;
  15990. ASSERT_TRUE(svr.is_valid());
  15991. svr.Get("/index", [&](const Request &, Response &res) {
  15992. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15993. "/index");
  15994. svr.stop();
  15995. });
  15996. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15997. ASSERT_TRUE(ssl_svr.is_valid());
  15998. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  15999. res.set_content("test", "text/plain");
  16000. ssl_svr.stop();
  16001. });
  16002. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16003. thread t2 =
  16004. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  16005. auto se = detail::scope_exit([&] {
  16006. t2.join();
  16007. t.join();
  16008. ASSERT_FALSE(svr.is_running());
  16009. });
  16010. svr.wait_until_ready();
  16011. ssl_svr.wait_until_ready();
  16012. Client cli("127.0.0.1", PORT);
  16013. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16014. cli.enable_server_certificate_verification(true);
  16015. cli.set_follow_location(true);
  16016. cli.set_connection_timeout(30);
  16017. auto res = cli.Get("/index");
  16018. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16019. ASSERT_EQ(StatusCode::OK_200, res->status);
  16020. }
  16021. TEST(UppercaseSchemeTest, UsesTLS) {
  16022. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16023. ASSERT_TRUE(ssl_svr.is_valid());
  16024. ssl_svr.Get("/index", [](const Request &, Response &res) {
  16025. res.set_content("test", "text/plain");
  16026. });
  16027. auto ssl_port = ssl_svr.bind_to_any_port("127.0.0.1");
  16028. auto https_url = "HTTPS://127.0.0.1:" + std::to_string(ssl_port);
  16029. Server svr;
  16030. svr.Get("/index", [&](const Request &, Response &res) {
  16031. res.set_redirect(https_url + "/index");
  16032. });
  16033. auto port = svr.bind_to_any_port("127.0.0.1");
  16034. auto t = thread([&] { ssl_svr.listen_after_bind(); });
  16035. auto t2 = thread([&] { svr.listen_after_bind(); });
  16036. auto se = detail::scope_exit([&] {
  16037. svr.stop();
  16038. ssl_svr.stop();
  16039. t2.join();
  16040. t.join();
  16041. });
  16042. ssl_svr.wait_until_ready();
  16043. svr.wait_until_ready();
  16044. {
  16045. Client cli(https_url);
  16046. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16047. auto res = cli.Get("/index");
  16048. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16049. EXPECT_EQ("test", res->body);
  16050. }
  16051. {
  16052. Client cli("127.0.0.1", port);
  16053. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  16054. cli.set_follow_location(true);
  16055. auto res = cli.Get("/index");
  16056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16057. EXPECT_EQ("test", res->body);
  16058. }
  16059. }
  16060. TEST(SSLClientRedirectTest, CertFile) {
  16061. auto ssl_port = PORT + 1;
  16062. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16063. ASSERT_TRUE(ssl_svr1.is_valid());
  16064. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16065. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16066. "/index");
  16067. ssl_svr1.stop();
  16068. });
  16069. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16070. ASSERT_TRUE(ssl_svr2.is_valid());
  16071. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16072. res.set_content("test", "text/plain");
  16073. ssl_svr2.stop();
  16074. });
  16075. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16076. thread t2 =
  16077. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16078. auto se = detail::scope_exit([&] {
  16079. t2.join();
  16080. t.join();
  16081. ASSERT_FALSE(ssl_svr1.is_running());
  16082. });
  16083. ssl_svr1.wait_until_ready();
  16084. ssl_svr2.wait_until_ready();
  16085. SSLClient cli("127.0.0.1", PORT);
  16086. std::string cert;
  16087. read_file(SERVER_CERT2_FILE, cert);
  16088. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16089. cli.enable_server_certificate_verification(true);
  16090. cli.set_follow_location(true);
  16091. cli.set_connection_timeout(30);
  16092. auto res = cli.Get("/index");
  16093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16094. ASSERT_EQ(StatusCode::OK_200, res->status);
  16095. }
  16096. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  16097. // another port, so the client follows it with a new client.
  16098. static Result GetThroughTlsRedirectToDifferentPort(
  16099. const std::function<void(SSLClient &)> &setup,
  16100. const char *target_cert = SERVER_CERT2_FILE,
  16101. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  16102. auto ssl_port = PORT + 1;
  16103. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16104. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16105. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16106. "/index");
  16107. });
  16108. SSLServer ssl_svr2(target_cert, target_key);
  16109. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16110. res.set_content("test", "text/plain");
  16111. });
  16112. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  16113. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  16114. auto se = detail::scope_exit([&] {
  16115. ssl_svr2.stop();
  16116. ssl_svr1.stop();
  16117. t2.join();
  16118. t.join();
  16119. });
  16120. ssl_svr1.wait_until_ready();
  16121. ssl_svr2.wait_until_ready();
  16122. SSLClient cli("127.0.0.1", PORT);
  16123. cli.set_follow_location(true);
  16124. cli.set_connection_timeout(30);
  16125. setup(cli);
  16126. return cli.Get("/index");
  16127. }
  16128. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  16129. auto calls = 0;
  16130. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  16131. cli.enable_server_certificate_verification(false);
  16132. // Accept the first server only.
  16133. cli.set_session_verifier([&](tls::session_t) {
  16134. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  16135. : SSLVerifierResponse::CertificateRejected;
  16136. });
  16137. });
  16138. ASSERT_FALSE(res);
  16139. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16140. EXPECT_EQ(2, calls);
  16141. }
  16142. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  16143. std::string pinned;
  16144. auto res = GetThroughTlsRedirectToDifferentPort(
  16145. [&](SSLClient &cli) {
  16146. cli.enable_server_certificate_verification(false);
  16147. // Pin the first certificate seen.
  16148. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  16149. if (pinned.empty()) { pinned = ctx.serial(); }
  16150. return ctx.serial() == pinned;
  16151. });
  16152. },
  16153. // A certificate other than the first server's.
  16154. SERVER_CERT_FILE);
  16155. EXPECT_FALSE(res);
  16156. EXPECT_FALSE(pinned.empty());
  16157. }
  16158. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  16159. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  16160. std::string cert;
  16161. read_file(SERVER_CERT2_FILE, cert);
  16162. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16163. });
  16164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16165. EXPECT_EQ(StatusCode::OK_200, res->status);
  16166. }
  16167. // The target's certificate is signed by the root CA, which the first server's
  16168. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  16169. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  16170. auto res = GetThroughTlsRedirectToDifferentPort(
  16171. [](SSLClient &cli) {
  16172. std::string root_ca, cert;
  16173. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16174. read_file(SERVER_CERT2_FILE, cert);
  16175. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16176. cli.load_ca_cert_store(cert.data(), cert.size());
  16177. cli.enable_server_hostname_verification(false);
  16178. },
  16179. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16181. EXPECT_EQ(StatusCode::OK_200, res->status);
  16182. }
  16183. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16184. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  16185. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  16186. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  16187. auto res = GetThroughTlsRedirectToDifferentPort(
  16188. [](SSLClient &cli) {
  16189. std::string root_ca, cert;
  16190. read_file(CLIENT_CA_CERT_FILE, root_ca);
  16191. read_file(SERVER_CERT2_FILE, cert);
  16192. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  16193. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16194. cli.enable_server_hostname_verification(false);
  16195. },
  16196. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  16197. ASSERT_FALSE(res);
  16198. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16199. }
  16200. #endif
  16201. #endif
  16202. #ifdef CPPHTTPLIB_SSL_ENABLED
  16203. // Test that set_ca_cert_store() skips system certs (consistent with
  16204. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  16205. // should be trusted - system certs should NOT be loaded.
  16206. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  16207. // Load a specific cert that is NOT a system CA cert
  16208. std::string cert;
  16209. read_file(SERVER_CERT2_FILE, cert);
  16210. SSLClient cli("google.com");
  16211. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16212. cli.enable_server_certificate_verification(true);
  16213. // This should FAIL because:
  16214. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  16215. // 2. System certs should NOT be loaded when custom store is set
  16216. // If system certs WERE loaded, this would succeed
  16217. auto res = cli.Get("/");
  16218. ASSERT_FALSE(res);
  16219. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16220. }
  16221. // Same as above, but through the native store handle path. Regression test:
  16222. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  16223. // merged system certs into the user-provided store.
  16224. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  16225. std::string cert;
  16226. read_file(SERVER_CERT2_FILE, cert);
  16227. SSLClient cli("google.com");
  16228. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16229. cli.enable_server_certificate_verification(true);
  16230. auto res = cli.Get("/");
  16231. ASSERT_FALSE(res);
  16232. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16233. }
  16234. // A custom store set via the native handle must still verify a server whose
  16235. // cert it does contain.
  16236. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  16237. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16238. ASSERT_TRUE(svr.is_valid());
  16239. svr.Get("/test", [&](const Request &, Response &res) {
  16240. res.set_content("test", "text/plain");
  16241. });
  16242. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16243. auto se = detail::scope_exit([&] {
  16244. svr.stop();
  16245. t.join();
  16246. ASSERT_FALSE(svr.is_running());
  16247. });
  16248. svr.wait_until_ready();
  16249. SSLClient cli("127.0.0.1", PORT);
  16250. std::string cert;
  16251. read_file(SERVER_CERT2_FILE, cert);
  16252. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  16253. cli.enable_server_certificate_verification(true);
  16254. cli.set_connection_timeout(30);
  16255. auto res = cli.Get("/test");
  16256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16257. ASSERT_EQ(StatusCode::OK_200, res->status);
  16258. }
  16259. // CA certs loaded through the universal Client must be transferred to the
  16260. // client created internally for following an HTTPS redirect. Regression test:
  16261. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  16262. // the CA data for redirect transfer.
  16263. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  16264. auto ssl_port = PORT + 1;
  16265. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16266. ASSERT_TRUE(ssl_svr1.is_valid());
  16267. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  16268. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  16269. "/index");
  16270. });
  16271. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16272. ASSERT_TRUE(ssl_svr2.is_valid());
  16273. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  16274. res.set_content("test", "text/plain");
  16275. });
  16276. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  16277. thread t2 =
  16278. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  16279. auto se = detail::scope_exit([&] {
  16280. ssl_svr2.stop();
  16281. ssl_svr1.stop();
  16282. t2.join();
  16283. t.join();
  16284. ASSERT_FALSE(ssl_svr1.is_running());
  16285. });
  16286. ssl_svr1.wait_until_ready();
  16287. ssl_svr2.wait_until_ready();
  16288. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16289. std::string cert;
  16290. read_file(SERVER_CERT2_FILE, cert);
  16291. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16292. cli.enable_server_certificate_verification(true);
  16293. cli.set_follow_location(true);
  16294. cli.set_connection_timeout(30);
  16295. auto res = cli.Get("/index");
  16296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16297. ASSERT_EQ(StatusCode::OK_200, res->status);
  16298. }
  16299. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  16300. // so a host signed by a system CA verifies even though a custom CA is set
  16301. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  16302. std::string cert;
  16303. read_file(SERVER_CERT2_FILE, cert);
  16304. SSLClient cli("google.com");
  16305. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16306. cli.enable_system_ca(true);
  16307. cli.enable_server_certificate_verification(true);
  16308. auto res = cli.Get("/");
  16309. // Any status: Google may redirect or rate-limit CI runners.
  16310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16311. }
  16312. // The custom CA remains effective when combined with the system CA
  16313. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  16314. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16315. ASSERT_TRUE(svr.is_valid());
  16316. svr.Get("/test", [&](const Request &, Response &res) {
  16317. res.set_content("test", "text/plain");
  16318. });
  16319. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16320. auto se = detail::scope_exit([&] {
  16321. svr.stop();
  16322. t.join();
  16323. ASSERT_FALSE(svr.is_running());
  16324. });
  16325. svr.wait_until_ready();
  16326. SSLClient cli("127.0.0.1", PORT);
  16327. std::string cert;
  16328. read_file(SERVER_CERT2_FILE, cert);
  16329. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16330. cli.enable_system_ca(true);
  16331. cli.enable_server_certificate_verification(true);
  16332. cli.set_connection_timeout(30);
  16333. auto res = cli.Get("/test");
  16334. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16335. ASSERT_EQ(StatusCode::OK_200, res->status);
  16336. }
  16337. #ifdef CPPHTTPLIB_USE_CERTS_FROM_MACOSX_KEYCHAIN
  16338. // A usage-constraints dictionary of a Keychain Trust Settings array, with
  16339. // the keys SecTrustSettingsCopyTrustSettings() returns.
  16340. static CFDictionaryRef
  16341. make_usage_constraint(SecPolicyRef policy, const char *policy_string,
  16342. const SecTrustSettingsResult *result) {
  16343. auto constraint =
  16344. CFDictionaryCreateMutable(nullptr, 0, &kCFTypeDictionaryKeyCallBacks,
  16345. &kCFTypeDictionaryValueCallBacks);
  16346. if (policy) {
  16347. CFDictionarySetValue(constraint, kSecTrustSettingsPolicy, policy);
  16348. }
  16349. if (policy_string) {
  16350. auto str = CFStringCreateWithCString(nullptr, policy_string,
  16351. kCFStringEncodingUTF8);
  16352. CFDictionarySetValue(constraint, kSecTrustSettingsPolicyString, str);
  16353. CFRelease(str);
  16354. }
  16355. if (result) {
  16356. auto number_value = static_cast<SInt32>(*result);
  16357. auto number = CFNumberCreate(nullptr, kCFNumberSInt32Type, &number_value);
  16358. CFDictionarySetValue(constraint, kSecTrustSettingsResult, number);
  16359. CFRelease(number);
  16360. }
  16361. return constraint;
  16362. }
  16363. static SecTrustSettingsResult
  16364. ssl_trust_settings_result(std::vector<CFDictionaryRef> constraints) {
  16365. auto trust_settings =
  16366. CFArrayCreateMutable(nullptr, 0, &kCFTypeArrayCallBacks);
  16367. for (auto constraint : constraints) {
  16368. CFArrayAppendValue(trust_settings, constraint);
  16369. CFRelease(constraint);
  16370. }
  16371. auto result = tls::impl::macos_ssl_trust_settings_result(trust_settings);
  16372. CFRelease(trust_settings);
  16373. return result;
  16374. }
  16375. // The system CA loader takes a Keychain certificate as a trusted root only
  16376. // when its Trust Settings say so for SSL, not merely because it has some.
  16377. TEST(SSLClientTest, MacOSKeychainTrustSettingsForSSL) {
  16378. const auto trust_root = kSecTrustSettingsResultTrustRoot;
  16379. const auto trust_as_root = kSecTrustSettingsResultTrustAsRoot;
  16380. const auto deny = kSecTrustSettingsResultDeny;
  16381. const auto unspecified = kSecTrustSettingsResultUnspecified;
  16382. auto ssl_policy = SecPolicyCreateSSL(true, nullptr);
  16383. auto x509_policy = SecPolicyCreateBasicX509();
  16384. // "Always Trust", which stores no constraint at all
  16385. EXPECT_EQ(kSecTrustSettingsResultTrustRoot, ssl_trust_settings_result({}));
  16386. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16387. ssl_trust_settings_result(
  16388. {make_usage_constraint(nullptr, nullptr, nullptr)}));
  16389. EXPECT_EQ(kSecTrustSettingsResultTrustRoot,
  16390. ssl_trust_settings_result(
  16391. {make_usage_constraint(ssl_policy, nullptr, &trust_root)}));
  16392. EXPECT_EQ(kSecTrustSettingsResultTrustAsRoot,
  16393. ssl_trust_settings_result(
  16394. {make_usage_constraint(ssl_policy, nullptr, &trust_as_root)}));
  16395. // "Never Trust", for everything or for SSL
  16396. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16397. ssl_trust_settings_result(
  16398. {make_usage_constraint(nullptr, nullptr, &deny)}));
  16399. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16400. ssl_trust_settings_result(
  16401. {make_usage_constraint(ssl_policy, nullptr, &deny)}));
  16402. // Trusted for another policy, for one host, or not at all
  16403. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16404. ssl_trust_settings_result(
  16405. {make_usage_constraint(x509_policy, nullptr, &trust_root)}));
  16406. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16407. ssl_trust_settings_result({make_usage_constraint(
  16408. ssl_policy, "www.example.com", &trust_root)}));
  16409. EXPECT_EQ(kSecTrustSettingsResultUnspecified,
  16410. ssl_trust_settings_result(
  16411. {make_usage_constraint(nullptr, nullptr, &unspecified)}));
  16412. // The first constraint that applies to SSL decides
  16413. EXPECT_EQ(kSecTrustSettingsResultDeny,
  16414. ssl_trust_settings_result(
  16415. {make_usage_constraint(x509_policy, nullptr, &trust_root),
  16416. make_usage_constraint(nullptr, nullptr, &deny)}));
  16417. CFRelease(x509_policy);
  16418. CFRelease(ssl_policy);
  16419. }
  16420. #endif
  16421. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  16422. // skip chain verification entirely (only the certificate identity was
  16423. // checked), so a server presenting an untrusted certificate with a matching
  16424. // IP SAN was accepted. The chain must be validated for IP hosts too.
  16425. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  16426. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16427. ASSERT_TRUE(svr.is_valid());
  16428. svr.Get("/test", [&](const Request &, Response &res) {
  16429. res.set_content("test", "text/plain");
  16430. });
  16431. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16432. auto se = detail::scope_exit([&] {
  16433. svr.stop();
  16434. t.join();
  16435. ASSERT_FALSE(svr.is_running());
  16436. });
  16437. svr.wait_until_ready();
  16438. SSLClient cli("127.0.0.1", PORT);
  16439. std::string cert;
  16440. // A trusted CA that did not sign the server certificate. The server cert
  16441. // (cert2) carries the matching IP SAN, so only chain validation can reject
  16442. // this connection.
  16443. read_file(CLIENT_CA_CERT_FILE, cert);
  16444. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16445. cli.enable_server_certificate_verification(true);
  16446. cli.set_connection_timeout(30);
  16447. auto res = cli.Get("/test");
  16448. ASSERT_FALSE(res);
  16449. }
  16450. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  16451. // A custom CA that brings no certificate still keeps the system CAs out, so a
  16452. // CA that failed to come through fails verification instead of trusting them.
  16453. // (wolfSSL does not list the system CAs it loaded.)
  16454. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  16455. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16456. ASSERT_TRUE(svr.is_valid());
  16457. auto port = svr.bind_to_any_port("127.0.0.1");
  16458. ASSERT_LT(0, port);
  16459. thread t = thread([&] { svr.listen_after_bind(); });
  16460. auto se = detail::scope_exit([&] {
  16461. svr.stop();
  16462. t.join();
  16463. ASSERT_FALSE(svr.is_running());
  16464. });
  16465. svr.wait_until_ready();
  16466. // The CAs a client trusts once its first request has loaded them
  16467. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  16468. Client cli("https://127.0.0.1:" + std::to_string(port));
  16469. setup(cli);
  16470. cli.Get("/");
  16471. return tls::get_ca_names(cli.tls_context()).size();
  16472. };
  16473. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  16474. EXPECT_EQ(0u,
  16475. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  16476. }
  16477. #endif
  16478. // A TLS setting changed between requests applies to the next one, not just to
  16479. // the next connection
  16480. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  16481. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16482. ASSERT_TRUE(svr.is_valid());
  16483. svr.Get("/", [](const Request &req, Response &res) {
  16484. res.set_content(std::to_string(req.remote_port), "text/plain");
  16485. });
  16486. auto port = svr.bind_to_any_port("127.0.0.1");
  16487. ASSERT_LT(0, port);
  16488. thread t = thread([&] { svr.listen_after_bind(); });
  16489. auto se = detail::scope_exit([&] {
  16490. svr.stop();
  16491. t.join();
  16492. ASSERT_FALSE(svr.is_running());
  16493. });
  16494. svr.wait_until_ready();
  16495. SSLClient cli("127.0.0.1", port);
  16496. cli.set_keep_alive(true);
  16497. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  16498. cli.enable_server_certificate_verification(false);
  16499. // The port the request went out from, so a new one means a new connection
  16500. auto client_port = [&] {
  16501. auto res = cli.Get("/");
  16502. return res ? res->body : std::string();
  16503. };
  16504. auto last = client_port();
  16505. ASSERT_FALSE(last.empty());
  16506. // Setting a value it already has keeps the connection
  16507. cli.enable_server_certificate_verification(false);
  16508. cli.enable_server_hostname_verification(true);
  16509. EXPECT_EQ(last, client_port());
  16510. cli.enable_server_certificate_verification(true);
  16511. auto res = cli.Get("/");
  16512. EXPECT_FALSE(res);
  16513. EXPECT_EQ(Error::SSLServerVerification, res.error());
  16514. std::string ca;
  16515. read_file(SERVER_CERT2_FILE, ca);
  16516. cli.load_ca_cert_store(ca.c_str(), ca.size());
  16517. last = client_port();
  16518. ASSERT_FALSE(last.empty());
  16519. std::vector<std::function<void()>> setters = {
  16520. [&] { cli.enable_server_hostname_verification(false); },
  16521. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  16522. [&] {
  16523. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  16524. },
  16525. [&] {
  16526. cli.set_server_certificate_verifier(
  16527. [](const tls::VerifyContext &) { return true; });
  16528. },
  16529. [&] {
  16530. cli.set_session_verifier(
  16531. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  16532. },
  16533. };
  16534. for (const auto &setter : setters) {
  16535. setter();
  16536. auto next = client_port();
  16537. ASSERT_FALSE(next.empty());
  16538. EXPECT_NE(last, next);
  16539. last = next;
  16540. }
  16541. cli.set_session_verifier(
  16542. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  16543. auto handle = cli.open_stream("GET", "/");
  16544. EXPECT_FALSE(handle.is_valid());
  16545. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  16546. }
  16547. // A PEM given to create_ca_store() needs no NUL after it
  16548. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  16549. std::string pem;
  16550. read_file(SERVER_CERT2_FILE, pem);
  16551. auto buf = pem + "X";
  16552. auto store = tls::create_ca_store(buf.data(), pem.size());
  16553. EXPECT_TRUE(store != nullptr);
  16554. SSLClient cli("localhost");
  16555. cli.set_ca_cert_store(store);
  16556. }
  16557. // enable_system_ca(false) prevents system CA loading entirely
  16558. TEST(SSLClientTest, DisableSystemCa_Online) {
  16559. SSLClient cli("google.com");
  16560. cli.enable_system_ca(false);
  16561. cli.enable_server_certificate_verification(true);
  16562. auto res = cli.Get("/");
  16563. ASSERT_FALSE(res);
  16564. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  16565. // itself when the CA chain is empty
  16566. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  16567. res.error() == Error::SSLConnection);
  16568. }
  16569. // The universal Client forwards enable_system_ca()
  16570. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  16571. std::string cert;
  16572. read_file(SERVER_CERT2_FILE, cert);
  16573. Client cli("https://google.com");
  16574. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16575. cli.enable_system_ca(true);
  16576. cli.enable_server_certificate_verification(true);
  16577. auto res = cli.Get("/");
  16578. // Any status: Google may redirect or rate-limit CI runners.
  16579. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16580. }
  16581. // The system CA policy must carry over to the client created internally for
  16582. // following a cross-host HTTPS redirect
  16583. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  16584. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  16585. ASSERT_TRUE(svr.is_valid());
  16586. svr.Get("/index", [&](const Request &, Response &res) {
  16587. res.set_redirect("https://www.google.com/");
  16588. });
  16589. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  16590. auto se = detail::scope_exit([&] {
  16591. svr.stop();
  16592. t.join();
  16593. ASSERT_FALSE(svr.is_running());
  16594. });
  16595. svr.wait_until_ready();
  16596. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  16597. std::string cert;
  16598. read_file(SERVER_CERT2_FILE, cert);
  16599. cli.load_ca_cert_store(cert.c_str(), cert.size());
  16600. cli.enable_system_ca(true);
  16601. cli.enable_server_certificate_verification(true);
  16602. cli.set_follow_location(true);
  16603. cli.set_connection_timeout(30);
  16604. // Receiving any response proves the redirect client completed the TLS
  16605. // handshake with a system-CA-signed host
  16606. auto res = cli.Get("/index");
  16607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16608. }
  16609. TEST(MultipartFormDataTest, LargeData) {
  16610. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16611. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  16612. const ContentReader &content_reader) {
  16613. if (req.is_multipart_form_data()) {
  16614. std::vector<FormData> items;
  16615. content_reader(
  16616. [&](const FormData &file) {
  16617. items.push_back(file);
  16618. return true;
  16619. },
  16620. [&](const char *data, size_t data_length) {
  16621. items.back().content.append(data, data_length);
  16622. return true;
  16623. });
  16624. EXPECT_TRUE(std::string(items[0].name) == "document");
  16625. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16626. EXPECT_TRUE(items[0].filename == "2MB_data");
  16627. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16628. EXPECT_TRUE(items[1].name == "hello");
  16629. EXPECT_TRUE(items[1].content == "world");
  16630. EXPECT_TRUE(items[1].filename == "");
  16631. EXPECT_TRUE(items[1].content_type == "");
  16632. } else {
  16633. std::string body;
  16634. content_reader([&](const char *data, size_t data_length) {
  16635. body.append(data, data_length);
  16636. return true;
  16637. });
  16638. }
  16639. });
  16640. auto port = svr.bind_to_any_port(HOST);
  16641. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16642. auto se = detail::scope_exit([&] {
  16643. svr.stop();
  16644. t.join();
  16645. ASSERT_FALSE(svr.is_running());
  16646. });
  16647. svr.wait_until_ready();
  16648. {
  16649. std::string data(1024 * 1024 * 2, '.');
  16650. std::stringstream buffer;
  16651. buffer << data;
  16652. SSLClient cli(HOST, port);
  16653. cli.enable_server_certificate_verification(false);
  16654. UploadFormDataItems items{
  16655. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16656. {"hello", "world", "", ""},
  16657. };
  16658. auto res = cli.Post("/post", items);
  16659. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16660. ASSERT_EQ(StatusCode::OK_200, res->status);
  16661. }
  16662. }
  16663. TEST(MultipartFormDataTest, DataProviderItems) {
  16664. std::random_device seed_gen;
  16665. std::mt19937 random(seed_gen());
  16666. std::string rand1;
  16667. rand1.resize(1000);
  16668. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  16669. std::string rand2;
  16670. rand2.resize(3000);
  16671. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  16672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16673. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  16674. const ContentReader &content_reader) {
  16675. ASSERT_FALSE(req.is_multipart_form_data());
  16676. std::string body;
  16677. content_reader([&](const char *data, size_t data_length) {
  16678. body.append(data, data_length);
  16679. return true;
  16680. });
  16681. EXPECT_EQ(body, "");
  16682. });
  16683. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  16684. const ContentReader &content_reader) {
  16685. ASSERT_TRUE(req.is_multipart_form_data());
  16686. std::vector<FormData> items;
  16687. content_reader(
  16688. [&](const FormData &file) {
  16689. items.push_back(file);
  16690. return true;
  16691. },
  16692. [&](const char *data, size_t data_length) {
  16693. items.back().content.append(data, data_length);
  16694. return true;
  16695. });
  16696. ASSERT_TRUE(items.size() == 2);
  16697. EXPECT_EQ(std::string(items[0].name), "name1");
  16698. EXPECT_EQ(items[0].content, "Testing123");
  16699. EXPECT_EQ(items[0].filename, "filename1");
  16700. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16701. EXPECT_EQ(items[1].name, "name2");
  16702. EXPECT_EQ(items[1].content, "Testing456");
  16703. EXPECT_EQ(items[1].filename, "");
  16704. EXPECT_EQ(items[1].content_type, "");
  16705. });
  16706. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  16707. const ContentReader &content_reader) {
  16708. ASSERT_TRUE(req.is_multipart_form_data());
  16709. std::vector<FormData> items;
  16710. content_reader(
  16711. [&](const FormData &file) {
  16712. items.push_back(file);
  16713. return true;
  16714. },
  16715. [&](const char *data, size_t data_length) {
  16716. items.back().content.append(data, data_length);
  16717. return true;
  16718. });
  16719. ASSERT_TRUE(items.size() == 2);
  16720. EXPECT_EQ(items[0].name, "name3");
  16721. EXPECT_EQ(items[0].content, rand1);
  16722. EXPECT_EQ(items[0].filename, "filename3");
  16723. EXPECT_EQ(items[0].content_type, "");
  16724. EXPECT_EQ(items[1].name, "name4");
  16725. EXPECT_EQ(items[1].content, rand2);
  16726. EXPECT_EQ(items[1].filename, "filename4");
  16727. EXPECT_EQ(items[1].content_type, "");
  16728. });
  16729. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  16730. const ContentReader &content_reader) {
  16731. ASSERT_TRUE(req.is_multipart_form_data());
  16732. std::vector<FormData> items;
  16733. content_reader(
  16734. [&](const FormData &file) {
  16735. items.push_back(file);
  16736. return true;
  16737. },
  16738. [&](const char *data, size_t data_length) {
  16739. items.back().content.append(data, data_length);
  16740. return true;
  16741. });
  16742. ASSERT_TRUE(items.size() == 4);
  16743. EXPECT_EQ(std::string(items[0].name), "name1");
  16744. EXPECT_EQ(items[0].content, "Testing123");
  16745. EXPECT_EQ(items[0].filename, "filename1");
  16746. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  16747. EXPECT_EQ(items[1].name, "name2");
  16748. EXPECT_EQ(items[1].content, "Testing456");
  16749. EXPECT_EQ(items[1].filename, "");
  16750. EXPECT_EQ(items[1].content_type, "");
  16751. EXPECT_EQ(items[2].name, "name3");
  16752. EXPECT_EQ(items[2].content, rand1);
  16753. EXPECT_EQ(items[2].filename, "filename3");
  16754. EXPECT_EQ(items[2].content_type, "");
  16755. EXPECT_EQ(items[3].name, "name4");
  16756. EXPECT_EQ(items[3].content, rand2);
  16757. EXPECT_EQ(items[3].filename, "filename4");
  16758. EXPECT_EQ(items[3].content_type, "");
  16759. });
  16760. auto port = svr.bind_to_any_port("localhost");
  16761. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16762. auto se = detail::scope_exit([&] {
  16763. svr.stop();
  16764. t.join();
  16765. ASSERT_FALSE(svr.is_running());
  16766. });
  16767. svr.wait_until_ready();
  16768. {
  16769. SSLClient cli("localhost", port);
  16770. cli.enable_server_certificate_verification(false);
  16771. UploadFormDataItems items{
  16772. {"name1", "Testing123", "filename1", "application/octet-stream"},
  16773. {"name2", "Testing456", "", ""}, // not a file
  16774. };
  16775. {
  16776. auto res = cli.Post("/post-none", {}, {}, {});
  16777. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16778. ASSERT_EQ(StatusCode::OK_200, res->status);
  16779. }
  16780. FormDataProviderItems providers;
  16781. {
  16782. auto res =
  16783. cli.Post("/post-items", {}, items, providers); // empty providers
  16784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16785. ASSERT_EQ(StatusCode::OK_200, res->status);
  16786. }
  16787. providers.push_back({"name3",
  16788. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16789. // test the offset is given correctly at each step
  16790. if (!offset)
  16791. sink.os.write(rand1.data(), 30);
  16792. else if (offset == 30)
  16793. sink.os.write(rand1.data() + 30, 300);
  16794. else if (offset == 330)
  16795. sink.os.write(rand1.data() + 330, 670);
  16796. else if (offset == rand1.size())
  16797. sink.done();
  16798. return true;
  16799. },
  16800. "filename3",
  16801. {}});
  16802. providers.push_back({"name4",
  16803. [&](size_t offset, httplib::DataSink &sink) -> bool {
  16804. // test the offset is given correctly at each step
  16805. if (!offset)
  16806. sink.os.write(rand2.data(), 2000);
  16807. else if (offset == 2000)
  16808. sink.os.write(rand2.data() + 2000, 1);
  16809. else if (offset == 2001)
  16810. sink.os.write(rand2.data() + 2001, 999);
  16811. else if (offset == rand2.size())
  16812. sink.done();
  16813. return true;
  16814. },
  16815. "filename4",
  16816. {}});
  16817. {
  16818. auto res = cli.Post("/post-providers", {}, {}, providers);
  16819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16820. ASSERT_EQ(StatusCode::OK_200, res->status);
  16821. }
  16822. {
  16823. auto res = cli.Post("/post-both", {}, items, providers);
  16824. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16825. ASSERT_EQ(StatusCode::OK_200, res->status);
  16826. }
  16827. }
  16828. }
  16829. TEST(MultipartFormDataTest, BadHeader) {
  16830. Server svr;
  16831. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16832. res.set_content("ok", "text/plain");
  16833. });
  16834. thread t = thread([&] { svr.listen(HOST, PORT); });
  16835. auto se = detail::scope_exit([&] {
  16836. svr.stop();
  16837. t.join();
  16838. ASSERT_FALSE(svr.is_running());
  16839. });
  16840. svr.wait_until_ready();
  16841. const std::string body =
  16842. "This is the preamble. It is to be ignored, though it\r\n"
  16843. "is a handy place for composition agents to include an\r\n"
  16844. "explanatory note to non-MIME conformant readers.\r\n"
  16845. "\r\n"
  16846. "\r\n"
  16847. "--simple boundary\r\n"
  16848. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16849. ": BAD...\r\n"
  16850. "\r\n"
  16851. "value1\r\n"
  16852. "--simple boundary\r\n"
  16853. "Content-Disposition: form-data; name=\"field2\"; "
  16854. "filename=\"example.txt\"\r\n"
  16855. "\r\n"
  16856. "value2\r\n"
  16857. "--simple boundary--\r\n"
  16858. "This is the epilogue. It is also to be ignored.\r\n";
  16859. std::string content_type =
  16860. R"(multipart/form-data; boundary="simple boundary")";
  16861. Client cli(HOST, PORT);
  16862. auto res = cli.Post("/post", body, content_type.c_str());
  16863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16864. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16865. }
  16866. TEST(MultipartFormDataTest, WithPreamble) {
  16867. Server svr;
  16868. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16869. res.set_content("ok", "text/plain");
  16870. });
  16871. thread t = thread([&] { svr.listen(HOST, PORT); });
  16872. auto se = detail::scope_exit([&] {
  16873. svr.stop();
  16874. t.join();
  16875. ASSERT_FALSE(svr.is_running());
  16876. });
  16877. svr.wait_until_ready();
  16878. const std::string body =
  16879. "This is the preamble. It is to be ignored, though it\r\n"
  16880. "is a handy place for composition agents to include an\r\n"
  16881. "explanatory note to non-MIME conformant readers.\r\n"
  16882. "\r\n"
  16883. "\r\n"
  16884. "--simple boundary\r\n"
  16885. "Content-Disposition: form-data; name=\"field1\"\r\n"
  16886. "\r\n"
  16887. "value1\r\n"
  16888. "--simple boundary\r\n"
  16889. "Content-Disposition: form-data; name=\"field2\"; "
  16890. "filename=\"example.txt\"\r\n"
  16891. "\r\n"
  16892. "value2\r\n"
  16893. "--simple boundary--\r\n"
  16894. "This is the epilogue. It is also to be ignored.\r\n";
  16895. std::string content_type =
  16896. R"(multipart/form-data; boundary="simple boundary")";
  16897. Client cli(HOST, PORT);
  16898. auto res = cli.Post("/post", body, content_type.c_str());
  16899. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16900. EXPECT_EQ(StatusCode::OK_200, res->status);
  16901. }
  16902. TEST(MultipartFormDataTest, PostCustomBoundary) {
  16903. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16904. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  16905. const ContentReader &content_reader) {
  16906. if (req.is_multipart_form_data()) {
  16907. std::vector<FormData> items;
  16908. content_reader(
  16909. [&](const FormData &file) {
  16910. items.push_back(file);
  16911. return true;
  16912. },
  16913. [&](const char *data, size_t data_length) {
  16914. items.back().content.append(data, data_length);
  16915. return true;
  16916. });
  16917. EXPECT_TRUE(std::string(items[0].name) == "document");
  16918. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16919. EXPECT_TRUE(items[0].filename == "2MB_data");
  16920. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16921. EXPECT_TRUE(items[1].name == "hello");
  16922. EXPECT_TRUE(items[1].content == "world");
  16923. EXPECT_TRUE(items[1].filename == "");
  16924. EXPECT_TRUE(items[1].content_type == "");
  16925. } else {
  16926. std::string body;
  16927. content_reader([&](const char *data, size_t data_length) {
  16928. body.append(data, data_length);
  16929. return true;
  16930. });
  16931. }
  16932. });
  16933. auto port = svr.bind_to_any_port("localhost");
  16934. auto t = std::thread([&]() { svr.listen_after_bind(); });
  16935. auto se = detail::scope_exit([&] {
  16936. svr.stop();
  16937. t.join();
  16938. ASSERT_FALSE(svr.is_running());
  16939. });
  16940. svr.wait_until_ready();
  16941. {
  16942. std::string data(1024 * 1024 * 2, '.');
  16943. std::stringstream buffer;
  16944. buffer << data;
  16945. SSLClient cli("localhost", port);
  16946. cli.enable_server_certificate_verification(false);
  16947. UploadFormDataItems items{
  16948. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16949. {"hello", "world", "", ""},
  16950. };
  16951. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  16952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16953. ASSERT_EQ(StatusCode::OK_200, res->status);
  16954. }
  16955. }
  16956. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  16957. std::string data(1024 * 1024 * 2, '&');
  16958. std::stringstream buffer;
  16959. buffer << data;
  16960. Client cli("https://localhost:8080");
  16961. UploadFormDataItems items{
  16962. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  16963. {"hello", "world", "", ""},
  16964. };
  16965. for (const char &c : " \t\r\n") {
  16966. auto res =
  16967. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  16968. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  16969. ASSERT_FALSE(res);
  16970. }
  16971. }
  16972. TEST(MultipartFormDataTest, PutFormData) {
  16973. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  16974. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  16975. const ContentReader &content_reader) {
  16976. if (req.is_multipart_form_data()) {
  16977. std::vector<FormData> items;
  16978. content_reader(
  16979. [&](const FormData &file) {
  16980. items.push_back(file);
  16981. return true;
  16982. },
  16983. [&](const char *data, size_t data_length) {
  16984. items.back().content.append(data, data_length);
  16985. return true;
  16986. });
  16987. EXPECT_TRUE(std::string(items[0].name) == "document");
  16988. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  16989. EXPECT_TRUE(items[0].filename == "2MB_data");
  16990. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  16991. EXPECT_TRUE(items[1].name == "hello");
  16992. EXPECT_TRUE(items[1].content == "world");
  16993. EXPECT_TRUE(items[1].filename == "");
  16994. EXPECT_TRUE(items[1].content_type == "");
  16995. } else {
  16996. std::string body;
  16997. content_reader([&](const char *data, size_t data_length) {
  16998. body.append(data, data_length);
  16999. return true;
  17000. });
  17001. }
  17002. });
  17003. auto port = svr.bind_to_any_port("localhost");
  17004. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17005. auto se = detail::scope_exit([&] {
  17006. svr.stop();
  17007. t.join();
  17008. ASSERT_FALSE(svr.is_running());
  17009. });
  17010. svr.wait_until_ready();
  17011. {
  17012. std::string data(1024 * 1024 * 2, '&');
  17013. std::stringstream buffer;
  17014. buffer << data;
  17015. SSLClient cli("localhost", port);
  17016. cli.enable_server_certificate_verification(false);
  17017. UploadFormDataItems items{
  17018. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17019. {"hello", "world", "", ""},
  17020. };
  17021. auto res = cli.Put("/put", items);
  17022. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17023. ASSERT_EQ(StatusCode::OK_200, res->status);
  17024. }
  17025. }
  17026. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  17027. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17028. svr.Put("/put_customboundary",
  17029. [&](const Request &req, const Response & /*res*/,
  17030. const ContentReader &content_reader) {
  17031. if (req.is_multipart_form_data()) {
  17032. std::vector<FormData> items;
  17033. content_reader(
  17034. [&](const FormData &file) {
  17035. items.push_back(file);
  17036. return true;
  17037. },
  17038. [&](const char *data, size_t data_length) {
  17039. items.back().content.append(data, data_length);
  17040. return true;
  17041. });
  17042. EXPECT_TRUE(std::string(items[0].name) == "document");
  17043. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  17044. EXPECT_TRUE(items[0].filename == "2MB_data");
  17045. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  17046. EXPECT_TRUE(items[1].name == "hello");
  17047. EXPECT_TRUE(items[1].content == "world");
  17048. EXPECT_TRUE(items[1].filename == "");
  17049. EXPECT_TRUE(items[1].content_type == "");
  17050. } else {
  17051. std::string body;
  17052. content_reader([&](const char *data, size_t data_length) {
  17053. body.append(data, data_length);
  17054. return true;
  17055. });
  17056. }
  17057. });
  17058. auto port = svr.bind_to_any_port("localhost");
  17059. auto t = std::thread([&]() { svr.listen_after_bind(); });
  17060. auto se = detail::scope_exit([&] {
  17061. svr.stop();
  17062. t.join();
  17063. ASSERT_FALSE(svr.is_running());
  17064. });
  17065. svr.wait_until_ready();
  17066. {
  17067. std::string data(1024 * 1024 * 2, '&');
  17068. std::stringstream buffer;
  17069. buffer << data;
  17070. SSLClient cli("localhost", port);
  17071. cli.enable_server_certificate_verification(false);
  17072. UploadFormDataItems items{
  17073. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17074. {"hello", "world", "", ""},
  17075. };
  17076. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  17077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17078. ASSERT_EQ(StatusCode::OK_200, res->status);
  17079. }
  17080. }
  17081. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  17082. std::string data(1024 * 1024 * 2, '&');
  17083. std::stringstream buffer;
  17084. buffer << data;
  17085. Client cli("https://localhost:8080");
  17086. cli.enable_server_certificate_verification(false);
  17087. UploadFormDataItems items{
  17088. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  17089. {"hello", "world", "", ""},
  17090. };
  17091. for (const char &c : " \t\r\n") {
  17092. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  17093. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  17094. ASSERT_FALSE(res);
  17095. }
  17096. }
  17097. TEST(MultipartFormDataTest, AlternateFilename) {
  17098. auto handled = false;
  17099. Server svr;
  17100. svr.Post("/test", [&](const Request &req, Response &res) {
  17101. ASSERT_EQ(2u, req.form.files.size());
  17102. ASSERT_EQ(1u, req.form.fields.size());
  17103. // Test files
  17104. const auto &file1 = req.form.get_file("file1");
  17105. ASSERT_EQ("file1", file1.name);
  17106. ASSERT_EQ("A.txt", file1.filename);
  17107. ASSERT_EQ("text/plain", file1.content_type);
  17108. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  17109. const auto &file2 = req.form.get_file("file2");
  17110. ASSERT_EQ("file2", file2.name);
  17111. ASSERT_EQ("a.html", file2.filename);
  17112. ASSERT_EQ("text/html", file2.content_type);
  17113. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  17114. file2.content);
  17115. // Test text field
  17116. const auto &text = req.form.get_field("text");
  17117. ASSERT_EQ("text default", text);
  17118. res.set_content("ok", "text/plain");
  17119. handled = true;
  17120. });
  17121. thread t = thread([&] { svr.listen(HOST, PORT); });
  17122. auto se = detail::scope_exit([&] {
  17123. svr.stop();
  17124. t.join();
  17125. ASSERT_FALSE(svr.is_running());
  17126. ASSERT_TRUE(handled);
  17127. });
  17128. svr.wait_until_ready();
  17129. auto req = "POST /test HTTP/1.1\r\n"
  17130. "Host: localhost\r\n"
  17131. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17132. "Content-Length: 399\r\n"
  17133. "\r\n"
  17134. "----------\r\n"
  17135. "Content-Disposition: form-data; name=\"text\"\r\n"
  17136. "\r\n"
  17137. "text default\r\n"
  17138. "----------\r\n"
  17139. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  17140. "filename=\"a.txt\"; name=\"file1\"\r\n"
  17141. "Content-Type: text/plain\r\n"
  17142. "\r\n"
  17143. "Content of a.txt.\r\n"
  17144. "\r\n"
  17145. "----------\r\n"
  17146. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  17147. "\"a.html\"\r\n"
  17148. "Content-Type: text/html\r\n"
  17149. "\r\n"
  17150. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  17151. "\r\n"
  17152. "------------\r\n";
  17153. ASSERT_TRUE(send_request(1, req));
  17154. }
  17155. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  17156. auto handled = false;
  17157. Server svr;
  17158. svr.Post("/test", [&](const Request &req, Response &res) {
  17159. // Case-insensitive "utf-8''" prefix with a long value
  17160. const auto &file = req.form.get_file("file1");
  17161. ASSERT_EQ("file1", file.name);
  17162. // 8000 chars exercises both the Content-Disposition parser and the
  17163. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  17164. // Prior to the fix, std::regex_match on this header would cause O(N)
  17165. // stack recursion in libstdc++, leading to SIGSEGV.
  17166. std::string expected_filename(8000, 'A');
  17167. ASSERT_EQ(expected_filename, file.filename);
  17168. res.set_content("ok", "text/plain");
  17169. handled = true;
  17170. });
  17171. thread t = thread([&] { svr.listen(HOST, PORT); });
  17172. auto se = detail::scope_exit([&] {
  17173. svr.stop();
  17174. t.join();
  17175. ASSERT_FALSE(svr.is_running());
  17176. ASSERT_TRUE(handled);
  17177. });
  17178. svr.wait_until_ready();
  17179. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  17180. // Regression test for GHSA-qq6v-r583-3h69
  17181. std::string long_filename(8000, 'A');
  17182. std::string body = "----------\r\n"
  17183. "Content-Disposition: form-data; name=\"file1\"; "
  17184. "filename*=\"Utf-8''" +
  17185. long_filename +
  17186. "\"\r\n"
  17187. "\r\n"
  17188. "hello\r\n"
  17189. "------------\r\n";
  17190. auto req = "POST /test HTTP/1.1\r\n"
  17191. "Host: localhost\r\n"
  17192. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17193. "Content-Length: " +
  17194. std::to_string(body.size()) + "\r\n\r\n" + body;
  17195. ASSERT_TRUE(send_request(1, req));
  17196. }
  17197. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  17198. auto handled = false;
  17199. Server svr;
  17200. svr.Post("/test", [&](const Request &req, Response &) {
  17201. ASSERT_EQ(2u, req.form.fields.size());
  17202. const auto &text1 = req.form.get_field("text1");
  17203. ASSERT_EQ("text1", text1);
  17204. const auto &text2 = req.form.get_field("text2");
  17205. ASSERT_EQ("text2", text2);
  17206. handled = true;
  17207. });
  17208. thread t = thread([&] { svr.listen(HOST, PORT); });
  17209. auto se = detail::scope_exit([&] {
  17210. svr.stop();
  17211. t.join();
  17212. ASSERT_FALSE(svr.is_running());
  17213. ASSERT_TRUE(handled);
  17214. });
  17215. svr.wait_until_ready();
  17216. auto req = "POST /test HTTP/1.1\r\n"
  17217. "Host: localhost\r\n"
  17218. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17219. "Content-Length: 146\r\n"
  17220. "\r\n----------\r\n"
  17221. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17222. "\r\n"
  17223. "text1"
  17224. "\r\n----------\r\n"
  17225. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17226. "\r\n"
  17227. "text2"
  17228. "\r\n------------";
  17229. std::string response;
  17230. ASSERT_TRUE(send_request(1, req, &response));
  17231. ASSERT_EQ("200", response.substr(9, 3));
  17232. }
  17233. TEST(MultipartFormDataTest, ContentLength) {
  17234. auto handled = false;
  17235. Server svr;
  17236. svr.Post("/test", [&](const Request &req, Response &) {
  17237. ASSERT_EQ(2u, req.form.fields.size());
  17238. const auto &text1 = req.form.get_field("text1");
  17239. ASSERT_EQ("text1", text1);
  17240. const auto &text2 = req.form.get_field("text2");
  17241. ASSERT_EQ("text2", text2);
  17242. handled = true;
  17243. });
  17244. thread t = thread([&] { svr.listen(HOST, PORT); });
  17245. auto se = detail::scope_exit([&] {
  17246. svr.stop();
  17247. t.join();
  17248. ASSERT_FALSE(svr.is_running());
  17249. ASSERT_TRUE(handled);
  17250. });
  17251. svr.wait_until_ready();
  17252. auto req = "POST /test HTTP/1.1\r\n"
  17253. "Host: localhost\r\n"
  17254. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17255. "Content-Length: 167\r\n"
  17256. "\r\n----------\r\n"
  17257. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17258. "Content-Length: 5\r\n"
  17259. "\r\n"
  17260. "text1"
  17261. "\r\n----------\r\n"
  17262. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17263. "\r\n"
  17264. "text2"
  17265. "\r\n------------\r\n";
  17266. std::string response;
  17267. ASSERT_TRUE(send_request(1, req, &response));
  17268. ASSERT_EQ("200", response.substr(9, 3));
  17269. }
  17270. TEST(MultipartFormDataTest, AccessPartHeaders) {
  17271. auto handled = false;
  17272. Server svr;
  17273. svr.Post("/test", [&](const Request &req, Response &) {
  17274. ASSERT_EQ(2u, req.form.fields.size());
  17275. const auto &text1 = req.form.get_field("text1");
  17276. ASSERT_EQ("text1", text1);
  17277. // TODO: Add header access for text fields if needed
  17278. const auto &text2 = req.form.get_field("text2");
  17279. ASSERT_EQ("text2", text2);
  17280. // TODO: Header access for text fields needs to be implemented
  17281. // auto &headers = it->second.headers;
  17282. // ASSERT_EQ(3U, headers.size());
  17283. // auto custom_header = headers.find("x-whatever");
  17284. // ASSERT_TRUE(custom_header != headers.end());
  17285. // ASSERT_NE("customvalue", custom_header->second);
  17286. // ASSERT_EQ("CustomValue", custom_header->second);
  17287. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  17288. handled = true;
  17289. });
  17290. thread t = thread([&] { svr.listen(HOST, PORT); });
  17291. auto se = detail::scope_exit([&] {
  17292. svr.stop();
  17293. t.join();
  17294. ASSERT_FALSE(svr.is_running());
  17295. ASSERT_TRUE(handled);
  17296. });
  17297. svr.wait_until_ready();
  17298. auto req = "POST /test HTTP/1.1\r\n"
  17299. "Host: localhost\r\n"
  17300. "Content-Type: multipart/form-data;boundary=--------\r\n"
  17301. "Content-Length: 232\r\n"
  17302. "\r\n----------\r\n"
  17303. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17304. "Content-Length: 5\r\n"
  17305. "X-Test: 1\r\n"
  17306. "\r\n"
  17307. "text1"
  17308. "\r\n----------\r\n"
  17309. "Content-Disposition: form-data; name=\"text2\"\r\n"
  17310. "Content-Type: text/plain\r\n"
  17311. "X-Whatever: CustomValue\r\n"
  17312. "\r\n"
  17313. "text2"
  17314. "\r\n------------\r\n"
  17315. "That should be disregarded. Not even read";
  17316. std::string response;
  17317. ASSERT_TRUE(send_request(1, req, &response));
  17318. ASSERT_EQ("200", response.substr(9, 3));
  17319. }
  17320. TEST(MultipartFormDataTest, LargeHeader) {
  17321. auto handled = false;
  17322. Server svr;
  17323. svr.Post("/test", [&](const Request &req, Response &) {
  17324. ASSERT_EQ(1u, req.form.fields.size());
  17325. const auto &text = req.form.get_field("name1");
  17326. ASSERT_EQ("text1", text);
  17327. handled = true;
  17328. });
  17329. thread t = thread([&] { svr.listen(HOST, PORT); });
  17330. auto se = detail::scope_exit([&] {
  17331. svr.stop();
  17332. t.join();
  17333. ASSERT_FALSE(svr.is_running());
  17334. ASSERT_TRUE(handled);
  17335. });
  17336. svr.wait_until_ready();
  17337. auto boundary = std::string("cpp-httplib-multipart-data");
  17338. std::string content = "--" + boundary +
  17339. "\r\n"
  17340. "Content-Disposition: form-data; name=\"name1\"\r\n"
  17341. "\r\n"
  17342. "text1\r\n"
  17343. "--" +
  17344. boundary + "--\r\n";
  17345. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  17346. "Host: localhost\r\n"
  17347. "Content-Type: multipart/form-data;boundary=" +
  17348. boundary +
  17349. "\r\n"
  17350. "Content-Length: " +
  17351. std::to_string(content.size()) +
  17352. "\r\n"
  17353. "Dummy-Header: ";
  17354. std::string header_suffix = "\r\n"
  17355. "\r\n";
  17356. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  17357. size_t header_dummy_size =
  17358. read_buff_size -
  17359. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  17360. auto header_dummy = std::string(header_dummy_size, '@');
  17361. auto req = header_prefix + header_dummy + header_suffix + content;
  17362. std::string response;
  17363. ASSERT_TRUE(send_request(1, req, &response));
  17364. ASSERT_EQ("200", response.substr(9, 3));
  17365. }
  17366. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  17367. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  17368. // (not chunked Transfer-Encoding) after the streaming refactor.
  17369. auto handled = false;
  17370. Server svr;
  17371. svr.Post("/upload", [&](const Request &req, Response &res) {
  17372. auto cl_it = req.headers.find("Content-Length");
  17373. EXPECT_TRUE(cl_it != req.headers.end());
  17374. auto te_it = req.headers.find("Transfer-Encoding");
  17375. EXPECT_TRUE(te_it == req.headers.end());
  17376. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  17377. res.set_content("ok", "text/plain");
  17378. handled = true;
  17379. });
  17380. auto port = svr.bind_to_any_port(HOST);
  17381. auto t = thread([&] { svr.listen_after_bind(); });
  17382. auto se = detail::scope_exit([&] {
  17383. svr.stop();
  17384. t.join();
  17385. ASSERT_FALSE(svr.is_running());
  17386. ASSERT_TRUE(handled);
  17387. });
  17388. svr.wait_until_ready();
  17389. UploadFormDataItems items = {
  17390. {"field1", "hello", "", "text/plain"},
  17391. {"file1", "world", "test.txt", "application/octet-stream"},
  17392. };
  17393. Client cli(HOST, port);
  17394. auto res = cli.Post("/upload", {}, items);
  17395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17396. EXPECT_EQ(StatusCode::OK_200, res->status);
  17397. }
  17398. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  17399. // Verify that make_multipart_content_provider coalesces many small segments
  17400. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  17401. constexpr size_t kItemCount = 1000;
  17402. UploadFormDataItems items;
  17403. items.reserve(kItemCount);
  17404. for (size_t i = 0; i < kItemCount; i++) {
  17405. items.push_back(
  17406. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17407. }
  17408. const std::string boundary = "----test-boundary";
  17409. auto content_length = detail::get_multipart_content_length(items, boundary);
  17410. auto provider = detail::make_multipart_content_provider(items, boundary);
  17411. // Drive the provider the same way write_content_with_progress does
  17412. size_t write_count = 0;
  17413. size_t total_bytes = 0;
  17414. DataSink sink;
  17415. size_t offset = 0;
  17416. sink.write = [&](const char *d, size_t l) -> bool {
  17417. (void)d;
  17418. write_count++;
  17419. total_bytes += l;
  17420. offset += l;
  17421. return true;
  17422. };
  17423. sink.is_writable = []() -> bool { return true; };
  17424. while (offset < content_length) {
  17425. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  17426. }
  17427. EXPECT_EQ(content_length, total_bytes);
  17428. // The total number of segments is 3 * kItemCount + 1 = 3001.
  17429. // With buffering into 64KB blocks, write_count should be much smaller.
  17430. auto segment_count = 3 * kItemCount + 1;
  17431. EXPECT_LT(write_count, segment_count / 10);
  17432. }
  17433. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  17434. // Integration test: send many UploadFormDataItems and verify the server
  17435. // receives all of them correctly (#2410).
  17436. constexpr size_t kItemCount = 500;
  17437. auto handled = false;
  17438. Server svr;
  17439. svr.Post("/upload", [&](const Request &req, Response &res) {
  17440. EXPECT_EQ(kItemCount, req.form.fields.size());
  17441. for (size_t i = 0; i < kItemCount; i++) {
  17442. auto key = "field" + std::to_string(i);
  17443. auto val = "value" + std::to_string(i);
  17444. auto it = req.form.fields.find(key);
  17445. if (it != req.form.fields.end()) {
  17446. EXPECT_EQ(val, it->second.content);
  17447. } else {
  17448. ADD_FAILURE() << "Missing field: " << key;
  17449. }
  17450. }
  17451. res.set_content("ok", "text/plain");
  17452. handled = true;
  17453. });
  17454. auto port = svr.bind_to_any_port(HOST);
  17455. auto t = thread([&] { svr.listen_after_bind(); });
  17456. auto se = detail::scope_exit([&] {
  17457. svr.stop();
  17458. t.join();
  17459. ASSERT_FALSE(svr.is_running());
  17460. ASSERT_TRUE(handled);
  17461. });
  17462. svr.wait_until_ready();
  17463. UploadFormDataItems items;
  17464. items.reserve(kItemCount);
  17465. for (size_t i = 0; i < kItemCount; i++) {
  17466. items.push_back(
  17467. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  17468. }
  17469. Client cli(HOST, port);
  17470. auto res = cli.Post("/upload", items);
  17471. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17472. EXPECT_EQ(StatusCode::OK_200, res->status);
  17473. }
  17474. TEST(MultipartFormDataTest, MakeFileProvider) {
  17475. // Verify make_file_provider sends a file's contents correctly.
  17476. const std::string file_content(4096, 'Z');
  17477. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  17478. {
  17479. std::ofstream ofs(tmp_path, std::ios::binary);
  17480. ofs.write(file_content.data(),
  17481. static_cast<std::streamsize>(file_content.size()));
  17482. }
  17483. auto handled = false;
  17484. Server svr;
  17485. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  17486. const ContentReader &content_reader) {
  17487. ASSERT_TRUE(req.is_multipart_form_data());
  17488. std::vector<FormData> items;
  17489. content_reader(
  17490. [&](const FormData &file) {
  17491. items.push_back(file);
  17492. return true;
  17493. },
  17494. [&](const char *data, size_t data_length) {
  17495. items.back().content.append(data, data_length);
  17496. return true;
  17497. });
  17498. ASSERT_EQ(1u, items.size());
  17499. EXPECT_EQ("myfile", items[0].name);
  17500. EXPECT_EQ("data.bin", items[0].filename);
  17501. EXPECT_EQ("application/octet-stream", items[0].content_type);
  17502. EXPECT_EQ(file_content, items[0].content);
  17503. handled = true;
  17504. });
  17505. auto port = svr.bind_to_any_port(HOST);
  17506. auto t = thread([&] { svr.listen_after_bind(); });
  17507. auto se = detail::scope_exit([&] {
  17508. svr.stop();
  17509. t.join();
  17510. ASSERT_FALSE(svr.is_running());
  17511. ASSERT_TRUE(handled);
  17512. std::remove(tmp_path.c_str());
  17513. });
  17514. svr.wait_until_ready();
  17515. FormDataProviderItems providers;
  17516. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  17517. "application/octet-stream"));
  17518. Client cli(HOST, port);
  17519. auto res = cli.Post("/upload", {}, {}, providers);
  17520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17521. EXPECT_EQ(StatusCode::OK_200, res->status);
  17522. }
  17523. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  17524. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  17525. // (100) headers is rejected with a 400 Bad Request response.
  17526. Server svr;
  17527. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  17528. res.set_content("ok", "text/plain");
  17529. });
  17530. thread t = thread([&] { svr.listen(HOST, PORT); });
  17531. auto se = detail::scope_exit([&] {
  17532. svr.stop();
  17533. t.join();
  17534. ASSERT_FALSE(svr.is_running());
  17535. });
  17536. svr.wait_until_ready();
  17537. // Build a multipart part with 101 custom headers (exceeding
  17538. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  17539. std::stringstream body;
  17540. body << "--simpleboundary\r\n"
  17541. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  17542. for (int i = 0; i < 101; i++) {
  17543. body << "X-Custom-Header-" << i << ": value\r\n";
  17544. }
  17545. body << "\r\n"
  17546. << "value1\r\n"
  17547. << "--simpleboundary--\r\n";
  17548. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  17549. Client cli(HOST, PORT);
  17550. auto res = cli.Post("/post", body.str(), content_type.c_str());
  17551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17552. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17553. }
  17554. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  17555. // A body that never contains the declared boundary must not be accumulated
  17556. // while the parser waits for it. Buffering it would also make every read
  17557. // rescan everything seen so far, which is quadratic in the body size.
  17558. Server svr;
  17559. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17560. res.set_content("ok", "text/plain");
  17561. });
  17562. auto port = svr.bind_to_any_port(HOST);
  17563. thread t = thread([&] { svr.listen_after_bind(); });
  17564. auto se = detail::scope_exit([&] {
  17565. svr.stop();
  17566. t.join();
  17567. ASSERT_FALSE(svr.is_running());
  17568. });
  17569. svr.wait_until_ready();
  17570. Client cli(HOST, port);
  17571. cli.set_read_timeout(60, 0);
  17572. cli.set_write_timeout(60, 0);
  17573. // '-' is the worst case: it matches the first character of the boundary, so
  17574. // every position has to be checked against it.
  17575. auto post_dashes = [&](size_t size) {
  17576. const std::string body(size, '-');
  17577. auto start = std::chrono::steady_clock::now();
  17578. auto res =
  17579. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  17580. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  17581. std::chrono::steady_clock::now() - start)
  17582. .count();
  17583. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  17584. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  17585. return ms;
  17586. };
  17587. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  17588. // Windows.
  17589. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  17590. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  17591. // Comparing the two sizes rather than checking an absolute duration keeps
  17592. // this meaningful across build types and CI load, both of which move the
  17593. // absolute numbers by more than an order of magnitude. Four times the bytes
  17594. // costs about four times the time when parsing is linear, and about sixteen
  17595. // times when the body is buffered and rescanned.
  17596. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  17597. EXPECT_LT(ms_16mb, ms_4mb * 10)
  17598. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  17599. << "ms, which suggests the body is being buffered and rescanned";
  17600. }
  17601. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  17602. // A boundary can only be followed by CRLF or by "--", so anything else is
  17603. // malformed no matter what comes next. The parser must say so right away
  17604. // instead of buffering the rest of the declared body.
  17605. Server svr;
  17606. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  17607. res.set_content("ok", "text/plain");
  17608. });
  17609. auto port = svr.bind_to_any_port(HOST);
  17610. thread t = thread([&] { svr.listen_after_bind(); });
  17611. auto se = detail::scope_exit([&] {
  17612. svr.stop();
  17613. t.join();
  17614. ASSERT_FALSE(svr.is_running());
  17615. });
  17616. svr.wait_until_ready();
  17617. // Announce a 1 MB body but send only the malformed prefix. A parser that
  17618. // buffers instead of failing would still be waiting for the remaining bytes.
  17619. const std::string body = "--zzzz\r\n"
  17620. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17621. "\r\n"
  17622. "text1"
  17623. "\r\n--zzzzXX";
  17624. const std::string req = "POST /post HTTP/1.1\r\n"
  17625. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17626. "Content-Length: 1048576\r\n"
  17627. "\r\n" +
  17628. body;
  17629. std::string response;
  17630. ASSERT_TRUE(send_request(3, req, &response, port));
  17631. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  17632. EXPECT_EQ("400", response.substr(9, 3));
  17633. }
  17634. // Posts a multipart body split into two writes, so that the server sees the
  17635. // split at whatever offset the caller chose, and expects the single "text1"
  17636. // field to come through.
  17637. static void expect_split_multipart_ok(const std::string &body1,
  17638. const std::string &body2) {
  17639. auto handled = false;
  17640. Server svr;
  17641. svr.Post("/post", [&](const Request &req, Response &) {
  17642. EXPECT_EQ(1u, req.form.fields.size());
  17643. EXPECT_EQ("text1", req.form.get_field("text1"));
  17644. handled = true;
  17645. });
  17646. auto port = svr.bind_to_any_port(HOST);
  17647. thread t = thread([&] { svr.listen_after_bind(); });
  17648. auto se = detail::scope_exit([&] {
  17649. svr.stop();
  17650. t.join();
  17651. ASSERT_FALSE(svr.is_running());
  17652. ASSERT_TRUE(handled);
  17653. });
  17654. svr.wait_until_ready();
  17655. // "Connection: close" makes the server close once it has answered, so the
  17656. // response drain ends immediately instead of idling until the read timeout.
  17657. const std::string head =
  17658. "POST /post HTTP/1.1\r\n"
  17659. "Host: localhost\r\n"
  17660. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  17661. "Connection: close\r\n"
  17662. "Content-Length: " +
  17663. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  17664. std::string response;
  17665. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  17666. ASSERT_GE(response.size(), 12u) << "no response";
  17667. EXPECT_EQ("200", response.substr(9, 3));
  17668. }
  17669. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  17670. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  17671. // ignored, including when it does not arrive in the same read as the
  17672. // close-delimiter itself.
  17673. expect_split_multipart_ok("--zzzz\r\n"
  17674. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17675. "\r\n"
  17676. "text1"
  17677. "\r\n--zzzz--",
  17678. "\r\nthis epilogue must be ignored\r\n");
  17679. }
  17680. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  17681. // The initial boundary may be preceded by a preamble of any length and may
  17682. // straddle a read boundary. Discarding data while waiting for it must not
  17683. // throw away a partial boundary sitting at the end of the buffer.
  17684. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  17685. "zz\r\n"
  17686. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17687. "\r\n"
  17688. "text1"
  17689. "\r\n--zzzz--\r\n");
  17690. }
  17691. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  17692. // The received boundary was only checked for being non-empty, so it could be
  17693. // as long as a header is allowed to be. The parser scans the body for
  17694. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  17695. // costs a nearly full comparison at nearly every position, making the
  17696. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  17697. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  17698. Server svr;
  17699. svr.Post("/post", [](const Request &req, Response &res) {
  17700. EXPECT_EQ(1u, req.form.fields.size());
  17701. EXPECT_EQ("text1", req.form.get_field("text1"));
  17702. res.set_content("ok", "text/plain");
  17703. });
  17704. auto port = svr.bind_to_any_port(HOST);
  17705. thread t = thread([&] { svr.listen_after_bind(); });
  17706. auto se = detail::scope_exit([&] {
  17707. svr.stop();
  17708. t.join();
  17709. ASSERT_FALSE(svr.is_running());
  17710. });
  17711. svr.wait_until_ready();
  17712. Client cli(HOST, port);
  17713. auto post_with_boundary_of_length = [&](size_t len) {
  17714. const std::string boundary(len, 'a');
  17715. const std::string body =
  17716. "--" + boundary +
  17717. "\r\n"
  17718. "Content-Disposition: form-data; name=\"text1\"\r\n"
  17719. "\r\n"
  17720. "text1"
  17721. "\r\n--" +
  17722. boundary + "--\r\n";
  17723. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  17724. };
  17725. auto res = post_with_boundary_of_length(70);
  17726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17727. EXPECT_EQ(StatusCode::OK_200, res->status);
  17728. res = post_with_boundary_of_length(71);
  17729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17730. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  17731. }
  17732. TEST(MakeFileBodyTest, Basic) {
  17733. const std::string file_content(4096, 'Z');
  17734. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  17735. {
  17736. std::ofstream ofs(tmp_path, std::ios::binary);
  17737. ofs.write(file_content.data(),
  17738. static_cast<std::streamsize>(file_content.size()));
  17739. }
  17740. auto handled = false;
  17741. Server svr;
  17742. svr.Post("/upload", [&](const Request &req, Response &res) {
  17743. EXPECT_EQ(file_content, req.body);
  17744. handled = true;
  17745. res.status = StatusCode::OK_200;
  17746. });
  17747. auto port = svr.bind_to_any_port(HOST);
  17748. auto t = thread([&] { svr.listen_after_bind(); });
  17749. auto se = detail::scope_exit([&] {
  17750. svr.stop();
  17751. t.join();
  17752. ASSERT_FALSE(svr.is_running());
  17753. ASSERT_TRUE(handled);
  17754. std::remove(tmp_path.c_str());
  17755. });
  17756. svr.wait_until_ready();
  17757. auto fb = make_file_body(tmp_path);
  17758. ASSERT_GT(fb.first, 0u);
  17759. Client cli(HOST, port);
  17760. auto res =
  17761. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  17762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17763. EXPECT_EQ(StatusCode::OK_200, res->status);
  17764. }
  17765. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  17766. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  17767. {
  17768. std::ofstream ofs(path, std::ios::binary);
  17769. const std::string content(100, 'A');
  17770. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17771. }
  17772. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17773. auto body = make_file_body(path);
  17774. ASSERT_EQ(100u, body.first);
  17775. ASSERT_TRUE(static_cast<bool>(body.second));
  17776. // Rewritten shorter after its length was measured - and, on a server, after
  17777. // that length has already gone out as Content-Length.
  17778. {
  17779. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  17780. const std::string content(10, 'A');
  17781. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17782. }
  17783. std::string written;
  17784. DataSink sink;
  17785. sink.write = [&](const char *d, size_t l) {
  17786. written.append(d, l);
  17787. return true;
  17788. };
  17789. // The provider has to report failure. write_content_with_progress() advances
  17790. // its offset only by what was written, so a provider that returns true
  17791. // without completing the length it promised is called again straight away,
  17792. // and again.
  17793. EXPECT_FALSE(body.second(0, body.first, sink));
  17794. EXPECT_EQ(std::string(10, 'A'), written);
  17795. }
  17796. TEST(MakeFileBodyTest, WholeFileIsSent) {
  17797. const std::string path = "./httplib_test_make_file_body_whole.bin";
  17798. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  17799. {
  17800. std::ofstream ofs(path, std::ios::binary);
  17801. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  17802. }
  17803. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  17804. auto body = make_file_body(path);
  17805. ASSERT_EQ(content.size(), body.first);
  17806. ASSERT_TRUE(static_cast<bool>(body.second));
  17807. std::string written;
  17808. DataSink sink;
  17809. sink.write = [&](const char *d, size_t l) {
  17810. written.append(d, l);
  17811. return true;
  17812. };
  17813. EXPECT_TRUE(body.second(0, body.first, sink));
  17814. EXPECT_EQ(content, written);
  17815. }
  17816. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  17817. static constexpr unsigned int number_of_tasks{1000000};
  17818. std::atomic_uint count{0};
  17819. std::unique_ptr<TaskQueue> task_queue{
  17820. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  17821. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17822. auto queued = task_queue->enqueue(
  17823. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  17824. EXPECT_TRUE(queued);
  17825. }
  17826. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17827. task_queue->shutdown();
  17828. #else
  17829. EXPECT_NO_THROW(task_queue->shutdown());
  17830. #endif
  17831. EXPECT_EQ(number_of_tasks, count.load());
  17832. }
  17833. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  17834. static constexpr unsigned int number_of_tasks{1000000};
  17835. static constexpr unsigned int qlimit{2};
  17836. unsigned int queued_count{0};
  17837. std::atomic_uint count{0};
  17838. std::unique_ptr<TaskQueue> task_queue{
  17839. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  17840. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  17841. if (task_queue->enqueue(
  17842. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  17843. queued_count++;
  17844. }
  17845. }
  17846. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17847. task_queue->shutdown();
  17848. #else
  17849. EXPECT_NO_THROW(task_queue->shutdown());
  17850. #endif
  17851. EXPECT_EQ(queued_count, count.load());
  17852. EXPECT_TRUE(queued_count <= number_of_tasks);
  17853. EXPECT_TRUE(queued_count >= qlimit);
  17854. }
  17855. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  17856. // Use a short idle timeout so a dynamic thread spawns, times out and
  17857. // exits during the test, and the pool keeps working afterwards.
  17858. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  17859. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  17860. /*idle_timeout_sec=*/1}};
  17861. std::atomic_uint count{0};
  17862. std::condition_variable cv;
  17863. std::mutex mtx;
  17864. bool release = false;
  17865. // Block the base thread so the second task spawns a dynamic thread.
  17866. EXPECT_TRUE(task_queue->enqueue([&] {
  17867. std::unique_lock<std::mutex> lock(mtx);
  17868. while (!release) {
  17869. cv.wait(lock);
  17870. }
  17871. count++;
  17872. }));
  17873. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17874. // Let the dynamic thread finish its task and exceed the idle timeout.
  17875. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  17876. {
  17877. std::unique_lock<std::mutex> lock(mtx);
  17878. release = true;
  17879. }
  17880. cv.notify_all();
  17881. // The pool must still accept and run tasks after the dynamic thread exited.
  17882. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  17883. task_queue->shutdown();
  17884. EXPECT_EQ(3u, count.load());
  17885. }
  17886. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  17887. static constexpr size_t number_of_tasks{32};
  17888. std::unique_ptr<TaskQueue> task_queue{
  17889. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  17890. // Let the base threads go idle so the burst below finds them waiting.
  17891. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17892. std::mutex mtx;
  17893. std::condition_variable cv;
  17894. size_t running = 0;
  17895. bool release = false;
  17896. for (size_t i = 0; i < number_of_tasks; i++) {
  17897. EXPECT_TRUE(task_queue->enqueue([&] {
  17898. std::unique_lock<std::mutex> lock(mtx);
  17899. running++;
  17900. cv.notify_all();
  17901. cv.wait(lock, [&] { return release; });
  17902. }));
  17903. }
  17904. {
  17905. std::unique_lock<std::mutex> lock(mtx);
  17906. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  17907. [&] { return running == number_of_tasks; }));
  17908. release = true;
  17909. }
  17910. cv.notify_all();
  17911. task_queue->shutdown();
  17912. }
  17913. TEST(TaskQueueTest, MaxQueuedRequests) {
  17914. static constexpr unsigned int qlimit{3};
  17915. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  17916. std::condition_variable sem_cv;
  17917. std::mutex sem_mtx;
  17918. int credits = 0;
  17919. bool queued;
  17920. /* Fill up the queue with tasks that will block until we give them credits to
  17921. * complete. */
  17922. for (unsigned int n = 0; n <= qlimit;) {
  17923. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  17924. std::unique_lock<std::mutex> lock(sem_mtx);
  17925. while (credits <= 0) {
  17926. sem_cv.wait(lock);
  17927. }
  17928. /* Consume the credit and signal the test code if they are all gone. */
  17929. if (--credits == 0) { sem_cv.notify_one(); }
  17930. });
  17931. if (n < qlimit) {
  17932. /* The first qlimit enqueues must succeed. */
  17933. EXPECT_TRUE(queued);
  17934. } else {
  17935. /* The last one will succeed only when the worker thread
  17936. * starts and dequeues the first blocking task. Although
  17937. * not necessary for the correctness of this test, we sleep for
  17938. * a short while to avoid busy waiting. */
  17939. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17940. }
  17941. if (queued) { n++; }
  17942. }
  17943. /* Further enqueues must fail since the queue is full. */
  17944. for (auto i = 0; i < 4; i++) {
  17945. queued = task_queue->enqueue([] {});
  17946. EXPECT_FALSE(queued);
  17947. }
  17948. /* Give the credits to allow the previous tasks to complete. */
  17949. {
  17950. std::unique_lock<std::mutex> lock(sem_mtx);
  17951. credits += qlimit + 1;
  17952. }
  17953. sem_cv.notify_all();
  17954. /* Wait for all the credits to be consumed. */
  17955. {
  17956. std::unique_lock<std::mutex> lock(sem_mtx);
  17957. while (credits > 0) {
  17958. sem_cv.wait(lock);
  17959. }
  17960. }
  17961. /* Check that we are able again to enqueue at least qlimit tasks. */
  17962. for (unsigned int i = 0; i < qlimit; i++) {
  17963. queued = task_queue->enqueue([] {});
  17964. EXPECT_TRUE(queued);
  17965. }
  17966. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  17967. task_queue->shutdown();
  17968. #else
  17969. EXPECT_NO_THROW(task_queue->shutdown());
  17970. #endif
  17971. }
  17972. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  17973. Server svr;
  17974. std::string method;
  17975. std::string body;
  17976. auto has_content_length = false;
  17977. auto has_transfer_encoding = false;
  17978. std::atomic<int> bad_requests{0};
  17979. // Leftover body bytes get parsed as a malformed request and answered with
  17980. // 400
  17981. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  17982. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  17983. });
  17984. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  17985. res.set_redirect("/down", StatusCode::SeeOther_303);
  17986. });
  17987. svr.Get("/down", [&](const Request &req, Response &res) {
  17988. method = req.method;
  17989. body = req.body;
  17990. has_content_length = req.has_header("Content-Length");
  17991. has_transfer_encoding = req.has_header("Transfer-Encoding");
  17992. res.set_content("ok", "text/plain");
  17993. });
  17994. auto port = svr.bind_to_any_port(HOST);
  17995. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17996. auto se = detail::scope_exit([&] {
  17997. svr.stop();
  17998. thread.join();
  17999. ASSERT_FALSE(svr.is_running());
  18000. });
  18001. svr.wait_until_ready();
  18002. const std::string payload = "SECRET-BODY";
  18003. auto check = [&](Client &cli, const Result &res) {
  18004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18005. EXPECT_EQ(StatusCode::OK_200, res->status);
  18006. EXPECT_EQ("ok", res->body);
  18007. EXPECT_EQ("GET", method);
  18008. EXPECT_TRUE(body.empty());
  18009. EXPECT_FALSE(has_content_length);
  18010. EXPECT_FALSE(has_transfer_encoding);
  18011. // Nothing of the original body may be left on the connection
  18012. auto res2 = cli.Get("/down");
  18013. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18014. EXPECT_EQ(StatusCode::OK_200, res2->status);
  18015. EXPECT_EQ("ok", res2->body);
  18016. EXPECT_EQ(0, bad_requests);
  18017. };
  18018. // With content length
  18019. {
  18020. Client cli(HOST, port);
  18021. cli.set_keep_alive(true);
  18022. cli.set_follow_location(true);
  18023. auto res = cli.Post(
  18024. "/up", payload.size(),
  18025. [&](size_t offset, size_t length, DataSink &sink) {
  18026. return sink.write(payload.data() + offset, length);
  18027. },
  18028. "text/plain");
  18029. check(cli, res);
  18030. }
  18031. // Without content length (chunked)
  18032. {
  18033. Client cli(HOST, port);
  18034. cli.set_keep_alive(true);
  18035. cli.set_follow_location(true);
  18036. auto res = cli.Post(
  18037. "/up",
  18038. [&](size_t /*offset*/, DataSink &sink) {
  18039. sink.write(payload.data(), payload.size());
  18040. sink.done();
  18041. return true;
  18042. },
  18043. "text/plain");
  18044. check(cli, res);
  18045. }
  18046. }
  18047. TEST(RedirectTest, LocationPathIsNotDecoded) {
  18048. Server svr;
  18049. std::string target;
  18050. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  18051. // Echo the still-encoded name back in the Location
  18052. const std::string prefix = "/start/";
  18053. res.status = StatusCode::Found_302;
  18054. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  18055. });
  18056. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  18057. target = req.target;
  18058. res.set_content("ok", "text/plain");
  18059. });
  18060. auto port = svr.bind_to_any_port(HOST);
  18061. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18062. auto se = detail::scope_exit([&] {
  18063. svr.stop();
  18064. thread.join();
  18065. ASSERT_FALSE(svr.is_running());
  18066. });
  18067. svr.wait_until_ready();
  18068. // Decoding the Location path would turn the first four into a path
  18069. // separator, a query delimiter, a fragment delimiter and a different
  18070. // percent-encoded octet. The rest must keep reaching the server as they are.
  18071. const std::vector<std::string> names = {
  18072. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  18073. };
  18074. for (auto path_encode : {true, false}) {
  18075. Client cli(HOST, port);
  18076. cli.set_follow_location(true);
  18077. cli.set_path_encode(path_encode);
  18078. for (const auto &name : names) {
  18079. target.clear();
  18080. auto res = cli.Get("/start/" + name);
  18081. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18082. EXPECT_EQ(StatusCode::OK_200, res->status);
  18083. EXPECT_EQ("/dest/" + name, target);
  18084. }
  18085. }
  18086. }
  18087. TEST(RedirectTest, NotModifiedIsReturned) {
  18088. Server svr;
  18089. svr.Get("/cached", [](const Request &, Response &res) {
  18090. res.status = StatusCode::NotModified_304;
  18091. });
  18092. auto port = svr.bind_to_any_port(HOST);
  18093. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18094. auto se = detail::scope_exit([&] {
  18095. svr.stop();
  18096. thread.join();
  18097. ASSERT_FALSE(svr.is_running());
  18098. });
  18099. svr.wait_until_ready();
  18100. Client cli(HOST, port);
  18101. cli.set_follow_location(true);
  18102. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  18103. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18104. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  18105. }
  18106. TEST(RedirectTest, NoLocationIsReturned) {
  18107. Server svr;
  18108. svr.Get("/no-location", [](const Request &, Response &res) {
  18109. res.status = StatusCode::Found_302;
  18110. res.set_content("no location", "text/plain");
  18111. });
  18112. auto port = svr.bind_to_any_port(HOST);
  18113. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18114. auto se = detail::scope_exit([&] {
  18115. svr.stop();
  18116. thread.join();
  18117. ASSERT_FALSE(svr.is_running());
  18118. });
  18119. svr.wait_until_ready();
  18120. Client cli(HOST, port);
  18121. cli.set_follow_location(true);
  18122. auto res = cli.Get("/no-location");
  18123. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18124. EXPECT_EQ(StatusCode::Found_302, res->status);
  18125. EXPECT_EQ("no location", res->body);
  18126. // The callbacks see the body of the response that is returned
  18127. auto handler_called = false;
  18128. auto progress_called = false;
  18129. std::string body;
  18130. auto res2 = cli.Get(
  18131. "/no-location",
  18132. [&](const Response &) {
  18133. handler_called = true;
  18134. return true;
  18135. },
  18136. [&](const char *data, size_t data_length) {
  18137. body.append(data, data_length);
  18138. return true;
  18139. },
  18140. [&](size_t, size_t) {
  18141. progress_called = true;
  18142. return true;
  18143. });
  18144. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  18145. EXPECT_EQ(StatusCode::Found_302, res2->status);
  18146. EXPECT_TRUE(handler_called);
  18147. EXPECT_TRUE(progress_called);
  18148. EXPECT_EQ("no location", body);
  18149. }
  18150. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  18151. Server svr;
  18152. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18153. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  18154. });
  18155. svr.Get("/hello", [](const Request &req, Response &res) {
  18156. res.set_content(req.get_param_value("key"), "text/plain");
  18157. });
  18158. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18159. auto se = detail::scope_exit([&] {
  18160. svr.stop();
  18161. thread.join();
  18162. ASSERT_FALSE(svr.is_running());
  18163. });
  18164. svr.wait_until_ready();
  18165. {
  18166. Client cli(HOST, PORT);
  18167. cli.set_follow_location(true);
  18168. auto res = cli.Get("/");
  18169. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18170. EXPECT_EQ(StatusCode::OK_200, res->status);
  18171. EXPECT_EQ("val&key2=val2", res->body);
  18172. }
  18173. }
  18174. #endif
  18175. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  18176. Server svr;
  18177. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18178. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  18179. });
  18180. svr.Get("/hello", [](const Request &req, Response &res) {
  18181. res.set_content(req.get_param_value("key"), "text/plain");
  18182. });
  18183. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18184. auto se = detail::scope_exit([&] {
  18185. svr.stop();
  18186. thread.join();
  18187. ASSERT_FALSE(svr.is_running());
  18188. });
  18189. svr.wait_until_ready();
  18190. {
  18191. Client cli(HOST, PORT);
  18192. cli.set_follow_location(true);
  18193. auto res = cli.Get("/");
  18194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18195. EXPECT_EQ(StatusCode::OK_200, res->status);
  18196. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  18197. }
  18198. }
  18199. TEST(RedirectTest, RedirectWithPlusInPath) {
  18200. Server svr;
  18201. svr.Get("/", [](const Request & /*req*/, Response &res) {
  18202. res.set_redirect("/a+b");
  18203. });
  18204. // Route pattern uses regex; escape + as \\+
  18205. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  18206. res.set_content(req.path, "text/plain");
  18207. });
  18208. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18209. auto se = detail::scope_exit([&] {
  18210. svr.stop();
  18211. thread.join();
  18212. ASSERT_FALSE(svr.is_running());
  18213. });
  18214. svr.wait_until_ready();
  18215. {
  18216. Client cli(HOST, PORT);
  18217. cli.set_follow_location(true);
  18218. auto res = cli.Get("/");
  18219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18220. EXPECT_EQ(StatusCode::OK_200, res->status);
  18221. EXPECT_EQ("/a+b", res->body);
  18222. }
  18223. }
  18224. TEST(RedirectTest, ResolveRelativeLocation) {
  18225. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  18226. const std::vector<std::pair<std::string, std::string>> cases = {
  18227. {"g", "/b/c/g"},
  18228. {"./g", "/b/c/g"},
  18229. {"g/", "/b/c/g/"},
  18230. {"?y", "/b/c/d;p?y"},
  18231. {"g?y", "/b/c/g?y"},
  18232. {"#s", "/b/c/d;p?q#s"},
  18233. {"g#s", "/b/c/g#s"},
  18234. {"g?y#s", "/b/c/g?y#s"},
  18235. {";x", "/b/c/;x"},
  18236. {"g;x", "/b/c/g;x"},
  18237. {".", "/b/c/"},
  18238. {"./", "/b/c/"},
  18239. {"..", "/b/"},
  18240. {"../", "/b/"},
  18241. {"../g", "/b/g"},
  18242. {"../..", "/"},
  18243. {"../../", "/"},
  18244. {"../../g", "/g"},
  18245. {"../../../g", "/g"},
  18246. {"g.", "/b/c/g."},
  18247. {".g", "/b/c/.g"},
  18248. {"g..", "/b/c/g.."},
  18249. {"..g", "/b/c/..g"},
  18250. {"./../g", "/b/g"},
  18251. {"./g/.", "/b/c/g/"},
  18252. {"g/./h", "/b/c/g/h"},
  18253. {"g/../h", "/b/c/h"},
  18254. {"g;x=1/./y", "/b/c/g;x=1/y"},
  18255. {"g;x=1/../y", "/b/c/y"},
  18256. {"g?y/./x", "/b/c/g?y/./x"},
  18257. {"g#s/../x", "/b/c/g#s/../x"},
  18258. // Not relative-path references, so left for parse_url.
  18259. {"/g", "/g"},
  18260. {"//g", "//g"},
  18261. {"http://g/x", "http://g/x"},
  18262. {"g:h", "g:h"},
  18263. };
  18264. for (const auto &c : cases) {
  18265. EXPECT_EQ(c.second,
  18266. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  18267. << c.first;
  18268. }
  18269. // A result starting with "//" is still a path, not a network-path reference
  18270. EXPECT_EQ("/.//g",
  18271. detail::resolve_relative_location("../../..//g", "/b/c/d;p?q"));
  18272. EXPECT_EQ("/.//g/x", detail::resolve_relative_location("x", "//g/h"));
  18273. EXPECT_EQ("/.//g/h?y", detail::resolve_relative_location("?y", "//g/h"));
  18274. EXPECT_EQ("/.//g/h#s", detail::resolve_relative_location("#s", "//g/h"));
  18275. }
  18276. TEST(RedirectTest, RemoveDotSegments) {
  18277. // RFC 3986 section 5.2.4
  18278. EXPECT_EQ("/a/g", detail::remove_dot_segments("/a/b/c/./../../g"));
  18279. EXPECT_EQ("/mid/6", detail::remove_dot_segments("/mid/content=5/../6"));
  18280. EXPECT_EQ("/g", detail::remove_dot_segments("/./g"));
  18281. EXPECT_EQ("/g", detail::remove_dot_segments("/../g"));
  18282. EXPECT_EQ("/", detail::remove_dot_segments("/.."));
  18283. EXPECT_EQ("/a/", detail::remove_dot_segments("/a/b/.."));
  18284. EXPECT_EQ("/a/b", detail::remove_dot_segments("/a/b"));
  18285. }
  18286. TEST(RedirectTest, AbsoluteLocationIsNormalized) {
  18287. Server svr;
  18288. svr.Get("/absolute-path", [](const Request & /*req*/, Response &res) {
  18289. res.set_redirect("/dir/../target?x=1");
  18290. });
  18291. svr.Get("/absolute-uri", [](const Request & /*req*/, Response &res) {
  18292. res.set_redirect("http://localhost:" + std::to_string(PORT) +
  18293. "/dir/./../target");
  18294. });
  18295. svr.Get("/target", [](const Request &req, Response &res) {
  18296. res.set_content(req.path, "text/plain");
  18297. });
  18298. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  18299. auto se = detail::scope_exit([&] {
  18300. svr.stop();
  18301. th.join();
  18302. ASSERT_FALSE(svr.is_running());
  18303. });
  18304. svr.wait_until_ready();
  18305. Client cli("localhost", PORT);
  18306. cli.set_follow_location(true);
  18307. for (auto path : {"/absolute-path", "/absolute-uri"}) {
  18308. auto res = cli.Get(path);
  18309. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  18310. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  18311. EXPECT_EQ("/target", res->body) << path;
  18312. }
  18313. }
  18314. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  18315. Server svr;
  18316. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18317. res.set_redirect(req.get_param_value("to"));
  18318. });
  18319. svr.Get("/dir/next", [](const Request &req, Response &res) {
  18320. res.set_content(req.target, "text/plain");
  18321. });
  18322. svr.Get("/other", [](const Request &req, Response &res) {
  18323. res.set_content(req.target, "text/plain");
  18324. });
  18325. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18326. auto se = detail::scope_exit([&] {
  18327. svr.stop();
  18328. thread.join();
  18329. ASSERT_FALSE(svr.is_running());
  18330. });
  18331. svr.wait_until_ready();
  18332. const std::vector<std::pair<std::string, std::string>> cases = {
  18333. {"next", "/dir/next"},
  18334. {"./next?x=1", "/dir/next?x=1"},
  18335. {"next?source=https://example.com/catalog",
  18336. "/dir/next?source=https://example.com/catalog"},
  18337. {"../other", "/other"},
  18338. };
  18339. for (const auto &c : cases) {
  18340. Client cli(HOST, PORT);
  18341. cli.set_follow_location(true);
  18342. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  18343. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  18344. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  18345. EXPECT_EQ(c.second, res->body) << c.first;
  18346. }
  18347. }
  18348. // "..//host:port/x" resolves to the path "//host:port/x" on the same host
  18349. // (RFC 3986 5.2), as curl and the URL Standard have it, not to another host.
  18350. TEST(RedirectTest, RelativeLocationStaysOnHost) {
  18351. Server other;
  18352. std::atomic<int> other_hits{0};
  18353. other.Get(".*", [&](const Request & /*req*/, Response &res) {
  18354. other_hits++;
  18355. res.set_content("other", "text/plain");
  18356. });
  18357. auto other_port = other.bind_to_any_port("127.0.0.1");
  18358. auto other_thread = std::thread([&]() { other.listen_after_bind(); });
  18359. Server svr;
  18360. svr.Get("/dir/page", [](const Request &req, Response &res) {
  18361. res.set_redirect(req.get_param_value("to"));
  18362. });
  18363. svr.Get(".*", [](const Request &req, Response &res) {
  18364. res.set_content(req.path, "text/plain");
  18365. });
  18366. auto port = svr.bind_to_any_port(HOST);
  18367. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18368. auto se = detail::scope_exit([&] {
  18369. svr.stop();
  18370. thread.join();
  18371. other.stop();
  18372. other_thread.join();
  18373. ASSERT_FALSE(svr.is_running());
  18374. ASSERT_FALSE(other.is_running());
  18375. });
  18376. svr.wait_until_ready();
  18377. other.wait_until_ready();
  18378. auto authority = "127.0.0.1:" + std::to_string(other_port);
  18379. for (const auto &to :
  18380. {"..//" + authority + "/x", "../..//" + authority + "/x"}) {
  18381. Client cli(HOST, port);
  18382. cli.set_follow_location(true);
  18383. auto res = cli.Get("/dir/page?to=" + encode_query_component(to));
  18384. ASSERT_TRUE(res) << to << ": " << to_string(res.error());
  18385. EXPECT_EQ(StatusCode::OK_200, res->status) << to;
  18386. EXPECT_EQ("//" + authority + "/x", res->body) << to;
  18387. }
  18388. EXPECT_EQ(0, other_hits.load());
  18389. }
  18390. #ifdef CPPHTTPLIB_SSL_ENABLED
  18391. TEST(RedirectTest, Issue2185_Online) {
  18392. SSLClient client("github.com");
  18393. client.set_follow_location(true);
  18394. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  18395. "Coollab-Windows.zip");
  18396. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18397. EXPECT_EQ(StatusCode::OK_200, res->status);
  18398. EXPECT_EQ(9920427U, res->body.size());
  18399. }
  18400. #endif
  18401. TEST(VulnerabilityTest, CRLFInjection) {
  18402. Server svr;
  18403. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  18404. res.set_content("Hello 1", "text/plain");
  18405. });
  18406. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  18407. res.set_content("Hello 2", "text/plain");
  18408. });
  18409. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  18410. res.set_content("Hello 3", "text/plain");
  18411. });
  18412. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  18413. res.set_content("Hello 4", "text/plain");
  18414. });
  18415. svr.set_logger([](const Request &req, const Response & /*res*/) {
  18416. for (const auto &x : req.headers) {
  18417. auto key = x.first;
  18418. EXPECT_STRNE("evil", key.c_str());
  18419. }
  18420. });
  18421. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  18422. auto se = detail::scope_exit([&] {
  18423. svr.stop();
  18424. thread.join();
  18425. ASSERT_FALSE(svr.is_running());
  18426. });
  18427. svr.wait_until_ready();
  18428. {
  18429. Client cli(HOST, PORT);
  18430. cli.Post("/test1", "A=B",
  18431. "application/x-www-form-urlencoded\r\nevil: hello1");
  18432. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  18433. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  18434. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  18435. }
  18436. }
  18437. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  18438. auto server_thread = std::thread([] {
  18439. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18440. default_socket_options(srv);
  18441. sockaddr_in addr{};
  18442. addr.sin_family = AF_INET;
  18443. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18444. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18445. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  18446. ::listen(srv, 1);
  18447. sockaddr_in cli_addr{};
  18448. socklen_t cli_len = sizeof(cli_addr);
  18449. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18450. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  18451. std::string buf_all;
  18452. char buf[2048];
  18453. ssize_t n;
  18454. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  18455. buf_all.append(buf, static_cast<size_t>(n));
  18456. size_t pos;
  18457. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  18458. auto request_block = buf_all.substr(0, pos + 4); // include separator
  18459. auto e = request_block.find("\r\n");
  18460. if (e != std::string::npos) {
  18461. auto request_line = request_block.substr(0, e);
  18462. std::string msg =
  18463. "CRLF injection detected in request line: '" + request_line + "'";
  18464. EXPECT_FALSE(true) << msg;
  18465. }
  18466. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  18467. ::send(cli,
  18468. #ifdef _WIN32
  18469. static_cast<const char *>(resp.c_str()),
  18470. static_cast<int>(resp.size()),
  18471. #else
  18472. resp.c_str(), resp.size(),
  18473. #endif
  18474. 0);
  18475. buf_all.erase(0, pos + 4);
  18476. }
  18477. }
  18478. detail::close_socket(cli);
  18479. detail::close_socket(srv);
  18480. });
  18481. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18482. auto cli = Client("127.0.0.1", PORT + 1);
  18483. auto headers = Headers{
  18484. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  18485. {"Connection", "keep-alive"}};
  18486. auto res = cli.Get("/hi", headers);
  18487. EXPECT_FALSE(res);
  18488. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18489. server_thread.join();
  18490. }
  18491. // A request rejected before any byte reaches the socket must fail right away
  18492. // instead of waiting for a response the server will never send.
  18493. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  18494. // The kernel completes the TCP handshake from the listen backlog, so the
  18495. // client connects, but nothing ever reads, responds or closes.
  18496. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18497. default_socket_options(srv);
  18498. sockaddr_in addr{};
  18499. addr.sin_family = AF_INET;
  18500. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18501. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18502. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18503. ASSERT_EQ(0, ::listen(srv, 8));
  18504. auto cli = Client("127.0.0.1", PORT + 1);
  18505. cli.set_read_timeout(10, 0);
  18506. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  18507. return std::chrono::duration_cast<std::chrono::milliseconds>(
  18508. std::chrono::steady_clock::now() - start)
  18509. .count();
  18510. };
  18511. {
  18512. Request req;
  18513. req.method = "GE T";
  18514. req.path = "/";
  18515. auto start = std::chrono::steady_clock::now();
  18516. auto res = cli.send(req);
  18517. EXPECT_FALSE(res);
  18518. EXPECT_EQ(Error::Write, res.error());
  18519. EXPECT_LT(elapsed_ms(start), 1000);
  18520. }
  18521. {
  18522. auto start = std::chrono::steady_clock::now();
  18523. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  18524. EXPECT_FALSE(res);
  18525. EXPECT_EQ(Error::InvalidHeaders, res.error());
  18526. EXPECT_LT(elapsed_ms(start), 1000);
  18527. }
  18528. EXPECT_FALSE(cli.is_socket_open());
  18529. detail::close_socket(srv);
  18530. }
  18531. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  18532. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18533. default_socket_options(srv);
  18534. sockaddr_in addr{};
  18535. addr.sin_family = AF_INET;
  18536. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  18537. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18538. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18539. ASSERT_EQ(0, ::listen(srv, 1));
  18540. std::string received;
  18541. auto server_thread = std::thread([&] {
  18542. auto sock = ::accept(srv, nullptr, nullptr);
  18543. if (sock == INVALID_SOCKET) { return; }
  18544. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  18545. char buf[2048];
  18546. ssize_t n;
  18547. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  18548. received.append(buf, static_cast<size_t>(n));
  18549. }
  18550. detail::close_socket(sock);
  18551. });
  18552. {
  18553. auto cli = Client("127.0.0.1", PORT + 1);
  18554. // "Z" sorts after the default headers, so writing straight to the socket
  18555. // would have sent the request line and those headers before the rejection.
  18556. auto handle =
  18557. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  18558. EXPECT_FALSE(handle.is_valid());
  18559. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  18560. }
  18561. server_thread.join();
  18562. detail::close_socket(srv);
  18563. EXPECT_TRUE(received.empty()) << received;
  18564. }
  18565. TEST(PathParamsTest, StaticMatch) {
  18566. const auto pattern = "/users/all";
  18567. detail::PathParamsMatcher matcher(pattern);
  18568. Request request;
  18569. request.path = "/users/all";
  18570. ASSERT_TRUE(matcher.match(request));
  18571. std::unordered_map<std::string, std::string> expected_params = {};
  18572. EXPECT_EQ(request.path_params, expected_params);
  18573. }
  18574. TEST(PathParamsTest, StaticMismatch) {
  18575. const auto pattern = "/users/all";
  18576. detail::PathParamsMatcher matcher(pattern);
  18577. Request request;
  18578. request.path = "/users/1";
  18579. ASSERT_FALSE(matcher.match(request));
  18580. }
  18581. TEST(PathParamsTest, SingleParamInTheMiddle) {
  18582. const auto pattern = "/users/:id/subscriptions";
  18583. detail::PathParamsMatcher matcher(pattern);
  18584. Request request;
  18585. request.path = "/users/42/subscriptions";
  18586. ASSERT_TRUE(matcher.match(request));
  18587. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18588. EXPECT_EQ(request.path_params, expected_params);
  18589. }
  18590. TEST(PathParamsTest, SingleParamInTheEnd) {
  18591. const auto pattern = "/users/:id";
  18592. detail::PathParamsMatcher matcher(pattern);
  18593. Request request;
  18594. request.path = "/users/24";
  18595. ASSERT_TRUE(matcher.match(request));
  18596. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  18597. EXPECT_EQ(request.path_params, expected_params);
  18598. }
  18599. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  18600. const auto pattern = "/users/:id/";
  18601. detail::PathParamsMatcher matcher(pattern);
  18602. Request request;
  18603. request.path = "/users/42/";
  18604. ASSERT_TRUE(matcher.match(request));
  18605. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  18606. EXPECT_EQ(request.path_params, expected_params);
  18607. }
  18608. TEST(PathParamsTest, EmptyParam) {
  18609. const auto pattern = "/users/:id/";
  18610. detail::PathParamsMatcher matcher(pattern);
  18611. Request request;
  18612. request.path = "/users//";
  18613. ASSERT_TRUE(matcher.match(request));
  18614. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  18615. EXPECT_EQ(request.path_params, expected_params);
  18616. }
  18617. TEST(PathParamsTest, FragmentMismatch) {
  18618. const auto pattern = "/users/:id/";
  18619. detail::PathParamsMatcher matcher(pattern);
  18620. Request request;
  18621. request.path = "/admins/24/";
  18622. ASSERT_FALSE(matcher.match(request));
  18623. }
  18624. TEST(PathParamsTest, ExtraFragments) {
  18625. const auto pattern = "/users/:id";
  18626. detail::PathParamsMatcher matcher(pattern);
  18627. Request request;
  18628. request.path = "/users/42/subscriptions";
  18629. ASSERT_FALSE(matcher.match(request));
  18630. }
  18631. TEST(PathParamsTest, MissingTrailingParam) {
  18632. const auto pattern = "/users/:id";
  18633. detail::PathParamsMatcher matcher(pattern);
  18634. Request request;
  18635. request.path = "/users";
  18636. ASSERT_FALSE(matcher.match(request));
  18637. }
  18638. TEST(PathParamsTest, MissingParamInTheMiddle) {
  18639. const auto pattern = "/users/:id/subscriptions";
  18640. detail::PathParamsMatcher matcher(pattern);
  18641. Request request;
  18642. request.path = "/users/subscriptions";
  18643. ASSERT_FALSE(matcher.match(request));
  18644. }
  18645. TEST(PathParamsTest, MultipleParams) {
  18646. const auto pattern = "/users/:userid/subscriptions/:subid";
  18647. detail::PathParamsMatcher matcher(pattern);
  18648. Request request;
  18649. request.path = "/users/42/subscriptions/2";
  18650. ASSERT_TRUE(matcher.match(request));
  18651. std::unordered_map<std::string, std::string> expected_params = {
  18652. {"userid", "42"}, {"subid", "2"}};
  18653. EXPECT_EQ(request.path_params, expected_params);
  18654. }
  18655. TEST(PathParamsTest, SequenceOfParams) {
  18656. const auto pattern = "/values/:x/:y/:z";
  18657. detail::PathParamsMatcher matcher(pattern);
  18658. Request request;
  18659. request.path = "/values/1/2/3";
  18660. ASSERT_TRUE(matcher.match(request));
  18661. std::unordered_map<std::string, std::string> expected_params = {
  18662. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  18663. EXPECT_EQ(request.path_params, expected_params);
  18664. }
  18665. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  18666. const auto pattern = "/prefix:suffix";
  18667. detail::PathParamsMatcher matcher(pattern);
  18668. Request request;
  18669. request.path = "/prefix:suffix";
  18670. ASSERT_TRUE(matcher.match(request));
  18671. const std::unordered_map<std::string, std::string> expected_params = {};
  18672. EXPECT_EQ(request.path_params, expected_params);
  18673. }
  18674. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  18675. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  18676. // calling thread's stack on a long enough path for a quantified pattern;
  18677. // RegexMatcher must refuse to run regex matching on paths beyond
  18678. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  18679. detail::RegexMatcher matcher("/files/(.*)");
  18680. Request within_limit;
  18681. within_limit.path = "/files/" + std::string(10, 'A');
  18682. EXPECT_TRUE(matcher.match(within_limit));
  18683. Request over_limit;
  18684. over_limit.path =
  18685. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  18686. EXPECT_FALSE(matcher.match(over_limit));
  18687. }
  18688. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  18689. Server svr;
  18690. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  18691. res.set_content("ok", "text/plain");
  18692. });
  18693. auto port = svr.bind_to_any_port(HOST);
  18694. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  18695. auto se = detail::scope_exit([&] {
  18696. svr.stop();
  18697. thread.join();
  18698. ASSERT_FALSE(svr.is_running());
  18699. });
  18700. svr.wait_until_ready();
  18701. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  18702. // request URI limit; this used to be able to crash the process.
  18703. std::string path =
  18704. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  18705. std::string req = "GET " + path +
  18706. " HTTP/1.1\r\n"
  18707. "Host: " +
  18708. std::string(HOST) + ":" + std::to_string(port) +
  18709. "\r\n"
  18710. "Connection: close\r\n"
  18711. "\r\n";
  18712. std::string response;
  18713. ASSERT_TRUE(send_request(5, req, &response, port));
  18714. EXPECT_NE(std::string::npos, response.find("404"));
  18715. }
  18716. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  18717. Server svr;
  18718. auto handler = [](const Request & /*req*/, Response &res) {
  18719. res.set_content("hit", "text/plain");
  18720. };
  18721. // No regex metacharacter, so this one is compared literally
  18722. svr.Get("/literal/route", handler);
  18723. // '.' is a regex metacharacter, so this one must keep regex semantics
  18724. svr.Get("/a.c", handler);
  18725. auto port = svr.bind_to_any_port(HOST);
  18726. std::thread t([&]() { svr.listen_after_bind(); });
  18727. auto se = detail::scope_exit([&] {
  18728. svr.stop();
  18729. t.join();
  18730. ASSERT_FALSE(svr.is_running());
  18731. });
  18732. svr.wait_until_ready();
  18733. Client cli(HOST, port);
  18734. struct {
  18735. const char *path;
  18736. int status;
  18737. } cases[] = {
  18738. {"/literal/route", StatusCode::OK_200},
  18739. {"/literal/routes", StatusCode::NotFound_404},
  18740. {"/literal/rout", StatusCode::NotFound_404},
  18741. {"/abc", StatusCode::OK_200},
  18742. {"/a.c", StatusCode::OK_200},
  18743. };
  18744. for (const auto &x : cases) {
  18745. auto res = cli.Get(x.path);
  18746. ASSERT_TRUE(res) << x.path;
  18747. EXPECT_EQ(x.status, res->status) << x.path;
  18748. }
  18749. }
  18750. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  18751. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  18752. // from exhausting the stack, so it must only constrain routes that actually
  18753. // run a regular expression. A literal route is matched by comparison and
  18754. // stays usable at any length.
  18755. Server svr;
  18756. const std::string pattern =
  18757. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  18758. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  18759. res.set_content("hit", "text/plain");
  18760. });
  18761. auto port = svr.bind_to_any_port(HOST);
  18762. std::thread t([&]() { svr.listen_after_bind(); });
  18763. auto se = detail::scope_exit([&] {
  18764. svr.stop();
  18765. t.join();
  18766. ASSERT_FALSE(svr.is_running());
  18767. });
  18768. svr.wait_until_ready();
  18769. Client cli(HOST, port);
  18770. auto res = cli.Get(pattern);
  18771. ASSERT_TRUE(res);
  18772. EXPECT_EQ(StatusCode::OK_200, res->status);
  18773. }
  18774. TEST(ParseUrlTest, VariousPatterns) {
  18775. {
  18776. detail::UrlComponents uc;
  18777. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  18778. EXPECT_EQ("http", uc.scheme);
  18779. EXPECT_EQ("example.com", uc.host);
  18780. EXPECT_EQ("8080", uc.port);
  18781. EXPECT_EQ("/path", uc.path);
  18782. EXPECT_EQ("?q=1", uc.query);
  18783. }
  18784. {
  18785. detail::UrlComponents uc;
  18786. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  18787. EXPECT_EQ("https", uc.scheme);
  18788. EXPECT_EQ("example.com", uc.host);
  18789. EXPECT_TRUE(uc.port.empty());
  18790. EXPECT_EQ("/path", uc.path);
  18791. }
  18792. {
  18793. detail::UrlComponents uc;
  18794. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  18795. EXPECT_EQ("::1", uc.host);
  18796. EXPECT_EQ("8080", uc.port);
  18797. EXPECT_EQ("/path", uc.path);
  18798. }
  18799. {
  18800. detail::UrlComponents uc;
  18801. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  18802. }
  18803. {
  18804. // Bytes after the IPv6 literal must be a delimiter, not folded into
  18805. // the path while the connection still targets the bracketed host.
  18806. detail::UrlComponents uc;
  18807. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  18808. }
  18809. {
  18810. detail::UrlComponents uc;
  18811. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  18812. }
  18813. {
  18814. detail::UrlComponents uc;
  18815. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  18816. EXPECT_EQ("::1", uc.host);
  18817. EXPECT_TRUE(uc.port.empty());
  18818. EXPECT_EQ("/path", uc.path);
  18819. }
  18820. {
  18821. detail::UrlComponents uc;
  18822. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  18823. EXPECT_TRUE(uc.scheme.empty());
  18824. EXPECT_EQ("example.com", uc.host);
  18825. EXPECT_EQ("/path", uc.path);
  18826. EXPECT_EQ("?q=1", uc.query);
  18827. }
  18828. {
  18829. detail::UrlComponents uc;
  18830. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  18831. EXPECT_TRUE(uc.host.empty());
  18832. EXPECT_EQ("/path", uc.path);
  18833. EXPECT_EQ("?q=1", uc.query);
  18834. }
  18835. {
  18836. detail::UrlComponents uc;
  18837. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  18838. EXPECT_EQ("example.com", uc.host);
  18839. EXPECT_EQ("8080", uc.port);
  18840. }
  18841. {
  18842. // Unix socket path — must not be parsed as host
  18843. detail::UrlComponents uc;
  18844. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  18845. EXPECT_TRUE(uc.host.empty());
  18846. }
  18847. {
  18848. detail::UrlComponents uc;
  18849. ASSERT_TRUE(detail::parse_url("", uc));
  18850. EXPECT_TRUE(uc.host.empty());
  18851. EXPECT_TRUE(uc.path.empty());
  18852. }
  18853. {
  18854. detail::UrlComponents uc;
  18855. ASSERT_TRUE(detail::parse_url("HTTP://example.com/path", uc));
  18856. EXPECT_EQ("http", uc.scheme);
  18857. }
  18858. {
  18859. detail::UrlComponents uc;
  18860. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  18861. }
  18862. {
  18863. // Accepted by parse_url; callers restrict to http/https
  18864. detail::UrlComponents uc;
  18865. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  18866. EXPECT_EQ("ftp", uc.scheme);
  18867. }
  18868. {
  18869. detail::UrlComponents uc;
  18870. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  18871. }
  18872. {
  18873. detail::UrlComponents uc;
  18874. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  18875. }
  18876. }
  18877. TEST(ParseUrlTest, FragmentHandling) {
  18878. {
  18879. detail::UrlComponents uc;
  18880. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  18881. EXPECT_EQ("/path", uc.path);
  18882. EXPECT_TRUE(uc.query.empty());
  18883. }
  18884. {
  18885. detail::UrlComponents uc;
  18886. ASSERT_TRUE(detail::parse_url("#frag", uc));
  18887. EXPECT_TRUE(uc.path.empty());
  18888. EXPECT_TRUE(uc.query.empty());
  18889. }
  18890. }
  18891. TEST(ParseUrlTest, UserinfoHandling) {
  18892. // userinfo, and a backslash some parsers take for '/', are rejected: such
  18893. // parsers would see evil.com as the host.
  18894. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  18895. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  18896. for (auto url : urls) {
  18897. detail::UrlComponents uc;
  18898. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  18899. }
  18900. }
  18901. TEST(ParseUrlTest, IPv6EdgeCases) {
  18902. {
  18903. detail::UrlComponents uc;
  18904. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  18905. EXPECT_TRUE(uc.scheme.empty());
  18906. EXPECT_EQ("::1", uc.host);
  18907. EXPECT_EQ("8080", uc.port);
  18908. }
  18909. {
  18910. // Zone ID '%25' is not in [a-fA-F0-9:]
  18911. detail::UrlComponents uc;
  18912. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  18913. }
  18914. }
  18915. TEST(ParseUrlTest, SchemeEdgeCases) {
  18916. {
  18917. detail::UrlComponents uc;
  18918. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  18919. }
  18920. {
  18921. detail::UrlComponents uc;
  18922. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  18923. }
  18924. {
  18925. detail::UrlComponents uc;
  18926. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  18927. }
  18928. {
  18929. detail::UrlComponents uc;
  18930. ASSERT_TRUE(detail::parse_url("httpS://example.com/path", uc));
  18931. EXPECT_EQ("https", uc.scheme);
  18932. }
  18933. {
  18934. detail::UrlComponents uc;
  18935. ASSERT_TRUE(detail::parse_url("/path?next=https://example.com/", uc));
  18936. EXPECT_TRUE(uc.scheme.empty());
  18937. EXPECT_TRUE(uc.host.empty());
  18938. EXPECT_EQ("/path", uc.path);
  18939. EXPECT_EQ("?next=https://example.com/", uc.query);
  18940. }
  18941. }
  18942. TEST(ParseUrlTest, PortEdgeCases) {
  18943. {
  18944. detail::UrlComponents uc;
  18945. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  18946. EXPECT_TRUE(uc.port.empty());
  18947. EXPECT_EQ("/path", uc.path);
  18948. }
  18949. {
  18950. // parse_url accepts any port string; validation is done by parse_port
  18951. detail::UrlComponents uc;
  18952. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  18953. EXPECT_EQ("abc", uc.port);
  18954. }
  18955. }
  18956. TEST(ParseUrlTest, WebSocketPatterns) {
  18957. {
  18958. detail::UrlComponents uc;
  18959. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  18960. EXPECT_EQ("ws", uc.scheme);
  18961. EXPECT_EQ("echo.example.com", uc.host);
  18962. EXPECT_EQ("8080", uc.port);
  18963. EXPECT_EQ("/ws", uc.path);
  18964. }
  18965. {
  18966. detail::UrlComponents uc;
  18967. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  18968. EXPECT_EQ("wss", uc.scheme);
  18969. EXPECT_EQ("echo.example.com", uc.host);
  18970. EXPECT_TRUE(uc.port.empty());
  18971. EXPECT_EQ("/ws", uc.path);
  18972. }
  18973. }
  18974. TEST(ParseUrlTest, QueryOnly) {
  18975. detail::UrlComponents uc;
  18976. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  18977. EXPECT_TRUE(uc.host.empty());
  18978. EXPECT_TRUE(uc.path.empty());
  18979. EXPECT_EQ("?q=1&r=2", uc.query);
  18980. }
  18981. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  18982. detail::UrlComponents uc;
  18983. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  18984. EXPECT_TRUE(uc.scheme.empty());
  18985. EXPECT_EQ("example.com", uc.host);
  18986. EXPECT_EQ("443", uc.port);
  18987. EXPECT_EQ("/path", uc.path);
  18988. }
  18989. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  18990. // If ipv6 regex working, regex match codepath is taken.
  18991. // else port will default to 80 in Client impl
  18992. int clientImplMagicPort = 80;
  18993. int port = 4321;
  18994. // above ports must be different to avoid false negative
  18995. EXPECT_NE(clientImplMagicPort, port);
  18996. std::string ipV6TestURL = "http://[ff06::c3]";
  18997. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  18998. CLIENT_PRIVATE_KEY_FILE);
  18999. EXPECT_EQ(cli.port(), port);
  19000. }
  19001. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  19002. auto file_path = "./www/dir/index.html";
  19003. auto dir_path = "./www/dir";
  19004. detail::FileStat stat_file(file_path);
  19005. EXPECT_TRUE(stat_file.is_file());
  19006. EXPECT_FALSE(stat_file.is_dir());
  19007. detail::FileStat stat_dir(dir_path);
  19008. EXPECT_FALSE(stat_dir.is_file());
  19009. EXPECT_TRUE(stat_dir.is_dir());
  19010. }
  19011. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  19012. // IPv4 with default HTTP port (80)
  19013. EXPECT_EQ("example.com",
  19014. detail::make_host_and_port_string("example.com", 80, false));
  19015. // IPv4 with default HTTPS port (443)
  19016. EXPECT_EQ("example.com",
  19017. detail::make_host_and_port_string("example.com", 443, true));
  19018. // IPv4 with non-default HTTP port
  19019. EXPECT_EQ("example.com:8080",
  19020. detail::make_host_and_port_string("example.com", 8080, false));
  19021. // IPv4 with non-default HTTPS port
  19022. EXPECT_EQ("example.com:8443",
  19023. detail::make_host_and_port_string("example.com", 8443, true));
  19024. // IPv6 with default HTTP port (80)
  19025. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  19026. // IPv6 with default HTTPS port (443)
  19027. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  19028. // IPv6 with non-default HTTP port
  19029. EXPECT_EQ("[::1]:8080",
  19030. detail::make_host_and_port_string("::1", 8080, false));
  19031. // IPv6 with non-default HTTPS port
  19032. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  19033. // IPv6 full address with default port
  19034. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  19035. detail::make_host_and_port_string(
  19036. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  19037. // IPv6 full address with non-default port
  19038. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  19039. detail::make_host_and_port_string(
  19040. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  19041. // IPv6 localhost with non-default port
  19042. EXPECT_EQ("[::1]:3000",
  19043. detail::make_host_and_port_string("::1", 3000, false));
  19044. // IPv6 with zone ID (link-local address) with default port
  19045. EXPECT_EQ("[fe80::1%eth0]",
  19046. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  19047. // IPv6 with zone ID (link-local address) with non-default port
  19048. EXPECT_EQ("[fe80::1%eth0]:8080",
  19049. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  19050. // Edge case: Port 443 with is_ssl=false (should add port)
  19051. EXPECT_EQ("example.com:443",
  19052. detail::make_host_and_port_string("example.com", 443, false));
  19053. // Edge case: Port 80 with is_ssl=true (should add port)
  19054. EXPECT_EQ("example.com:80",
  19055. detail::make_host_and_port_string("example.com", 80, true));
  19056. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  19057. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  19058. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  19059. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  19060. // Security fix: Already bracketed IPv6 should not get double brackets
  19061. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  19062. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  19063. EXPECT_EQ("[::1]:8080",
  19064. detail::make_host_and_port_string("[::1]", 8080, false));
  19065. EXPECT_EQ("[2001:db8::1]:8080",
  19066. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  19067. EXPECT_EQ("[fe80::1%eth0]",
  19068. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  19069. EXPECT_EQ("[fe80::1%eth0]:8080",
  19070. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  19071. // Edge case: Empty host (should return as-is)
  19072. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  19073. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  19074. // This is a known limitation but shouldn't crash
  19075. EXPECT_EQ("[host:name]",
  19076. detail::make_host_and_port_string("host:name", 80, false));
  19077. // Port number edge cases (no validation, but should not crash)
  19078. EXPECT_EQ("example.com:0",
  19079. detail::make_host_and_port_string("example.com", 0, false));
  19080. EXPECT_EQ("example.com:-1",
  19081. detail::make_host_and_port_string("example.com", -1, false));
  19082. EXPECT_EQ("example.com:65535",
  19083. detail::make_host_and_port_string("example.com", 65535, false));
  19084. EXPECT_EQ("example.com:65536",
  19085. detail::make_host_and_port_string("example.com", 65536, false));
  19086. }
  19087. namespace httplib {
  19088. namespace detail {
  19089. std::string
  19090. make_connect_request_target(const std::map<std::string, std::string> &addr_map,
  19091. const std::string &host, int port);
  19092. } // namespace detail
  19093. } // namespace httplib
  19094. TEST(MakeConnectRequestTargetTest, FollowsHostnameAddrMap) {
  19095. std::map<std::string, std::string> addr_map = {
  19096. {"ipv4.example", "192.0.2.10"},
  19097. {"ipv6.example", "2001:db8::1"},
  19098. {"name.example", "internal.example.lan"},
  19099. {"empty.example", ""}};
  19100. EXPECT_EQ("192.0.2.10:443",
  19101. detail::make_connect_request_target(addr_map, "ipv4.example", 443));
  19102. EXPECT_EQ("[2001:db8::1]:443",
  19103. detail::make_connect_request_target(addr_map, "ipv6.example", 443));
  19104. EXPECT_EQ("internal.example.lan:8443", detail::make_connect_request_target(
  19105. addr_map, "name.example", 8443));
  19106. // An empty or absent mapping keeps the hostname as the target
  19107. EXPECT_EQ("empty.example:443", detail::make_connect_request_target(
  19108. addr_map, "empty.example", 443));
  19109. EXPECT_EQ("other.example:443", detail::make_connect_request_target(
  19110. addr_map, "other.example", 443));
  19111. EXPECT_EQ("[::1]:443", detail::make_connect_request_target({}, "::1", 443));
  19112. }
  19113. #ifdef CPPHTTPLIB_SSL_ENABLED
  19114. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  19115. httplib::SSLClient cli("roblox.com", 443);
  19116. cli.set_follow_location(true);
  19117. auto res = cli.Get("/");
  19118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19119. EXPECT_EQ(StatusCode::OK_200, res->status);
  19120. }
  19121. #endif
  19122. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  19123. Server svr;
  19124. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19125. EXPECT_EQ(res.status, 400);
  19126. });
  19127. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19128. auto se = detail::scope_exit([&] {
  19129. svr.stop();
  19130. thread.join();
  19131. ASSERT_FALSE(svr.is_running());
  19132. });
  19133. svr.wait_until_ready();
  19134. Client cli(HOST, PORT);
  19135. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  19136. }
  19137. TEST(InvalidHeaderCharsTest, is_field_name) {
  19138. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  19139. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  19140. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  19141. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  19142. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  19143. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  19144. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  19145. EXPECT_FALSE(detail::fields::is_field_name(""));
  19146. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  19147. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  19148. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  19149. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  19150. }
  19151. TEST(InvalidHeaderCharsTest, is_field_value) {
  19152. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  19153. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  19154. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  19155. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  19156. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  19157. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  19158. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  19159. EXPECT_TRUE(detail::fields::is_field_value(""));
  19160. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  19161. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  19162. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  19163. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  19164. EXPECT_TRUE(detail::fields::is_field_value("0"));
  19165. }
  19166. TEST(InvalidHeaderCharsTest, OnServer) {
  19167. Server svr;
  19168. svr.Get("/test_name", [&](const Request &req, Response &res) {
  19169. std::string header = "Not Set";
  19170. if (req.has_param("header")) { header = req.get_param_value("header"); }
  19171. res.set_header(header, "value");
  19172. res.set_content("Page Content Page Content", "text/plain");
  19173. });
  19174. svr.Get("/test_value", [&](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("X-Test", header);
  19178. res.set_content("Page Content Page Content", "text/plain");
  19179. });
  19180. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19181. auto se = detail::scope_exit([&] {
  19182. svr.stop();
  19183. thread.join();
  19184. ASSERT_FALSE(svr.is_running());
  19185. });
  19186. svr.wait_until_ready();
  19187. Client cli(HOST, PORT);
  19188. {
  19189. auto res = cli.Get(
  19190. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19191. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19192. EXPECT_EQ("Page Content Page Content", res->body);
  19193. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19194. }
  19195. {
  19196. auto res = cli.Get(
  19197. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  19198. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19199. EXPECT_EQ("Page Content Page Content", res->body);
  19200. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  19201. }
  19202. }
  19203. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  19204. auto handled = false;
  19205. Server svr;
  19206. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19207. thread t = thread([&] { svr.listen(HOST, PORT); });
  19208. auto se = detail::scope_exit([&] {
  19209. svr.stop();
  19210. t.join();
  19211. ASSERT_FALSE(svr.is_running());
  19212. ASSERT_FALSE(handled);
  19213. });
  19214. svr.wait_until_ready();
  19215. auto req = "POST /test HTTP/1.1\r\n"
  19216. "Content-Length: x\r\n"
  19217. "\r\n";
  19218. std::string response;
  19219. ASSERT_TRUE(send_request(1, req, &response));
  19220. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19221. response.substr(0, response.find("\r\n")));
  19222. }
  19223. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  19224. // case-insensitive, and a server that receives a 100-continue expectation in
  19225. // an HTTP/1.0 request MUST ignore it.
  19226. static void probe_expect(int port, const std::string &req, bool *got_100) {
  19227. std::string response;
  19228. ASSERT_TRUE(send_request(1, req, &response, port));
  19229. *got_100 = response.find("100 Continue") != std::string::npos;
  19230. }
  19231. class ExpectTokenTest : public ::testing::Test {
  19232. protected:
  19233. void SetUp() override {
  19234. svr_.Post("/p", [](const Request &, Response &res) {
  19235. res.set_content("ok", "text/plain");
  19236. });
  19237. port_ = svr_.bind_to_any_port(HOST);
  19238. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19239. svr_.wait_until_ready();
  19240. }
  19241. void TearDown() override {
  19242. svr_.stop();
  19243. if (thread_.joinable()) { thread_.join(); }
  19244. }
  19245. std::string request(const char *version, const char *expect_value) const {
  19246. return std::string("POST /p ") + version +
  19247. "\r\n"
  19248. "Host: localhost\r\n"
  19249. "Content-Length: 2\r\n"
  19250. "Connection: close\r\n"
  19251. "Expect: " +
  19252. expect_value +
  19253. "\r\n"
  19254. "\r\n"
  19255. "hi";
  19256. }
  19257. Server svr_;
  19258. int port_ = 0;
  19259. thread thread_;
  19260. };
  19261. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  19262. bool got_100 = false;
  19263. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  19264. EXPECT_TRUE(got_100);
  19265. }
  19266. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  19267. bool got_100 = true;
  19268. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  19269. EXPECT_FALSE(got_100);
  19270. }
  19271. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  19272. bool got_100 = false;
  19273. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  19274. EXPECT_TRUE(got_100);
  19275. }
  19276. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  19277. bool got_100 = false;
  19278. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  19279. EXPECT_TRUE(got_100);
  19280. }
  19281. // `100 Continue` is sent only when the server starts reading the body, so a
  19282. // request rejected before that never invites the client to send it. The
  19283. // requests below carry the expectation but withhold the body, as a client
  19284. // waiting for `100 Continue` would.
  19285. // A POST that expects `100 Continue` and withholds its two-byte body.
  19286. static std::string expect_headers_only(const std::string &path) {
  19287. return "POST " + path +
  19288. " HTTP/1.1\r\n"
  19289. "Host: localhost\r\n"
  19290. "Content-Length: 2\r\n"
  19291. "Expect: 100-continue\r\n"
  19292. "\r\n";
  19293. }
  19294. class ExpectLazyContinueTest : public ::testing::Test {
  19295. protected:
  19296. void SetUp() override {
  19297. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  19298. if (req.path == "/pre-routing") {
  19299. res.status = StatusCode::Unauthorized_401;
  19300. return Server::HandlerResponse::Handled;
  19301. }
  19302. return Server::HandlerResponse::Unhandled;
  19303. });
  19304. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  19305. if (req.matched_route == "/pre-request") {
  19306. res.status = StatusCode::Forbidden_403;
  19307. return Server::HandlerResponse::Handled;
  19308. }
  19309. return Server::HandlerResponse::Unhandled;
  19310. });
  19311. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  19312. res.set_content("ok", "text/plain");
  19313. });
  19314. svr_.Post("/pre-request", [](const Request &, Response &res) {
  19315. res.set_content("ok", "text/plain");
  19316. });
  19317. svr_.Post("/reader-used", [](const Request &, Response &res,
  19318. const ContentReader &content_reader) {
  19319. std::string body;
  19320. content_reader([&](const char *data, size_t len) {
  19321. body.append(data, len);
  19322. return true;
  19323. });
  19324. res.set_content(body, "text/plain");
  19325. });
  19326. svr_.Post("/reader-unused",
  19327. [](const Request &, Response &res, const ContentReader &) {
  19328. res.set_content("ignored", "text/plain");
  19329. });
  19330. port_ = svr_.bind_to_any_port(HOST);
  19331. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19332. svr_.wait_until_ready();
  19333. }
  19334. void TearDown() override {
  19335. svr_.stop();
  19336. if (thread_.joinable()) { thread_.join(); }
  19337. }
  19338. // Sends `req` and reads until the server closes the connection. Returns
  19339. // false if the read had to wait for the client-side timeout instead.
  19340. bool send_until_closed(const std::string &req, std::string *resp) const {
  19341. auto start = std::chrono::steady_clock::now();
  19342. if (!send_request(3, req, resp, port_)) { return false; }
  19343. auto elapsed = std::chrono::steady_clock::now() - start;
  19344. return elapsed < std::chrono::seconds(2);
  19345. }
  19346. // The final response comes without `100 Continue`, and the server closes
  19347. // the connection since the body may or may not follow.
  19348. void expect_final_without_interim(const std::string &path,
  19349. const char *status_line) const {
  19350. std::string resp;
  19351. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  19352. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  19353. EXPECT_EQ(0u, resp.find(status_line));
  19354. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19355. }
  19356. Server svr_;
  19357. int port_ = 0;
  19358. thread thread_;
  19359. };
  19360. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  19361. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  19362. }
  19363. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  19364. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  19365. }
  19366. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  19367. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  19368. }
  19369. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  19370. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  19371. }
  19372. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  19373. // The body follows once `100 Continue` has had time to arrive.
  19374. auto req = expect_headers_only("/reader-used");
  19375. req.insert(req.size() - 2, "Connection: close\r\n");
  19376. std::string resp;
  19377. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  19378. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  19379. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  19380. EXPECT_NE(std::string::npos, resp.find("hi"));
  19381. }
  19382. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  19383. // Large enough for the client to add `Expect: 100-continue` itself.
  19384. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  19385. std::atomic<bool> body_sent{false};
  19386. Client cli(HOST, port_);
  19387. auto res = cli.Post(
  19388. "/pre-request", length,
  19389. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  19390. body_sent = true;
  19391. std::string chunk(len, 'x');
  19392. sink.write(chunk.data(), chunk.size());
  19393. return true;
  19394. },
  19395. "application/octet-stream");
  19396. ASSERT_TRUE(res);
  19397. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  19398. EXPECT_FALSE(body_sent);
  19399. }
  19400. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  19401. Server svr;
  19402. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  19403. return StatusCode::ExpectationFailed_417;
  19404. });
  19405. svr.Post("/p", [](const Request &, Response &res) {
  19406. res.set_content("ok", "text/plain");
  19407. });
  19408. auto port = svr.bind_to_any_port(HOST);
  19409. thread t = thread([&] { svr.listen_after_bind(); });
  19410. auto se = detail::scope_exit([&] {
  19411. svr.stop();
  19412. t.join();
  19413. });
  19414. svr.wait_until_ready();
  19415. std::string resp;
  19416. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  19417. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  19418. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  19419. // Exactly one response: the route handler must not run after the 417.
  19420. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  19421. }
  19422. #ifndef _WIN32
  19423. TEST(Expect100ContinueTest, ServerClosesConnection) {
  19424. static constexpr char reject[] = "Unauthorized";
  19425. static constexpr char accept[] = "Upload accepted";
  19426. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  19427. Server svr;
  19428. svr.set_expect_100_continue_handler(
  19429. [](const Request & /*req*/, Response &res) {
  19430. res.status = StatusCode::Unauthorized_401;
  19431. res.set_content(reject, "text/plain");
  19432. return res.status;
  19433. });
  19434. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  19435. res.set_content(accept, "text/plain");
  19436. });
  19437. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19438. auto se = detail::scope_exit([&] {
  19439. svr.stop();
  19440. thread.join();
  19441. ASSERT_FALSE(svr.is_running());
  19442. });
  19443. svr.wait_until_ready();
  19444. {
  19445. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  19446. curl_easy_init(), &curl_easy_cleanup};
  19447. ASSERT_NE(curl, nullptr);
  19448. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  19449. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  19450. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  19451. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  19452. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  19453. &curl_slist_free_all};
  19454. ASSERT_NE(list, nullptr);
  19455. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  19456. struct read_data {
  19457. uint64_t read_size;
  19458. uint64_t total_size;
  19459. } data = {0, total_size};
  19460. using read_callback_t =
  19461. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19462. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  19463. void *userdata) -> size_t {
  19464. read_data *d = (read_data *)userdata;
  19465. if (!userdata || d->read_size >= d->total_size) { return 0; }
  19466. std::fill_n(ptr, size * nmemb, 'A');
  19467. d->read_size += size * nmemb;
  19468. return size * nmemb;
  19469. };
  19470. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  19471. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  19472. std::vector<char> buffer;
  19473. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  19474. using write_callback_t =
  19475. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  19476. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  19477. void *userdata) -> size_t {
  19478. std::vector<char> *buf = (std::vector<char> *)userdata;
  19479. buf->reserve(buf->size() + size * nmemb + 1);
  19480. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  19481. return size * nmemb;
  19482. };
  19483. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  19484. {
  19485. const auto res = curl_easy_perform(curl.get());
  19486. ASSERT_EQ(res, CURLE_OK);
  19487. }
  19488. {
  19489. auto response_code = long{};
  19490. const auto res =
  19491. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  19492. ASSERT_EQ(res, CURLE_OK);
  19493. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  19494. }
  19495. {
  19496. auto dl = curl_off_t{};
  19497. const auto res =
  19498. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  19499. ASSERT_EQ(res, CURLE_OK);
  19500. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  19501. }
  19502. {
  19503. buffer.push_back('\0');
  19504. ASSERT_STRCASEEQ(buffer.data(), reject);
  19505. }
  19506. }
  19507. }
  19508. #endif
  19509. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  19510. // Regression test for #2458.
  19511. //
  19512. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  19513. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  19514. // ticket can make the client socket spuriously readable during the
  19515. // 100-continue wait. If the readiness is mistaken for an incoming response,
  19516. // the client withholds the body and then blocks reading a response that never
  19517. // comes, failing with `Failed to read connection`.
  19518. //
  19519. // A correct client (like curl) sends the body once no `100 Continue` arrives
  19520. // within the timeout. This raw OpenSSL server deliberately never sends
  19521. // `100 Continue`; the client must still deliver the body and receive 200.
  19522. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  19523. signal(SIGPIPE, SIG_IGN);
  19524. const auto port = PORT + 4;
  19525. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19526. ASSERT_NE(srv, INVALID_SOCKET);
  19527. int opt = 1;
  19528. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  19529. sockaddr_in addr{};
  19530. addr.sin_family = AF_INET;
  19531. addr.sin_port = htons(static_cast<uint16_t>(port));
  19532. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19533. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  19534. ASSERT_EQ(0, ::listen(srv, 1));
  19535. std::atomic<size_t> server_body_bytes{0};
  19536. auto server_thread = std::thread([&] {
  19537. sockaddr_in cli_addr{};
  19538. socklen_t cli_len = sizeof(cli_addr);
  19539. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19540. if (cli == INVALID_SOCKET) { return; }
  19541. // Bound the lifetime of the server side so a buggy client (which never
  19542. // sends the body) cannot make this thread block forever on join.
  19543. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  19544. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  19545. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  19546. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  19547. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  19548. SSL *ssl = SSL_new(ctx);
  19549. SSL_set_fd(ssl, static_cast<int>(cli));
  19550. if (SSL_accept(ssl) > 0) {
  19551. // Read the request headers. Reading here also flushes the TLS 1.3
  19552. // session tickets to the client. Deliberately do NOT send
  19553. // `100 Continue`.
  19554. std::string buf;
  19555. char tmp[1024];
  19556. while (buf.find("\r\n\r\n") == std::string::npos) {
  19557. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19558. if (n <= 0) { break; }
  19559. buf.append(tmp, static_cast<size_t>(n));
  19560. }
  19561. // A correct client sends the body now; count what arrives.
  19562. auto pos = buf.find("\r\n\r\n");
  19563. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  19564. while (body < 4096) {
  19565. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  19566. if (n <= 0) { break; }
  19567. body += static_cast<size_t>(n);
  19568. }
  19569. server_body_bytes = body;
  19570. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19571. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  19572. SSL_shutdown(ssl);
  19573. }
  19574. SSL_free(ssl);
  19575. detail::close_socket(cli);
  19576. SSL_CTX_free(ctx);
  19577. });
  19578. auto se = detail::scope_exit([&] {
  19579. server_thread.join();
  19580. detail::close_socket(srv);
  19581. });
  19582. SSLClient cli("127.0.0.1", port);
  19583. cli.enable_server_certificate_verification(false);
  19584. cli.set_connection_timeout(5, 0);
  19585. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  19586. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  19587. std::string body(4096, 'A');
  19588. auto res = cli.Put("/api/test", body, "application/json");
  19589. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  19590. EXPECT_EQ(StatusCode::OK_200, res->status);
  19591. EXPECT_EQ(body.size(), server_body_bytes.load());
  19592. }
  19593. #endif
  19594. template <typename S, typename C>
  19595. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  19596. svr.Get("/stream", [&](const Request &, Response &res) {
  19597. auto data = new std::string("01234567890123456789");
  19598. res.set_content_provider(
  19599. data->size(), "text/plain",
  19600. [&, data](size_t offset, size_t length, DataSink &sink) {
  19601. const size_t DATA_CHUNK_SIZE = 4;
  19602. const auto &d = *data;
  19603. std::this_thread::sleep_for(std::chrono::seconds(1));
  19604. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  19605. return true;
  19606. },
  19607. [data](bool success) {
  19608. EXPECT_FALSE(success);
  19609. delete data;
  19610. });
  19611. });
  19612. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  19613. auto i = new size_t(0);
  19614. res.set_content_provider(
  19615. "text/plain",
  19616. [i](size_t, DataSink &sink) {
  19617. if (*i < 5) {
  19618. std::this_thread::sleep_for(std::chrono::seconds(1));
  19619. sink.write("abcd", 4);
  19620. (*i)++;
  19621. } else {
  19622. sink.done();
  19623. }
  19624. return true;
  19625. },
  19626. [i](bool success) {
  19627. EXPECT_FALSE(success);
  19628. delete i;
  19629. });
  19630. });
  19631. svr.Get("/chunked", [&](const Request &, Response &res) {
  19632. auto i = new size_t(0);
  19633. res.set_chunked_content_provider(
  19634. "text/plain",
  19635. [i](size_t, DataSink &sink) {
  19636. if (*i < 5) {
  19637. std::this_thread::sleep_for(std::chrono::seconds(1));
  19638. sink.os << "abcd";
  19639. (*i)++;
  19640. } else {
  19641. sink.done();
  19642. }
  19643. return true;
  19644. },
  19645. [i](bool success) {
  19646. EXPECT_FALSE(success);
  19647. delete i;
  19648. });
  19649. });
  19650. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  19651. auto se = detail::scope_exit([&] {
  19652. svr.stop();
  19653. listen_thread.join();
  19654. ASSERT_FALSE(svr.is_running());
  19655. });
  19656. svr.wait_until_ready();
  19657. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  19658. {
  19659. auto start = std::chrono::steady_clock::now();
  19660. auto res = cli.Get("/stream");
  19661. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19662. std::chrono::steady_clock::now() - start)
  19663. .count();
  19664. ASSERT_FALSE(res);
  19665. EXPECT_EQ(Error::Read, res.error());
  19666. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19667. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19668. }
  19669. {
  19670. auto start = std::chrono::steady_clock::now();
  19671. auto res = cli.Get("/stream_without_length");
  19672. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19673. std::chrono::steady_clock::now() - start)
  19674. .count();
  19675. ASSERT_FALSE(res);
  19676. EXPECT_EQ(Error::Read, res.error());
  19677. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19678. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19679. }
  19680. {
  19681. auto start = std::chrono::steady_clock::now();
  19682. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  19683. EXPECT_EQ("abcd", string(data, data_length));
  19684. return true;
  19685. });
  19686. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  19687. std::chrono::steady_clock::now() - start)
  19688. .count();
  19689. ASSERT_FALSE(res);
  19690. EXPECT_EQ(Error::Read, res.error());
  19691. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  19692. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  19693. }
  19694. }
  19695. TEST(MaxTimeoutTest, ContentStream) {
  19696. time_t timeout = 2000;
  19697. time_t threshold = 200;
  19698. Server svr;
  19699. Client cli("localhost", PORT);
  19700. max_timeout_test(svr, cli, timeout, threshold);
  19701. }
  19702. #ifdef CPPHTTPLIB_SSL_ENABLED
  19703. TEST(MaxTimeoutTest, ContentStreamSSL) {
  19704. time_t timeout = 2000;
  19705. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  19706. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19707. SSLClient cli("localhost", PORT);
  19708. cli.enable_server_certificate_verification(false);
  19709. max_timeout_test(svr, cli, timeout, threshold);
  19710. }
  19711. #endif
  19712. class EventDispatcher {
  19713. public:
  19714. EventDispatcher() {}
  19715. bool wait_event(DataSink *sink) {
  19716. unique_lock<mutex> lk(m_);
  19717. int id = id_;
  19718. // Wait with timeout to prevent hanging if client disconnects
  19719. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  19720. [&] { return cid_ == id; })) {
  19721. return false; // Timeout occurred
  19722. }
  19723. sink->write(message_.data(), message_.size());
  19724. return true;
  19725. }
  19726. void send_event(const string &message) {
  19727. lock_guard<mutex> lk(m_);
  19728. cid_ = id_++;
  19729. message_ = message;
  19730. cv_.notify_all();
  19731. }
  19732. private:
  19733. mutex m_;
  19734. condition_variable cv_;
  19735. atomic_int id_{0};
  19736. atomic_int cid_{-1};
  19737. string message_;
  19738. };
  19739. TEST(ClientInThreadTest, Issue2068) {
  19740. EventDispatcher ed;
  19741. Server svr;
  19742. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  19743. res.set_chunked_content_provider("text/event-stream",
  19744. [&](size_t /*offset*/, DataSink &sink) {
  19745. return ed.wait_event(&sink);
  19746. });
  19747. });
  19748. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  19749. svr.wait_until_ready();
  19750. thread event_thread([&] {
  19751. int id = 0;
  19752. while (svr.is_running()) {
  19753. this_thread::sleep_for(chrono::milliseconds(500));
  19754. std::stringstream ss;
  19755. ss << "data: " << id << "\n\n";
  19756. ed.send_event(ss.str());
  19757. id++;
  19758. }
  19759. });
  19760. auto se = detail::scope_exit([&] {
  19761. svr.stop();
  19762. listen_thread.join();
  19763. event_thread.join();
  19764. ASSERT_FALSE(svr.is_running());
  19765. });
  19766. {
  19767. auto client = detail::make_unique<Client>(HOST, PORT);
  19768. client->set_read_timeout(std::chrono::minutes(10));
  19769. std::atomic<bool> stop{false};
  19770. std::thread t([&] {
  19771. client->Get("/event1",
  19772. [&](const char *, size_t) -> bool { return !stop; });
  19773. });
  19774. std::this_thread::sleep_for(std::chrono::seconds(2));
  19775. stop = true;
  19776. client->stop();
  19777. t.join();
  19778. // Reset client after thread has finished
  19779. client.reset();
  19780. }
  19781. }
  19782. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  19783. auto handled = false;
  19784. Server svr;
  19785. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  19786. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19787. auto se = detail::scope_exit([&] {
  19788. svr.stop();
  19789. t.join();
  19790. ASSERT_FALSE(svr.is_running());
  19791. ASSERT_FALSE(handled);
  19792. });
  19793. svr.wait_until_ready();
  19794. // Two Content-Length headers with different values — must be rejected
  19795. auto req = "POST /test HTTP/1.1\r\n"
  19796. "Content-Length: 5\r\n"
  19797. "Content-Length: 10\r\n"
  19798. "\r\n"
  19799. "hello";
  19800. std::string response;
  19801. ASSERT_TRUE(send_request(1, req, &response));
  19802. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  19803. response.substr(0, response.find("\r\n")));
  19804. }
  19805. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  19806. auto handled = false;
  19807. Server svr;
  19808. svr.Post("/test", [&](const Request &, Response &res) {
  19809. handled = true;
  19810. res.set_content("ok", "text/plain");
  19811. });
  19812. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19813. auto se = detail::scope_exit([&] {
  19814. svr.stop();
  19815. t.join();
  19816. ASSERT_FALSE(svr.is_running());
  19817. ASSERT_TRUE(handled);
  19818. });
  19819. svr.wait_until_ready();
  19820. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  19821. auto req = "POST /test HTTP/1.1\r\n"
  19822. "Host: localhost\r\n"
  19823. "Content-Length: 5\r\n"
  19824. "Content-Length: 5\r\n"
  19825. "\r\n"
  19826. "hello";
  19827. std::string response;
  19828. ASSERT_TRUE(send_request(1, req, &response));
  19829. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  19830. }
  19831. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  19832. Server svr;
  19833. svr.Get("/test", [](const Request &, Response &res) {
  19834. res.set_content("ok", "text/plain");
  19835. });
  19836. auto port = svr.bind_to_any_port(HOST);
  19837. thread t = thread([&] { svr.listen_after_bind(); });
  19838. auto se = detail::scope_exit([&] {
  19839. svr.stop();
  19840. t.join();
  19841. ASSERT_FALSE(svr.is_running());
  19842. });
  19843. svr.wait_until_ready();
  19844. auto status_line = [&](const std::string &host_lines) {
  19845. std::string res;
  19846. send_request(
  19847. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  19848. &res, port);
  19849. return res.substr(0, res.find("\r\n"));
  19850. };
  19851. const char *accepted[] = {
  19852. "Host: localhost\r\n",
  19853. "Host: a.example:8080\r\n",
  19854. "Host: my_service\r\n",
  19855. "Host: [::1]:8080\r\n",
  19856. "Host: [fe80::1%25eth0]\r\n",
  19857. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  19858. };
  19859. for (auto host_lines : accepted) {
  19860. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  19861. }
  19862. const char *rejected[] = {
  19863. "Host: a.example\r\nHost: b.example\r\n",
  19864. "Host: a.example\r\nHost: a.example\r\n",
  19865. "Host: a@b.example\r\n",
  19866. "Host: a.example/b\r\n",
  19867. "Host: a.example\\b\r\n",
  19868. "Host: a.example?b\r\n",
  19869. "Host: a.example#b\r\n",
  19870. "Host: a.example b.example\r\n",
  19871. };
  19872. for (auto host_lines : rejected) {
  19873. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  19874. << host_lines;
  19875. }
  19876. }
  19877. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  19878. Server svr;
  19879. svr.Get("/", [](const Request &req, Response &res) {
  19880. EXPECT_EQ(2U, req.trailers.size());
  19881. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  19882. // Denied
  19883. EXPECT_FALSE(req.has_trailer("Content-Length"));
  19884. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  19885. // Accepted
  19886. EXPECT_TRUE(req.has_trailer("X-Hello"));
  19887. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  19888. EXPECT_TRUE(req.has_trailer("X-World"));
  19889. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  19890. res.set_content("ok", "text/plain");
  19891. });
  19892. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19893. auto se = detail::scope_exit([&] {
  19894. svr.stop();
  19895. t.join();
  19896. ASSERT_FALSE(svr.is_running());
  19897. });
  19898. svr.wait_until_ready();
  19899. const std::string req = "GET / HTTP/1.1\r\n"
  19900. "Transfer-Encoding: chunked\r\n"
  19901. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  19902. "\r\n"
  19903. "0\r\n"
  19904. "Content-Length: 10\r\n"
  19905. "Host: internal.local\r\n"
  19906. "Content-Type: malicious/content\r\n"
  19907. "Cookie: any\r\n"
  19908. "Set-Cookie: any\r\n"
  19909. "X-Forwarded-For: attacker.com\r\n"
  19910. "X-Real-Ip: 1.1.1.1\r\n"
  19911. "X-Hello: hello\r\n"
  19912. "X-World: world\r\n"
  19913. "\r\n";
  19914. std::string res;
  19915. ASSERT_TRUE(send_request(1, req, &res));
  19916. }
  19917. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  19918. // several field lines, and the combined value is what has to be parsed. A
  19919. // Trailer field split across lines therefore declares every name it lists;
  19920. // reading only the first line silently drops the trailers the later lines
  19921. // declare. The prohibited-trailer filter still applies to every line.
  19922. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  19923. Server svr;
  19924. size_t observed_trailer_count = 0;
  19925. std::string observed_hello;
  19926. std::string observed_world;
  19927. bool observed_content_length = true;
  19928. svr.Get("/", [&](const Request &req, Response &res) {
  19929. observed_trailer_count = req.trailers.size();
  19930. observed_hello = req.get_trailer_value("X-Hello");
  19931. observed_world = req.get_trailer_value("X-World");
  19932. observed_content_length = req.has_trailer("Content-Length");
  19933. res.set_content("ok", "text/plain");
  19934. });
  19935. auto port = svr.bind_to_any_port(HOST);
  19936. thread t = thread([&]() { svr.listen_after_bind(); });
  19937. auto se = detail::scope_exit([&] {
  19938. svr.stop();
  19939. t.join();
  19940. ASSERT_FALSE(svr.is_running());
  19941. });
  19942. svr.wait_until_ready();
  19943. const std::string req = "GET / HTTP/1.1\r\n"
  19944. "Host: localhost\r\n"
  19945. "Transfer-Encoding: chunked\r\n"
  19946. "Trailer: X-Hello\r\n"
  19947. "Trailer: X-World, Content-Length\r\n"
  19948. "\r\n"
  19949. "0\r\n"
  19950. "X-Hello: hello\r\n"
  19951. "X-World: world\r\n"
  19952. "Content-Length: 10\r\n"
  19953. "\r\n";
  19954. std::string res;
  19955. ASSERT_TRUE(send_request(1, req, &res, port));
  19956. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  19957. // Accepted: both field lines contribute to the declared set
  19958. EXPECT_EQ(2U, observed_trailer_count);
  19959. EXPECT_EQ(observed_hello, "hello");
  19960. EXPECT_EQ(observed_world, "world");
  19961. // Denied: a prohibited name stays prohibited on a later field line
  19962. EXPECT_FALSE(observed_content_length);
  19963. }
  19964. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  19965. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  19966. // unbounded run of fields that are never declared, because the counter would
  19967. // only advance for declared fields.
  19968. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  19969. Server svr;
  19970. bool handler_called = false;
  19971. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  19972. handler_called = true;
  19973. res.set_content("ok", "text/plain");
  19974. });
  19975. auto port = svr.bind_to_any_port(HOST);
  19976. thread t = thread([&]() { svr.listen_after_bind(); });
  19977. auto se = detail::scope_exit([&] {
  19978. svr.stop();
  19979. t.join();
  19980. ASSERT_FALSE(svr.is_running());
  19981. });
  19982. svr.wait_until_ready();
  19983. // Declare nothing, then send far more undeclared trailer fields than the
  19984. // header-count limit. Parsing must stop and reject the request rather than
  19985. // read every line.
  19986. std::string req = "GET / HTTP/1.1\r\n"
  19987. "Transfer-Encoding: chunked\r\n"
  19988. "\r\n"
  19989. "0\r\n";
  19990. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  19991. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  19992. }
  19993. req += "\r\n";
  19994. std::string res;
  19995. ASSERT_TRUE(send_request(1, req, &res, port));
  19996. // The request is rejected before the handler runs.
  19997. EXPECT_FALSE(handler_called);
  19998. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  19999. }
  20000. // The set of declared trailer names is capped so a peer cannot grow it without
  20001. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  20002. // declared past the cap is not honored, even if the field is actually sent.
  20003. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  20004. Server svr;
  20005. // One name inside the cap and one past it, so the test tracks the cap rather
  20006. // than a fixed count.
  20007. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  20008. const std::string within_cap_name = "X-T-0";
  20009. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  20010. bool observed_within_cap = false;
  20011. bool observed_past_cap = false;
  20012. svr.Get("/", [&](const Request &req, Response &res) {
  20013. observed_within_cap = req.has_trailer(within_cap_name);
  20014. observed_past_cap = req.has_trailer(past_cap_name);
  20015. res.set_content("ok", "text/plain");
  20016. });
  20017. auto port = svr.bind_to_any_port(HOST);
  20018. thread t = thread([&]() { svr.listen_after_bind(); });
  20019. auto se = detail::scope_exit([&] {
  20020. svr.stop();
  20021. t.join();
  20022. ASSERT_FALSE(svr.is_running());
  20023. });
  20024. svr.wait_until_ready();
  20025. // Declare more trailer names than the cap in a single Trailer field, then
  20026. // actually send the first (within the cap) and the last (past it).
  20027. std::string trailer_decl = "Trailer: ";
  20028. for (int i = 0; i < declared_count; i++) {
  20029. if (i != 0) { trailer_decl += ", "; }
  20030. trailer_decl += "X-T-" + std::to_string(i);
  20031. }
  20032. trailer_decl += "\r\n";
  20033. const std::string req = "GET / HTTP/1.1\r\n"
  20034. "Host: localhost\r\n"
  20035. "Transfer-Encoding: chunked\r\n" +
  20036. trailer_decl +
  20037. "\r\n"
  20038. "0\r\n" +
  20039. within_cap_name + ": a\r\n" + past_cap_name +
  20040. ": b\r\n"
  20041. "\r\n";
  20042. std::string res;
  20043. ASSERT_TRUE(send_request(1, req, &res, port));
  20044. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  20045. // A name within the cap is honored; one declared past the cap is dropped.
  20046. EXPECT_TRUE(observed_within_cap);
  20047. EXPECT_FALSE(observed_past_cap);
  20048. }
  20049. // A direct client that is not listed in trusted_proxies must not be able to
  20050. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  20051. // the peer address on the actual TCP connection determines whether the
  20052. // header is honored.
  20053. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  20054. Server svr;
  20055. // Deliberately does NOT include the loopback address the test client
  20056. // actually connects from, so the direct connection is not a trusted proxy.
  20057. svr.set_trusted_proxies({"203.0.113.66"});
  20058. std::string observed_remote_addr;
  20059. svr.Get("/ip", [&](const Request &req, Response &res) {
  20060. observed_remote_addr = req.remote_addr;
  20061. res.set_content("ok", "text/plain");
  20062. });
  20063. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20064. auto se = detail::scope_exit([&] {
  20065. svr.stop();
  20066. t.join();
  20067. ASSERT_FALSE(svr.is_running());
  20068. });
  20069. svr.wait_until_ready();
  20070. Client cli(HOST, PORT);
  20071. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  20072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20073. EXPECT_EQ(StatusCode::OK_200, res->status);
  20074. // The connecting peer is not a trusted proxy, so the spoofed header must be
  20075. // ignored entirely and the real connection-level address retained.
  20076. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20077. observed_remote_addr == "127.0.0.1");
  20078. }
  20079. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  20080. Server svr;
  20081. std::string observed_remote_addr;
  20082. std::string observed_xff;
  20083. svr.Get("/ip", [&](const Request &req, Response &res) {
  20084. observed_remote_addr = req.remote_addr;
  20085. observed_xff = req.get_header_value("X-Forwarded-For");
  20086. res.set_content("ok", "text/plain");
  20087. });
  20088. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20089. auto se = detail::scope_exit([&] {
  20090. svr.stop();
  20091. t.join();
  20092. ASSERT_FALSE(svr.is_running());
  20093. });
  20094. svr.wait_until_ready();
  20095. Client cli(HOST, PORT);
  20096. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  20097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20098. EXPECT_EQ(StatusCode::OK_200, res->status);
  20099. EXPECT_EQ(observed_xff, "203.0.113.66");
  20100. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20101. observed_remote_addr == "127.0.0.1");
  20102. }
  20103. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  20104. Server svr;
  20105. svr.set_trusted_proxies({"203.0.113.66"});
  20106. std::string observed_remote_addr;
  20107. std::string observed_xff;
  20108. svr.Get("/ip", [&](const Request &req, Response &res) {
  20109. observed_remote_addr = req.remote_addr;
  20110. observed_xff = req.get_header_value("X-Forwarded-For");
  20111. res.set_content("ok", "text/plain");
  20112. });
  20113. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20114. auto se = detail::scope_exit([&] {
  20115. svr.stop();
  20116. t.join();
  20117. ASSERT_FALSE(svr.is_running());
  20118. });
  20119. svr.wait_until_ready();
  20120. Client cli(HOST, PORT);
  20121. auto res = cli.Get("/ip");
  20122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20123. EXPECT_EQ(StatusCode::OK_200, res->status);
  20124. EXPECT_EQ(observed_xff, "");
  20125. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20126. observed_remote_addr == "127.0.0.1");
  20127. }
  20128. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  20129. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  20130. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  20131. Server svr;
  20132. svr.set_trusted_proxies({"127.0.0.1"});
  20133. svr.Get("/ip", [](const Request &req, Response &res) {
  20134. res.set_content(req.remote_addr, "text/plain");
  20135. });
  20136. auto port = svr.bind_to_any_port("::");
  20137. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  20138. thread t = thread([&] { svr.listen_after_bind(); });
  20139. auto se = detail::scope_exit([&] {
  20140. svr.stop();
  20141. t.join();
  20142. ASSERT_FALSE(svr.is_running());
  20143. });
  20144. svr.wait_until_ready();
  20145. Client cli("127.0.0.1", port);
  20146. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  20147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20148. EXPECT_EQ("198.51.100.23", res->body);
  20149. }
  20150. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  20151. Server svr;
  20152. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20153. svr.Get("/ip", [](const Request &req, Response &res) {
  20154. res.set_content(req.remote_addr, "text/plain");
  20155. });
  20156. auto port = svr.bind_to_any_port(HOST);
  20157. ASSERT_GT(port, 0);
  20158. thread t = thread([&] { svr.listen_after_bind(); });
  20159. auto se = detail::scope_exit([&] {
  20160. svr.stop();
  20161. t.join();
  20162. ASSERT_FALSE(svr.is_running());
  20163. });
  20164. svr.wait_until_ready();
  20165. Client cli(HOST, port);
  20166. auto res = cli.Get(
  20167. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  20168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20169. EXPECT_EQ("198.51.100.23", res->body);
  20170. }
  20171. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  20172. Server svr;
  20173. // Include the loopback address the test client actually connects from, so
  20174. // the direct connection itself is recognized as the trusted proxy hop.
  20175. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  20176. std::string observed_remote_addr;
  20177. std::string observed_xff;
  20178. svr.Get("/ip", [&](const Request &req, Response &res) {
  20179. observed_remote_addr = req.remote_addr;
  20180. observed_xff = req.get_header_value("X-Forwarded-For");
  20181. res.set_content("ok", "text/plain");
  20182. });
  20183. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20184. auto se = detail::scope_exit([&] {
  20185. svr.stop();
  20186. t.join();
  20187. ASSERT_FALSE(svr.is_running());
  20188. });
  20189. svr.wait_until_ready();
  20190. Client cli(HOST, PORT);
  20191. auto res = cli.Get(
  20192. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  20193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20194. EXPECT_EQ(StatusCode::OK_200, res->status);
  20195. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  20196. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20197. }
  20198. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  20199. Server svr;
  20200. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  20201. std::string observed_remote_addr;
  20202. std::string observed_xff;
  20203. svr.Get("/ip", [&](const Request &req, Response &res) {
  20204. observed_remote_addr = req.remote_addr;
  20205. observed_xff = req.get_header_value("X-Forwarded-For");
  20206. res.set_content("ok", "text/plain");
  20207. });
  20208. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20209. auto se = detail::scope_exit([&] {
  20210. svr.stop();
  20211. t.join();
  20212. ASSERT_FALSE(svr.is_running());
  20213. });
  20214. svr.wait_until_ready();
  20215. Client cli(HOST, PORT);
  20216. auto res = cli.Get(
  20217. "/ip",
  20218. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20220. EXPECT_EQ(StatusCode::OK_200, res->status);
  20221. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20222. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20223. }
  20224. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  20225. Server svr;
  20226. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20227. std::string observed_remote_addr;
  20228. std::string observed_xff;
  20229. svr.Get("/ip", [&](const Request &req, Response &res) {
  20230. observed_remote_addr = req.remote_addr;
  20231. observed_xff = req.get_header_value("X-Forwarded-For");
  20232. res.set_content("ok", "text/plain");
  20233. });
  20234. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20235. auto se = detail::scope_exit([&] {
  20236. svr.stop();
  20237. t.join();
  20238. ASSERT_FALSE(svr.is_running());
  20239. });
  20240. svr.wait_until_ready();
  20241. Client cli(HOST, PORT);
  20242. auto res = cli.Get(
  20243. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  20244. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20245. EXPECT_EQ(StatusCode::OK_200, res->status);
  20246. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  20247. // by the closest hop) is used. The leftmost entry is fully client-controlled
  20248. // and must not be selected.
  20249. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  20250. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  20251. }
  20252. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  20253. Server svr;
  20254. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  20255. std::string observed_remote_addr;
  20256. svr.Get("/ip", [&](const Request &req, Response &res) {
  20257. observed_remote_addr = req.remote_addr;
  20258. res.set_content("ok", "text/plain");
  20259. });
  20260. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20261. auto se = detail::scope_exit([&] {
  20262. svr.stop();
  20263. t.join();
  20264. ASSERT_FALSE(svr.is_running());
  20265. });
  20266. svr.wait_until_ready();
  20267. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  20268. // a forged address and the trusted proxy's own address; the forged value must
  20269. // not win over the address the trusted proxy actually recorded.
  20270. Client cli(HOST, PORT);
  20271. auto res = cli.Get(
  20272. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  20273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20274. EXPECT_EQ(StatusCode::OK_200, res->status);
  20275. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  20276. }
  20277. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  20278. Server svr;
  20279. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20280. std::string observed_remote_addr;
  20281. std::string observed_xff;
  20282. svr.Get("/ip", [&](const Request &req, Response &res) {
  20283. observed_remote_addr = req.remote_addr;
  20284. observed_xff = req.get_header_value("X-Forwarded-For");
  20285. res.set_content("ok", "text/plain");
  20286. });
  20287. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20288. auto se = detail::scope_exit([&] {
  20289. svr.stop();
  20290. t.join();
  20291. ASSERT_FALSE(svr.is_running());
  20292. });
  20293. svr.wait_until_ready();
  20294. Client cli(HOST, PORT);
  20295. auto res = cli.Get(
  20296. "/ip",
  20297. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  20298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20299. EXPECT_EQ(StatusCode::OK_200, res->status);
  20300. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  20301. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20302. }
  20303. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  20304. Server svr;
  20305. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20306. std::string observed_remote_addr;
  20307. std::string observed_xff;
  20308. svr.Get("/ip", [&](const Request &req, Response &res) {
  20309. observed_remote_addr = req.remote_addr;
  20310. observed_xff = req.get_header_value("X-Forwarded-For");
  20311. res.set_content("ok", "text/plain");
  20312. });
  20313. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20314. auto se = detail::scope_exit([&] {
  20315. svr.stop();
  20316. t.join();
  20317. ASSERT_FALSE(svr.is_running());
  20318. });
  20319. svr.wait_until_ready();
  20320. std::string raw_req =
  20321. "GET /ip HTTP/1.1\r\n"
  20322. "Host: localhost\r\n"
  20323. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  20324. "Connection: close\r\n"
  20325. "\r\n";
  20326. std::string out;
  20327. ASSERT_TRUE(send_request(5, raw_req, &out));
  20328. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20329. // Header parser trims surrounding whitespace of the header value
  20330. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  20331. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  20332. }
  20333. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  20334. // one comma-joined value, in the order received. Proxies such as HAProxy append
  20335. // their own X-Forwarded-For as a separate field line rather than extending the
  20336. // one the client sent, so every occurrence has to be taken into account.
  20337. // Reading only the first one hands back the address the client chose.
  20338. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  20339. Server svr;
  20340. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  20341. std::string observed_remote_addr;
  20342. size_t observed_xff_count = 0;
  20343. svr.Get("/ip", [&](const Request &req, Response &res) {
  20344. observed_remote_addr = req.remote_addr;
  20345. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  20346. res.set_content("ok", "text/plain");
  20347. });
  20348. auto port = svr.bind_to_any_port(HOST);
  20349. thread t = thread([&]() { svr.listen_after_bind(); });
  20350. auto se = detail::scope_exit([&] {
  20351. svr.stop();
  20352. t.join();
  20353. ASSERT_FALSE(svr.is_running());
  20354. });
  20355. svr.wait_until_ready();
  20356. // The client supplies the first field line; the trusted proxy appends the
  20357. // address it observed as a second one.
  20358. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  20359. "Host: localhost\r\n"
  20360. "X-Forwarded-For: 1.2.3.4\r\n"
  20361. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  20362. "Connection: close\r\n"
  20363. "\r\n";
  20364. std::string out;
  20365. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20366. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20367. EXPECT_EQ(observed_xff_count, 2U);
  20368. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20369. // The same chain spread over one field line per hop derives the same client
  20370. // address, i.e. the split and the comma-joined representations agree.
  20371. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  20372. "Host: localhost\r\n"
  20373. "X-Forwarded-For: 1.2.3.4\r\n"
  20374. "X-Forwarded-For: 198.51.100.23\r\n"
  20375. "X-Forwarded-For: 192.0.2.45\r\n"
  20376. "Connection: close\r\n"
  20377. "\r\n";
  20378. out.clear();
  20379. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  20380. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20381. EXPECT_EQ(observed_xff_count, 3U);
  20382. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  20383. }
  20384. // An X-Forwarded-For header whose value parses to zero IP segments must not
  20385. // crash the server (it used to call front() on an empty vector inside
  20386. // get_client_ip). The connection-level remote address must be retained instead.
  20387. static void run_malformed_xff_test(const std::string &xff_value) {
  20388. Server svr;
  20389. svr.set_trusted_proxies({"192.0.2.45"});
  20390. std::string observed_remote_addr;
  20391. svr.Get("/ip", [&](const Request &req, Response &res) {
  20392. observed_remote_addr = req.remote_addr;
  20393. res.set_content("ok", "text/plain");
  20394. });
  20395. int port = 0;
  20396. thread t = thread([&]() {
  20397. port = svr.bind_to_any_port(HOST);
  20398. svr.listen_after_bind();
  20399. });
  20400. auto se = detail::scope_exit([&] {
  20401. svr.stop();
  20402. t.join();
  20403. ASSERT_FALSE(svr.is_running());
  20404. });
  20405. svr.wait_until_ready();
  20406. Client cli(HOST, port);
  20407. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  20408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20409. EXPECT_EQ(StatusCode::OK_200, res->status);
  20410. EXPECT_TRUE(observed_remote_addr == "::1" ||
  20411. observed_remote_addr == "127.0.0.1");
  20412. }
  20413. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  20414. run_malformed_xff_test("");
  20415. }
  20416. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  20417. run_malformed_xff_test(",");
  20418. }
  20419. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  20420. run_malformed_xff_test(", , ,");
  20421. }
  20422. // The same rule applies to Accept: a request whose acceptable types are spread
  20423. // over several field lines must be negotiated against all of them.
  20424. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  20425. // case-insensitive connection options. Comparing the whole field value against
  20426. // one option misses a client that sends several of them, and misses every
  20427. // casing but the one written in the comparison.
  20428. //
  20429. // Sends req, reads the response, then reuses the same socket for a second
  20430. // request to find out whether the server kept the connection.
  20431. static void probe_connection_reuse(int port, const std::string &req,
  20432. bool *announced_close, bool *reusable) {
  20433. auto error = Error::Success;
  20434. auto sock = detail::create_client_socket(
  20435. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  20436. /*connection_timeout_sec=*/5, 0,
  20437. /*read_timeout_sec=*/1, 0,
  20438. /*write_timeout_sec=*/5, 0, std::string(), error);
  20439. ASSERT_NE(sock, INVALID_SOCKET);
  20440. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  20441. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  20442. "Host: localhost\r\n"
  20443. "Connection: close\r\n"
  20444. "\r\n";
  20445. std::string first_response;
  20446. std::string second_response;
  20447. detail::process_client_socket(
  20448. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  20449. [&](Stream &strm) {
  20450. if (strm.write(req.data(), req.size()) !=
  20451. static_cast<ssize_t>(req.size())) {
  20452. return false;
  20453. }
  20454. char buf[512];
  20455. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  20456. // Headers plus the two-byte body of the handler below
  20457. while (reader.getline()) {
  20458. first_response += reader.ptr();
  20459. if (first_response.find("ok") != std::string::npos) { break; }
  20460. }
  20461. if (strm.write(second.data(), second.size()) !=
  20462. static_cast<ssize_t>(second.size())) {
  20463. return true;
  20464. }
  20465. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  20466. while (reader2.getline()) {
  20467. second_response += reader2.ptr();
  20468. if (second_response.find("ok") != std::string::npos) { break; }
  20469. }
  20470. return true;
  20471. });
  20472. *announced_close =
  20473. first_response.find("Connection: close") != std::string::npos;
  20474. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  20475. }
  20476. class ConnectionTokenTest : public ::testing::Test {
  20477. protected:
  20478. void SetUp() override {
  20479. svr_.Get("/keepalive", [](const Request &, Response &res) {
  20480. res.set_content("ok", "text/plain");
  20481. });
  20482. port_ = svr_.bind_to_any_port(HOST);
  20483. thread_ = thread([&]() { svr_.listen_after_bind(); });
  20484. svr_.wait_until_ready();
  20485. }
  20486. void TearDown() override {
  20487. svr_.stop();
  20488. if (thread_.joinable()) { thread_.join(); }
  20489. }
  20490. Server svr_;
  20491. int port_ = 0;
  20492. thread thread_;
  20493. };
  20494. // "close" alongside another option still closes the connection, and the
  20495. // response says so rather than leaving the peer to discover it.
  20496. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  20497. bool announced_close = false;
  20498. bool reusable = true;
  20499. probe_connection_reuse(port_,
  20500. "GET /keepalive HTTP/1.1\r\n"
  20501. "Host: localhost\r\n"
  20502. "Connection: keep-alive, close\r\n"
  20503. "\r\n",
  20504. &announced_close, &reusable);
  20505. EXPECT_TRUE(announced_close);
  20506. EXPECT_FALSE(reusable);
  20507. }
  20508. // "close" split over two field lines is the same list, so it is honored too.
  20509. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  20510. bool announced_close = false;
  20511. bool reusable = true;
  20512. probe_connection_reuse(port_,
  20513. "GET /keepalive HTTP/1.1\r\n"
  20514. "Host: localhost\r\n"
  20515. "Connection: keep-alive\r\n"
  20516. "Connection: close\r\n"
  20517. "\r\n",
  20518. &announced_close, &reusable);
  20519. EXPECT_TRUE(announced_close);
  20520. EXPECT_FALSE(reusable);
  20521. }
  20522. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  20523. // keep-alive in the spelling everyone actually sends keeps its connection.
  20524. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  20525. bool announced_close = false;
  20526. bool reusable = false;
  20527. probe_connection_reuse(port_,
  20528. "GET /keepalive HTTP/1.0\r\n"
  20529. "Host: localhost\r\n"
  20530. "Connection: keep-alive\r\n"
  20531. "\r\n",
  20532. &announced_close, &reusable);
  20533. EXPECT_FALSE(announced_close);
  20534. EXPECT_TRUE(reusable);
  20535. }
  20536. // A token the value merely contains is not the token itself.
  20537. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  20538. bool announced_close = false;
  20539. bool reusable = false;
  20540. probe_connection_reuse(port_,
  20541. "GET /keepalive HTTP/1.1\r\n"
  20542. "Host: localhost\r\n"
  20543. "Connection: notclose\r\n"
  20544. "\r\n",
  20545. &announced_close, &reusable);
  20546. EXPECT_FALSE(announced_close);
  20547. EXPECT_TRUE(reusable);
  20548. }
  20549. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  20550. Server svr;
  20551. std::vector<std::string> observed_types;
  20552. svr.Get("/", [&](const Request &req, Response &res) {
  20553. observed_types = req.accept_content_types;
  20554. res.set_content("ok", "text/plain");
  20555. });
  20556. auto port = svr.bind_to_any_port(HOST);
  20557. thread t = thread([&]() { svr.listen_after_bind(); });
  20558. auto se = detail::scope_exit([&] {
  20559. svr.stop();
  20560. t.join();
  20561. ASSERT_FALSE(svr.is_running());
  20562. });
  20563. svr.wait_until_ready();
  20564. Client cli(HOST, port);
  20565. Headers headers;
  20566. headers.emplace("Accept", "text/plain;q=0.5");
  20567. headers.emplace("Accept", "application/json");
  20568. auto res = cli.Get("/", headers);
  20569. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20570. EXPECT_EQ(StatusCode::OK_200, res->status);
  20571. // Sorted by q-value, so the second field line's type comes first
  20572. ASSERT_EQ(2U, observed_types.size());
  20573. EXPECT_EQ("application/json", observed_types[0]);
  20574. EXPECT_EQ("text/plain", observed_types[1]);
  20575. }
  20576. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  20577. // empty field line must not contribute a bare comma to the combined value.
  20578. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  20579. Server svr;
  20580. std::vector<std::string> observed_types;
  20581. svr.Get("/", [&](const Request &req, Response &res) {
  20582. observed_types = req.accept_content_types;
  20583. res.set_content("ok", "text/plain");
  20584. });
  20585. auto port = svr.bind_to_any_port(HOST);
  20586. thread t = thread([&]() { svr.listen_after_bind(); });
  20587. auto se = detail::scope_exit([&] {
  20588. svr.stop();
  20589. t.join();
  20590. ASSERT_FALSE(svr.is_running());
  20591. });
  20592. svr.wait_until_ready();
  20593. // Empty first field line, then a real one
  20594. std::string raw_req = "GET / HTTP/1.1\r\n"
  20595. "Host: localhost\r\n"
  20596. "Accept:\r\n"
  20597. "Accept: application/json\r\n"
  20598. "Connection: close\r\n"
  20599. "\r\n";
  20600. std::string out;
  20601. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  20602. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  20603. ASSERT_EQ(1U, observed_types.size());
  20604. EXPECT_EQ("application/json", observed_types[0]);
  20605. }
  20606. // The skip in get_combined_header_value() is what keeps an empty field line
  20607. // from contributing a bare comma. Only a trailing empty field line exercises
  20608. // it: a leading one is already covered by the "combined is still empty" check,
  20609. // and parse_accept_header() now ignores the empty element either way, so the
  20610. // request-level test above can no longer tell the two apart.
  20611. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  20612. Headers headers;
  20613. headers.emplace("Accept", "text/html");
  20614. headers.emplace("Accept", "");
  20615. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  20616. headers.clear();
  20617. headers.emplace("Accept", "");
  20618. headers.emplace("Accept", "application/json");
  20619. EXPECT_EQ("application/json",
  20620. detail::get_combined_header_value(headers, "Accept"));
  20621. }
  20622. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20623. // An encoding offered on a later Accept-Encoding field line is still offered.
  20624. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  20625. Server svr;
  20626. svr.Get("/", [](const Request & /*req*/, Response &res) {
  20627. res.set_content(std::string(1024, 'x'), "text/plain");
  20628. });
  20629. auto port = svr.bind_to_any_port(HOST);
  20630. thread t = thread([&]() { svr.listen_after_bind(); });
  20631. auto se = detail::scope_exit([&] {
  20632. svr.stop();
  20633. t.join();
  20634. ASSERT_FALSE(svr.is_running());
  20635. });
  20636. svr.wait_until_ready();
  20637. Client cli(HOST, port);
  20638. cli.set_decompress(false);
  20639. Headers headers;
  20640. headers.emplace("Accept-Encoding", "identity");
  20641. headers.emplace("Accept-Encoding", "gzip");
  20642. auto res = cli.Get("/", headers);
  20643. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20644. EXPECT_EQ(StatusCode::OK_200, res->status);
  20645. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  20646. }
  20647. #endif
  20648. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  20649. // Transfer-Encoding is not its body.
  20650. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  20651. Server svr;
  20652. svr.set_payload_max_length(8);
  20653. svr.Post("/test", [](const Request &, Response &res) {
  20654. res.set_content("ok", "text/plain");
  20655. });
  20656. auto port = svr.bind_to_any_port(HOST);
  20657. ASSERT_GT(port, 0);
  20658. thread t = thread([&] { svr.listen_after_bind(); });
  20659. auto se = detail::scope_exit([&] {
  20660. svr.stop();
  20661. t.join();
  20662. ASSERT_FALSE(svr.is_running());
  20663. });
  20664. svr.wait_until_ready();
  20665. std::string resp;
  20666. ASSERT_TRUE(send_request(1,
  20667. "POST /test HTTP/1.1\r\n"
  20668. "Host: localhost\r\n"
  20669. "Connection: close\r\n"
  20670. "\r\n" +
  20671. std::string(16, 'X'),
  20672. &resp, port));
  20673. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  20674. }
  20675. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  20676. Server svr;
  20677. svr.Post("/post", [&](const Request &req, Response &res) {
  20678. res.set_content(req.body, "text/plain");
  20679. });
  20680. svr.Put("/put", [&](const Request &req, Response &res) {
  20681. res.set_content(req.body, "text/plain");
  20682. });
  20683. svr.Patch("/patch", [&](const Request &req, Response &res) {
  20684. res.set_content(req.body, "text/plain");
  20685. });
  20686. svr.Delete("/delete", [&](const Request &req, Response &res) {
  20687. res.set_content(req.body, "text/plain");
  20688. });
  20689. thread t = thread([&]() { svr.listen(HOST, PORT); });
  20690. auto se = detail::scope_exit([&] {
  20691. svr.stop();
  20692. t.join();
  20693. ASSERT_FALSE(svr.is_running());
  20694. });
  20695. svr.wait_until_ready();
  20696. std::string resp;
  20697. // POST without Content-Length
  20698. ASSERT_TRUE(send_request(5,
  20699. "POST /post HTTP/1.1\r\n"
  20700. "Host: localhost\r\n"
  20701. "Connection: close\r\n"
  20702. "\r\n",
  20703. &resp));
  20704. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20705. // PUT without Content-Length
  20706. resp.clear();
  20707. ASSERT_TRUE(send_request(5,
  20708. "PUT /put HTTP/1.1\r\n"
  20709. "Host: localhost\r\n"
  20710. "Connection: close\r\n"
  20711. "\r\n",
  20712. &resp));
  20713. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20714. // PATCH without Content-Length
  20715. resp.clear();
  20716. ASSERT_TRUE(send_request(5,
  20717. "PATCH /patch HTTP/1.1\r\n"
  20718. "Host: localhost\r\n"
  20719. "Connection: close\r\n"
  20720. "\r\n",
  20721. &resp));
  20722. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20723. // DELETE without Content-Length
  20724. resp.clear();
  20725. ASSERT_TRUE(send_request(5,
  20726. "DELETE /delete HTTP/1.1\r\n"
  20727. "Host: localhost\r\n"
  20728. "Connection: close\r\n"
  20729. "\r\n",
  20730. &resp));
  20731. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  20732. }
  20733. //==============================================================================
  20734. // open_stream() Tests
  20735. //==============================================================================
  20736. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  20737. std::string result;
  20738. char buf[8192];
  20739. ssize_t n;
  20740. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20741. result.append(buf, static_cast<size_t>(n));
  20742. }
  20743. return result;
  20744. }
  20745. // Mock stream for unit tests
  20746. class MockStream : public Stream {
  20747. public:
  20748. std::string data;
  20749. size_t pos = 0;
  20750. ssize_t error_after = -1; // -1 = no error
  20751. explicit MockStream(const std::string &d, ssize_t err = -1)
  20752. : data(d), error_after(err) {}
  20753. bool is_readable() const override { return true; }
  20754. bool wait_readable() const override { return true; }
  20755. bool wait_writable() const override { return true; }
  20756. ssize_t read(char *ptr, size_t size) override {
  20757. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  20758. if (pos >= data.size()) return 0;
  20759. size_t limit =
  20760. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  20761. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  20762. std::memcpy(ptr, data.data() + pos, to_read);
  20763. pos += to_read;
  20764. return static_cast<ssize_t>(to_read);
  20765. }
  20766. ssize_t write(const char *, size_t) override { return -1; }
  20767. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20768. ip = "127.0.0.1";
  20769. port = 0;
  20770. }
  20771. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20772. ip = "127.0.0.1";
  20773. port = 0;
  20774. }
  20775. socket_t socket() const override { return INVALID_SOCKET; }
  20776. time_t duration() const override { return 0; }
  20777. };
  20778. TEST(StreamHandleTest, Basic) {
  20779. ClientImpl::StreamHandle handle;
  20780. EXPECT_FALSE(handle.is_valid());
  20781. handle.response = detail::make_unique<Response>();
  20782. handle.error = Error::Connection;
  20783. EXPECT_FALSE(handle.is_valid());
  20784. handle.error = Error::Success;
  20785. EXPECT_TRUE(handle.is_valid());
  20786. }
  20787. TEST(BodyReaderTest, Basic) {
  20788. MockStream stream("Hello, World!");
  20789. detail::BodyReader reader;
  20790. reader.stream = &stream;
  20791. reader.content_length = 13;
  20792. char buf[32];
  20793. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  20794. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  20795. EXPECT_TRUE(reader.eof);
  20796. }
  20797. TEST(BodyReaderTest, NoStream) {
  20798. detail::BodyReader reader;
  20799. char buf[32];
  20800. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20801. EXPECT_EQ(Error::Connection, reader.last_error);
  20802. }
  20803. TEST(BodyReaderTest, Error) {
  20804. MockStream stream("Hello, World!", 5);
  20805. detail::BodyReader reader;
  20806. reader.stream = &stream;
  20807. reader.content_length = 13;
  20808. char buf[32];
  20809. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  20810. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  20811. EXPECT_EQ(Error::Read, reader.last_error);
  20812. }
  20813. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  20814. // Mock-based StreamHandle tests relying on private internals are removed.
  20815. class OpenStreamTest : public ::testing::Test {
  20816. protected:
  20817. void SetUp() override {
  20818. svr_.Get("/hello", [](const Request &, Response &res) {
  20819. res.set_content("Hello World!", "text/plain");
  20820. });
  20821. svr_.Get("/large", [](const Request &, Response &res) {
  20822. res.set_content(std::string(10000, 'X'), "text/plain");
  20823. });
  20824. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  20825. res.set_content("Hello World!", "image/jpeg");
  20826. res.set_header("Content-Encoding", "UTF-8");
  20827. });
  20828. svr_.Get("/chunked", [](const Request &, Response &res) {
  20829. res.set_chunked_content_provider("text/plain",
  20830. [](size_t offset, DataSink &sink) {
  20831. if (offset < 15) {
  20832. sink.write("chunk", 5);
  20833. return true;
  20834. }
  20835. sink.done();
  20836. return true;
  20837. });
  20838. });
  20839. svr_.Get("/compressible", [](const Request &, Response &res) {
  20840. res.set_chunked_content_provider("text/plain", [](size_t offset,
  20841. DataSink &sink) {
  20842. if (offset < 100 * 1024) {
  20843. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  20844. sink.write(chunk.data(), chunk.size());
  20845. return true;
  20846. }
  20847. sink.done();
  20848. return true;
  20849. });
  20850. });
  20851. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  20852. [](const Request & /*req*/, Response &res) {
  20853. auto i = new int(0);
  20854. res.set_header("Trailer", "Content-Length, X-Allowed");
  20855. res.set_chunked_content_provider(
  20856. "text/plain",
  20857. [i](size_t /*offset*/, DataSink &sink) {
  20858. switch (*i) {
  20859. case 0: sink.os << "123"; break;
  20860. case 1: sink.os << "456"; break;
  20861. case 2: sink.os << "789"; break;
  20862. case 3: {
  20863. sink.done_with_trailer(
  20864. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  20865. } break;
  20866. }
  20867. (*i)++;
  20868. return true;
  20869. },
  20870. [i](bool success) {
  20871. EXPECT_TRUE(success);
  20872. delete i;
  20873. });
  20874. });
  20875. // Echo headers endpoint for header-related tests
  20876. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  20877. std::string body;
  20878. for (const auto &h : req.headers) {
  20879. body.append(h.first);
  20880. body.push_back(':');
  20881. body.append(h.second);
  20882. body.push_back('\n');
  20883. }
  20884. res.set_content(body, "text/plain");
  20885. });
  20886. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  20887. std::string body;
  20888. for (const auto &h : req.headers) {
  20889. body.append(h.first);
  20890. body.push_back(':');
  20891. body.append(h.second);
  20892. body.push_back('\n');
  20893. }
  20894. res.set_content(body, "text/plain");
  20895. });
  20896. port_ = svr_.bind_to_any_port("127.0.0.1");
  20897. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20898. svr_.wait_until_ready();
  20899. }
  20900. void TearDown() override {
  20901. svr_.stop();
  20902. if (thread_.joinable()) thread_.join();
  20903. }
  20904. Server svr_;
  20905. std::thread thread_;
  20906. int port_ = 0;
  20907. };
  20908. TEST_F(OpenStreamTest, Basic) {
  20909. Client cli("127.0.0.1", port_);
  20910. auto handle = cli.open_stream("GET", "/hello");
  20911. EXPECT_TRUE(handle.is_valid());
  20912. EXPECT_EQ("Hello World!", read_all(handle));
  20913. }
  20914. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  20915. Client cli("127.0.0.1", port_);
  20916. auto handle = cli.open_stream("GET", "/unknown-encoding");
  20917. ASSERT_TRUE(handle.is_valid());
  20918. EXPECT_EQ("Hello World!", read_all(handle));
  20919. }
  20920. TEST_F(OpenStreamTest, SmallBuffer) {
  20921. Client cli("127.0.0.1", port_);
  20922. auto handle = cli.open_stream("GET", "/hello");
  20923. std::string result;
  20924. char buf[4];
  20925. ssize_t n;
  20926. while ((n = handle.read(buf, sizeof(buf))) > 0)
  20927. result.append(buf, static_cast<size_t>(n));
  20928. EXPECT_EQ("Hello World!", result);
  20929. }
  20930. TEST_F(OpenStreamTest, DefaultHeaders) {
  20931. Client cli("127.0.0.1", port_);
  20932. // open_stream GET should include Host, User-Agent and Accept-Encoding
  20933. {
  20934. auto handle = cli.open_stream("GET", "/echo-headers");
  20935. ASSERT_TRUE(handle.is_valid());
  20936. auto body = read_all(handle);
  20937. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  20938. std::string::npos);
  20939. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  20940. std::string::npos);
  20941. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  20942. }
  20943. // open_stream POST with body and no explicit content_type should NOT add
  20944. // text/plain Content-Type (behavior differs from non-streaming path), but
  20945. // should include Content-Length
  20946. {
  20947. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  20948. ASSERT_TRUE(handle.is_valid());
  20949. auto body = read_all(handle);
  20950. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  20951. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  20952. }
  20953. // open_stream POST with explicit Content-Type should preserve it
  20954. {
  20955. auto handle = cli.open_stream("POST", "/echo-headers", {},
  20956. {{"Content-Type", "application/custom"}},
  20957. "{}", "application/custom");
  20958. ASSERT_TRUE(handle.is_valid());
  20959. auto body = read_all(handle);
  20960. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  20961. }
  20962. // User-specified User-Agent must not be overwritten for stream API
  20963. {
  20964. auto handle = cli.open_stream("GET", "/echo-headers", {},
  20965. {{"User-Agent", "MyAgent/1.2"}});
  20966. ASSERT_TRUE(handle.is_valid());
  20967. auto body = read_all(handle);
  20968. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  20969. }
  20970. }
  20971. TEST_F(OpenStreamTest, Large) {
  20972. Client cli("127.0.0.1", port_);
  20973. auto handle = cli.open_stream("GET", "/large");
  20974. EXPECT_EQ(10000u, read_all(handle).size());
  20975. }
  20976. TEST_F(OpenStreamTest, ConnectionError) {
  20977. Client cli("127.0.0.1", 9999);
  20978. auto handle = cli.open_stream("GET", "/hello");
  20979. EXPECT_FALSE(handle.is_valid());
  20980. }
  20981. TEST_F(OpenStreamTest, Chunked) {
  20982. Client cli("127.0.0.1", port_);
  20983. auto handle = cli.open_stream("GET", "/chunked");
  20984. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20985. "Transfer-Encoding") == "chunked");
  20986. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  20987. }
  20988. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  20989. Client cli("127.0.0.1", port_);
  20990. auto handle =
  20991. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  20992. ASSERT_TRUE(handle.is_valid());
  20993. // Consume body to allow trailers to be received/parsed
  20994. auto body = read_all(handle);
  20995. // Explicitly parse trailers (ensure trailers are available for assertion)
  20996. handle.parse_trailers_if_needed();
  20997. EXPECT_EQ(std::string("123456789"), body);
  20998. // The response should include a Trailer header declaring both names
  20999. ASSERT_TRUE(handle.response);
  21000. EXPECT_TRUE(handle.response->has_header("Trailer"));
  21001. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  21002. handle.response->get_header_value("Trailer"));
  21003. // Prohibited trailer must not be present
  21004. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  21005. // Allowed trailer should be present
  21006. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  21007. EXPECT_EQ(std::string("yes"),
  21008. handle.response->get_trailer_value("X-Allowed"));
  21009. // Verify trailers are NOT present as regular headers
  21010. EXPECT_EQ(std::string(""),
  21011. handle.response->get_header_value("Content-Length"));
  21012. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  21013. }
  21014. // Accepts one connection on an OS-assigned port, which it hands over through
  21015. // port_promise, reads the request head and sends back response. after_send,
  21016. // if given, runs on the connection before it is closed.
  21017. static std::thread
  21018. serve_single_response(std::promise<int> &port_promise,
  21019. const std::string &response,
  21020. std::function<void(socket_t)> after_send = nullptr) {
  21021. return std::thread([&port_promise, response, after_send] {
  21022. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21023. default_socket_options(srv);
  21024. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  21025. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  21026. sockaddr_in addr{};
  21027. addr.sin_family = AF_INET;
  21028. addr.sin_port = htons(0); // Let OS assign a free port
  21029. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21030. int opt = 1;
  21031. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  21032. #ifdef _WIN32
  21033. reinterpret_cast<const char *>(&opt),
  21034. #else
  21035. &opt,
  21036. #endif
  21037. sizeof(opt));
  21038. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21039. ::listen(srv, 1) != 0) {
  21040. port_promise.set_value(-1);
  21041. detail::close_socket(srv);
  21042. return;
  21043. }
  21044. socklen_t addr_len = sizeof(addr);
  21045. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21046. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21047. sockaddr_in cli_addr{};
  21048. socklen_t cli_len = sizeof(cli_addr);
  21049. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  21050. if (cli != INVALID_SOCKET) {
  21051. // Read the complete HTTP request (until the blank line that terminates
  21052. // headers) before sending the response. If the server closes the socket
  21053. // while the client's request data is still unread in the kernel receive
  21054. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  21055. // connection on both sides: it discards the client's receive buffer
  21056. // (which already holds our response) and causes any in-progress write on
  21057. // the client to fail with ECONNRESET. Reading all request data first
  21058. // ensures close() emits a graceful FIN.
  21059. {
  21060. char rbuf[256];
  21061. std::string req;
  21062. while (req.find("\r\n\r\n") == std::string::npos) {
  21063. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  21064. if (n <= 0) { break; }
  21065. req.append(rbuf, static_cast<size_t>(n));
  21066. }
  21067. }
  21068. ::send(cli,
  21069. #ifdef _WIN32
  21070. static_cast<const char *>(response.c_str()),
  21071. static_cast<int>(response.size()),
  21072. #else
  21073. response.c_str(), response.size(),
  21074. #endif
  21075. 0);
  21076. if (after_send) { after_send(cli); }
  21077. detail::close_socket(cli);
  21078. }
  21079. detail::close_socket(srv);
  21080. });
  21081. }
  21082. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  21083. #ifndef _WIN32
  21084. signal(SIGPIPE, SIG_IGN);
  21085. #endif
  21086. std::promise<int> port_promise;
  21087. auto port_future = port_promise.get_future();
  21088. auto server_thread =
  21089. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  21090. "Content-Type: text/plain\r\n"
  21091. "Content-Length: not-a-number\r\n"
  21092. "Connection: close\r\n"
  21093. "\r\n"
  21094. "hello");
  21095. auto port = port_future.get();
  21096. ASSERT_GT(port, 0);
  21097. Client cli("127.0.0.1", port);
  21098. auto handle = cli.open_stream("GET", "/");
  21099. EXPECT_FALSE(handle.is_valid());
  21100. server_thread.join();
  21101. }
  21102. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  21103. #ifndef _WIN32
  21104. signal(SIGPIPE, SIG_IGN);
  21105. #endif
  21106. std::promise<int> port_promise;
  21107. auto port_future = port_promise.get_future();
  21108. auto server_thread = serve_single_response(
  21109. port_promise, "HTTP/1.1 200 OK\r\n"
  21110. "Content-Type: text/plain\r\n"
  21111. "Content-Length: 99999999999999999999999999\r\n"
  21112. "Connection: close\r\n"
  21113. "\r\n"
  21114. "hello");
  21115. auto port = port_future.get();
  21116. ASSERT_GT(port, 0);
  21117. // Historically std::stoull would throw std::out_of_range here and crash
  21118. // the process, then parsing silently clamped to a bogus framing length and
  21119. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  21120. // so the stream fails to open, matching the not-a-number case above. The
  21121. // process still must NOT terminate.
  21122. Client cli("127.0.0.1", port);
  21123. auto handle = cli.open_stream("GET", "/");
  21124. EXPECT_FALSE(handle.is_valid());
  21125. server_thread.join();
  21126. }
  21127. #ifndef _WIN32
  21128. // As above for the body of a streamed request: a send() cut short by the write
  21129. // timeout must not leave the rest of the body unsent.
  21130. TEST(OpenStreamPartialWriteTest, BodyIsWrittenWhole) {
  21131. signal(SIGPIPE, SIG_IGN);
  21132. Server svr;
  21133. svr.set_socket_options([](socket_t sock) {
  21134. int size = 8192;
  21135. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  21136. reinterpret_cast<const char *>(&size), sizeof(size));
  21137. });
  21138. svr.Post("/size", [](const Request &, Response &res,
  21139. const ContentReader &content_reader) {
  21140. // Outlast the client's write timeout before reading the body.
  21141. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  21142. size_t received = 0;
  21143. content_reader([&](const char *, size_t len) {
  21144. received += len;
  21145. return true;
  21146. });
  21147. res.set_content(std::to_string(received), "text/plain");
  21148. });
  21149. auto port = svr.bind_to_any_port(HOST);
  21150. std::thread t([&]() { svr.listen_after_bind(); });
  21151. auto se = detail::scope_exit([&] {
  21152. svr.stop();
  21153. t.join();
  21154. });
  21155. svr.wait_until_ready();
  21156. Client cli(HOST, port);
  21157. cli.set_write_timeout(0, 500000);
  21158. cli.set_socket_options([](socket_t sock) {
  21159. int size = 8192;
  21160. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  21161. reinterpret_cast<const char *>(&size), sizeof(size));
  21162. });
  21163. const std::string body(4 * 1024 * 1024, 'A');
  21164. auto handle = cli.open_stream("POST", "/size", {}, {}, body,
  21165. "application/octet-stream");
  21166. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21167. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  21168. EXPECT_EQ(std::to_string(body.size()), read_all(handle));
  21169. }
  21170. #endif
  21171. TEST(OpenStreamConcurrencyTest, RequestInFlightKeepsItsConnection) {
  21172. std::promise<void> slow_started;
  21173. auto slow_started_future = slow_started.get_future();
  21174. Server svr;
  21175. svr.Get("/slow", [&](const Request &, Response &res) {
  21176. slow_started.set_value();
  21177. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  21178. res.set_content("slow", "text/plain");
  21179. });
  21180. svr.Get("/fast", [](const Request &, Response &res) {
  21181. res.set_content("fast", "text/plain");
  21182. });
  21183. auto port = svr.bind_to_any_port(HOST);
  21184. std::thread t([&]() { svr.listen_after_bind(); });
  21185. auto se = detail::scope_exit([&] {
  21186. svr.stop();
  21187. t.join();
  21188. });
  21189. svr.wait_until_ready();
  21190. Client cli(HOST, port);
  21191. std::string slow_body;
  21192. std::thread slow_thread([&] {
  21193. auto res = cli.Get("/slow");
  21194. if (res) { slow_body = res->body; }
  21195. });
  21196. slow_started_future.wait();
  21197. auto result = stream::Get(cli, "/fast");
  21198. auto fast_body = result.is_valid() ? result.read_all() : std::string();
  21199. slow_thread.join();
  21200. EXPECT_EQ("slow", slow_body);
  21201. EXPECT_EQ("fast", fast_body);
  21202. }
  21203. // Serves `response` to the single request `fn` makes with a fresh client.
  21204. template <typename Fn>
  21205. static void with_single_response(const std::string &response, Fn fn) {
  21206. #ifndef _WIN32
  21207. signal(SIGPIPE, SIG_IGN);
  21208. #endif
  21209. std::promise<int> port_promise;
  21210. auto port_future = port_promise.get_future();
  21211. auto server_thread = serve_single_response(port_promise, response);
  21212. auto se = detail::scope_exit([&] { server_thread.join(); });
  21213. auto port = port_future.get();
  21214. ASSERT_GT(port, 0);
  21215. Client cli("127.0.0.1", port);
  21216. fn(cli);
  21217. }
  21218. // set_decompress(false) hands out the encoded bytes through the streaming APIs
  21219. // too, also in a build without the decoder for the advertised coding.
  21220. TEST(StreamDecompressionTest, DisabledPreservesEncodedBody) {
  21221. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  21222. const auto response = "HTTP/1.1 200 OK\r\n"
  21223. "Content-Encoding: gzip\r\n"
  21224. "Content-Length: " +
  21225. std::to_string(gzipped.size()) +
  21226. "\r\n"
  21227. "Connection: close\r\n\r\n" +
  21228. gzipped;
  21229. with_single_response(response, [&](Client &cli) {
  21230. cli.set_decompress(false);
  21231. auto handle = cli.open_stream("GET", "/");
  21232. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21233. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21234. EXPECT_EQ(gzipped, read_all(handle));
  21235. EXPECT_FALSE(handle.has_read_error());
  21236. });
  21237. with_single_response(response, [&](Client &cli) {
  21238. cli.set_decompress(false);
  21239. auto res = stream::Get(cli, "/", 7);
  21240. ASSERT_TRUE(res) << to_string(res.error());
  21241. EXPECT_EQ("gzip", res.get_header_value("Content-Encoding"));
  21242. EXPECT_EQ(gzipped, res.read_all());
  21243. EXPECT_FALSE(res.has_read_error());
  21244. });
  21245. }
  21246. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  21247. // Neither Content-Length nor chunked: the body ends at the close
  21248. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  21249. "Connection: close\r\n"
  21250. "\r\n"
  21251. "hello";
  21252. with_single_response(close_delimited, [](Client &cli) {
  21253. auto handle = cli.open_stream("GET", "/");
  21254. ASSERT_TRUE(handle.is_valid());
  21255. EXPECT_EQ("hello", read_all(handle));
  21256. EXPECT_FALSE(handle.has_read_error());
  21257. });
  21258. // A close before the end of the Content-Length is still an error
  21259. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  21260. "Content-Length: 10\r\n"
  21261. "\r\n"
  21262. "hello";
  21263. with_single_response(short_content_length, [](Client &cli) {
  21264. auto handle = cli.open_stream("GET", "/");
  21265. ASSERT_TRUE(handle.is_valid());
  21266. read_all(handle);
  21267. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  21268. });
  21269. // So is a close before the last chunk
  21270. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  21271. "Transfer-Encoding: chunked\r\n"
  21272. "\r\n"
  21273. "5\r\nhello\r\n";
  21274. with_single_response(short_chunked, [](Client &cli) {
  21275. auto handle = cli.open_stream("GET", "/");
  21276. ASSERT_TRUE(handle.is_valid());
  21277. read_all(handle);
  21278. EXPECT_TRUE(handle.has_read_error());
  21279. });
  21280. }
  21281. #ifdef CPPHTTPLIB_SSL_ENABLED
  21282. // Serves `response` to one request, then closes with or without a close_notify
  21283. template <typename Fn>
  21284. static void with_single_tls_response(const std::string &response,
  21285. bool close_notify, Fn fn) {
  21286. #ifndef _WIN32
  21287. signal(SIGPIPE, SIG_IGN);
  21288. #endif
  21289. std::promise<int> port_promise;
  21290. auto port_future = port_promise.get_future();
  21291. auto server_thread = std::thread([&port_promise, response, close_notify] {
  21292. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  21293. default_socket_options(srv);
  21294. sockaddr_in addr{};
  21295. addr.sin_family = AF_INET;
  21296. addr.sin_port = htons(0);
  21297. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  21298. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  21299. ::listen(srv, 1) != 0) {
  21300. port_promise.set_value(-1);
  21301. detail::close_socket(srv);
  21302. return;
  21303. }
  21304. socklen_t addr_len = sizeof(addr);
  21305. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  21306. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  21307. auto cli = ::accept(srv, nullptr, nullptr);
  21308. if (cli != INVALID_SOCKET) {
  21309. auto ctx = tls::create_server_context();
  21310. tls::set_server_cert_file(ctx, SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  21311. nullptr);
  21312. auto session = tls::create_session(ctx, cli);
  21313. tls::TlsError err;
  21314. if (tls::accept_nonblocking(session, cli, 5, 0, &err, nullptr)) {
  21315. // The request head first, so that closing the socket sends a FIN
  21316. // rather than an RST for the unread bytes.
  21317. std::string req;
  21318. char buf[256];
  21319. while (req.find("\r\n\r\n") == std::string::npos) {
  21320. auto n = tls::read(session, buf, sizeof(buf), err);
  21321. if (n <= 0) { break; }
  21322. req.append(buf, static_cast<size_t>(n));
  21323. }
  21324. size_t sent = 0;
  21325. while (sent < response.size()) {
  21326. auto n = tls::write(session, response.data() + sent,
  21327. response.size() - sent, err);
  21328. if (n <= 0) { break; }
  21329. sent += static_cast<size_t>(n);
  21330. }
  21331. if (close_notify) { tls::shutdown(session, true); }
  21332. }
  21333. tls::free_session(session);
  21334. detail::close_socket(cli);
  21335. tls::free_context(ctx);
  21336. }
  21337. detail::close_socket(srv);
  21338. });
  21339. auto se = detail::scope_exit([&] { server_thread.join(); });
  21340. auto port = port_future.get();
  21341. ASSERT_GT(port, 0);
  21342. SSLClient cli("127.0.0.1", port);
  21343. cli.enable_server_certificate_verification(false);
  21344. fn(cli);
  21345. }
  21346. // RFC 8446 6.1: a close-delimited body is complete only after a close_notify
  21347. TEST(SSLClientTest, UnframedBodyEndsOnlyAtCloseNotify) {
  21348. const std::string close_delimited = "HTTP/1.1 200 OK\r\n"
  21349. "Connection: close\r\n"
  21350. "\r\n"
  21351. "hello";
  21352. with_single_tls_response(close_delimited, true, [](SSLClient &cli) {
  21353. auto res = cli.Get("/");
  21354. ASSERT_TRUE(res) << to_string(res.error());
  21355. EXPECT_EQ("hello", res->body);
  21356. });
  21357. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21358. auto res = cli.Get("/");
  21359. ASSERT_FALSE(res);
  21360. EXPECT_EQ(Error::Read, res.error());
  21361. });
  21362. with_single_tls_response(close_delimited, false, [](SSLClient &cli) {
  21363. auto handle = cli.open_stream("GET", "/");
  21364. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  21365. read_all(handle);
  21366. EXPECT_TRUE(handle.has_read_error());
  21367. });
  21368. // A framed body ends where its framing says, with or without the alert
  21369. const std::string framed = "HTTP/1.1 200 OK\r\n"
  21370. "Content-Length: 5\r\n"
  21371. "Connection: close\r\n"
  21372. "\r\n"
  21373. "hello";
  21374. with_single_tls_response(framed, false, [](SSLClient &cli) {
  21375. auto res = cli.Get("/");
  21376. ASSERT_TRUE(res) << to_string(res.error());
  21377. EXPECT_EQ("hello", res->body);
  21378. });
  21379. }
  21380. #endif
  21381. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  21382. const char *responses[] = {
  21383. "HTTP/1.1 103 Early Hints\r\n"
  21384. "Link: </style.css>; rel=preload\r\n"
  21385. "\r\n"
  21386. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21387. "HTTP/1.1 100 Continue\r\n"
  21388. "X-Note: interim\r\n"
  21389. "\r\n"
  21390. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  21391. };
  21392. for (auto response : responses) {
  21393. with_single_response(response, [](Client &cli) {
  21394. auto res = cli.Get("/");
  21395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21396. EXPECT_EQ(StatusCode::OK_200, res->status);
  21397. EXPECT_EQ("ok", res->body);
  21398. });
  21399. }
  21400. }
  21401. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  21402. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  21403. const std::string final_response =
  21404. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  21405. std::string interims;
  21406. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  21407. interims += interim;
  21408. }
  21409. with_single_response(interims + final_response, [](Client &cli) {
  21410. auto res = cli.Get("/");
  21411. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21412. EXPECT_EQ("ok", res->body);
  21413. });
  21414. with_single_response(interims + interim + final_response, [](Client &cli) {
  21415. auto res = cli.Get("/");
  21416. ASSERT_FALSE(res);
  21417. EXPECT_EQ(Error::Read, res.error());
  21418. });
  21419. }
  21420. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  21421. #ifndef _WIN32
  21422. signal(SIGPIPE, SIG_IGN);
  21423. #endif
  21424. // The server answers the head without asking for the body. Bytes it then
  21425. // reads on the connection would be taken for the body the request declared.
  21426. auto closed_by_client = false;
  21427. std::promise<int> port_promise;
  21428. auto server_thread = serve_single_response(
  21429. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  21430. [&](socket_t sock) {
  21431. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21432. char buf[256];
  21433. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  21434. });
  21435. Client cli("127.0.0.1", port_promise.get_future().get());
  21436. cli.set_keep_alive(true);
  21437. cli.set_read_timeout(1, 0);
  21438. // Long enough for the client to send Expect: 100-continue.
  21439. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21440. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21441. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21442. cli.Get("/second");
  21443. server_thread.join();
  21444. EXPECT_TRUE(closed_by_client);
  21445. }
  21446. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  21447. // Long enough for the client to send Expect: 100-continue
  21448. with_single_response(
  21449. "HTTP/1.1 103 Early Hints\r\n"
  21450. "Link: </style.css>; rel=preload\r\n"
  21451. "\r\n"
  21452. "HTTP/1.1 401 Unauthorized\r\n"
  21453. "Content-Length: 0\r\n\r\n",
  21454. [](Client &cli) {
  21455. cli.set_read_timeout(2, 0);
  21456. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21457. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21458. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  21459. });
  21460. }
  21461. #ifdef CPPHTTPLIB_SSL_ENABLED
  21462. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  21463. #ifndef _WIN32
  21464. signal(SIGPIPE, SIG_IGN);
  21465. #endif
  21466. auto reused = false;
  21467. std::promise<int> port_promise;
  21468. auto server_thread = serve_single_response(
  21469. port_promise,
  21470. "HTTP/1.1 401 Unauthorized\r\n"
  21471. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  21472. "Content-Length: 0\r\n\r\n",
  21473. [&](socket_t sock) {
  21474. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  21475. char buf[256];
  21476. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  21477. });
  21478. Client cli("127.0.0.1", port_promise.get_future().get());
  21479. cli.set_keep_alive(true);
  21480. cli.set_digest_auth("user", "pass");
  21481. cli.set_read_timeout(1, 0);
  21482. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  21483. server_thread.join();
  21484. EXPECT_FALSE(reused);
  21485. }
  21486. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  21487. // Any other answer to CONNECT would read as the origin's response.
  21488. struct {
  21489. const char *response;
  21490. bool passed_on;
  21491. } cases[] = {
  21492. {"HTTP/1.1 201 Created\r\n"
  21493. "Set-Cookie: session=from-proxy\r\n"
  21494. "Content-Length: 0\r\n\r\n",
  21495. false},
  21496. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  21497. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  21498. "Content-Length: 0\r\n\r\n",
  21499. true},
  21500. };
  21501. for (const auto &c : cases) {
  21502. std::promise<int> port_promise;
  21503. auto server_thread = serve_single_response(port_promise, c.response);
  21504. SSLClient cli("example.com", 443);
  21505. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21506. auto res = cli.Get("/");
  21507. server_thread.join();
  21508. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  21509. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  21510. if (res) {
  21511. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21512. }
  21513. }
  21514. }
  21515. #endif
  21516. // Records the client's error logger calls as "error METHOD path", or
  21517. // "error null" for a call without a request
  21518. static ErrorLogger record_errors(std::vector<std::string> &log) {
  21519. return [&log](const Error &err, const Request *req) {
  21520. log.push_back(to_string(err) + " " +
  21521. (req ? req->method + " " + req->path : "null"));
  21522. };
  21523. }
  21524. // A failed request is reported once, with the request the caller made
  21525. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  21526. Server svr;
  21527. svr.Get("/big", [](const Request &, Response &res) {
  21528. res.set_content(std::string(100000, 'b'), "text/plain");
  21529. });
  21530. auto port = svr.bind_to_any_port(HOST);
  21531. std::thread t([&]() { svr.listen_after_bind(); });
  21532. auto se = detail::scope_exit([&] {
  21533. svr.stop();
  21534. t.join();
  21535. });
  21536. svr.wait_until_ready();
  21537. Client cli(HOST, port);
  21538. std::vector<std::string> log;
  21539. cli.set_error_logger(record_errors(log));
  21540. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  21541. cli.Get("/big", [](const char *, size_t) { return false; });
  21542. EXPECT_EQ(expected, log);
  21543. log.clear();
  21544. cli.Get("/big", [](size_t, size_t) { return false; });
  21545. EXPECT_EQ(expected, log);
  21546. }
  21547. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  21548. // Fails while the body is read
  21549. auto broken = [](const Request &, Response &res) {
  21550. res.set_content_provider(10, "text/plain",
  21551. [](size_t, size_t, DataSink &) { return false; });
  21552. };
  21553. Server other;
  21554. other.Get("/broken", broken);
  21555. auto other_port = other.bind_to_any_port(HOST);
  21556. std::thread other_t([&]() { other.listen_after_bind(); });
  21557. auto other_se = detail::scope_exit([&] {
  21558. other.stop();
  21559. other_t.join();
  21560. });
  21561. other.wait_until_ready();
  21562. Server svr;
  21563. svr.Get("/broken", broken);
  21564. svr.Get("/same-origin",
  21565. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  21566. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  21567. res.set_redirect("http://" + std::string(HOST) + ":" +
  21568. std::to_string(other_port) + "/broken");
  21569. });
  21570. auto port = svr.bind_to_any_port(HOST);
  21571. std::thread t([&]() { svr.listen_after_bind(); });
  21572. auto se = detail::scope_exit([&] {
  21573. svr.stop();
  21574. t.join();
  21575. });
  21576. svr.wait_until_ready();
  21577. Client cli(HOST, port);
  21578. cli.set_follow_location(true);
  21579. std::vector<std::string> log;
  21580. cli.set_error_logger(record_errors(log));
  21581. for (auto path : {"/same-origin", "/cross-origin"}) {
  21582. log.clear();
  21583. auto res = cli.Get(path);
  21584. ASSERT_FALSE(res);
  21585. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  21586. log);
  21587. }
  21588. }
  21589. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  21590. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  21591. std::vector<std::string> log;
  21592. cli.set_error_logger(record_errors(log));
  21593. auto handle = cli.open_stream("GET", "/x");
  21594. EXPECT_FALSE(handle.is_valid());
  21595. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  21596. log);
  21597. });
  21598. }
  21599. #ifdef CPPHTTPLIB_SSL_ENABLED
  21600. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  21601. // Not a TLS server, so the handshake fails. It waits for a request line in
  21602. // the handshake bytes, so a short read timeout lets it close quickly.
  21603. Server svr;
  21604. svr.set_read_timeout(0, 100000);
  21605. svr.Get("/x", [](const Request &, Response &res) {
  21606. res.set_content("x", "text/plain");
  21607. });
  21608. auto port = svr.bind_to_any_port(HOST);
  21609. std::thread t([&]() { svr.listen_after_bind(); });
  21610. auto se = detail::scope_exit([&] {
  21611. svr.stop();
  21612. t.join();
  21613. });
  21614. svr.wait_until_ready();
  21615. std::vector<std::string> log;
  21616. SSLClient cli(HOST, port);
  21617. cli.enable_server_certificate_verification(false);
  21618. cli.set_error_logger(record_errors(log));
  21619. auto res = cli.Get("/x");
  21620. ASSERT_FALSE(res);
  21621. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21622. log.clear();
  21623. auto handle = cli.open_stream("GET", "/x");
  21624. EXPECT_FALSE(handle.is_valid());
  21625. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  21626. log.clear();
  21627. SSLClient no_ca(HOST, port);
  21628. no_ca.set_ca_cert_path("./no-such-ca.pem");
  21629. no_ca.set_error_logger(record_errors(log));
  21630. res = no_ca.Get("/x");
  21631. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  21632. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  21633. }
  21634. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  21635. #ifndef _WIN32
  21636. signal(SIGPIPE, SIG_IGN);
  21637. #endif
  21638. // Refused, answered with a challenge, or closed without an answer
  21639. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  21640. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  21641. "Content-Length: 0\r\n\r\n",
  21642. ""}) {
  21643. std::promise<int> port_promise;
  21644. auto server_thread = serve_single_response(port_promise, response);
  21645. SSLClient cli("example.com", 443);
  21646. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  21647. std::vector<std::string> log;
  21648. cli.set_error_logger(record_errors(log));
  21649. auto res = cli.Get("/");
  21650. server_thread.join();
  21651. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  21652. << response;
  21653. }
  21654. }
  21655. #endif
  21656. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  21657. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  21658. // the chunked coding and drop Content-Length, so a front-end that trusts
  21659. // Content-Length would disagree about where the body ends (response
  21660. // smuggling). The client must reject such a response.
  21661. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21662. for (const char *te : {"chunked", "gzip, chunked"}) {
  21663. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  21664. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  21665. "\r\n" + "Connection: close\r\n" + "\r\n" +
  21666. "5\r\nhello\r\n0\r\n\r\n";
  21667. with_single_response(response, [&](Client &cli) {
  21668. auto res = cli.Get("/");
  21669. EXPECT_FALSE(static_cast<bool>(res)) << te;
  21670. EXPECT_EQ(Error::Read, res.error()) << te;
  21671. });
  21672. with_single_response(response, [&](Client &cli) {
  21673. auto handle = cli.open_stream("GET", "/");
  21674. EXPECT_FALSE(handle.is_valid()) << te;
  21675. EXPECT_EQ(Error::Read, handle.error) << te;
  21676. });
  21677. }
  21678. }
  21679. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  21680. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  21681. // closing the connection (unlike a request, which must be rejected).
  21682. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  21683. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21684. "Transfer-Encoding: chunked\r\n"
  21685. "Connection: close\r\n"
  21686. "\r\n"
  21687. "5\r\nhello\r\n0\r\n\r\n",
  21688. "HTTP/1.1 200 OK\r\n"
  21689. "Transfer-Encoding: gzip\r\n"
  21690. "Connection: close\r\n"
  21691. "\r\n"
  21692. "hello"}) {
  21693. with_single_response(response, [&](Client &cli) {
  21694. auto res = cli.Get("/");
  21695. ASSERT_TRUE(static_cast<bool>(res)) << response;
  21696. EXPECT_EQ("hello", res->body);
  21697. });
  21698. with_single_response(response, [&](Client &cli) {
  21699. auto handle = cli.open_stream("GET", "/");
  21700. ASSERT_TRUE(handle.is_valid()) << response;
  21701. EXPECT_EQ("hello", read_all(handle));
  21702. });
  21703. }
  21704. }
  21705. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  21706. // framing headers describe nothing to read and must not be rejected.
  21707. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  21708. const std::string framing = "Content-Length: 5\r\n"
  21709. "Transfer-Encoding: chunked\r\n"
  21710. "Connection: close\r\n"
  21711. "\r\n";
  21712. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21713. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  21714. });
  21715. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  21716. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  21717. });
  21718. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  21719. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  21720. with_single_response(response, [&](Client &cli) {
  21721. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  21722. });
  21723. with_single_response(response, [&](Client &cli) {
  21724. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  21725. });
  21726. }
  21727. }
  21728. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  21729. // header section, so a stream opened on one has nothing to read, whatever
  21730. // framing or coding headers it carries.
  21731. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  21732. struct Case {
  21733. const char *method;
  21734. const char *status;
  21735. };
  21736. // A reader of the declared body reports an early close when nothing
  21737. // follows, and hands back what does.
  21738. struct Framing {
  21739. const char *headers;
  21740. const char *after;
  21741. };
  21742. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  21743. Case{"GET", "304 Not Modified"}}) {
  21744. for (const auto &f :
  21745. {Framing{"Content-Length: 5\r\n", ""},
  21746. Framing{"Content-Length: 5\r\n", "hello"},
  21747. Framing{"Transfer-Encoding: chunked\r\n", ""},
  21748. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  21749. // Not decoded, so a build without Brotli opens it too
  21750. Framing{"Content-Encoding: br\r\n", ""}}) {
  21751. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  21752. "Connection: close\r\n"
  21753. "\r\n" +
  21754. f.after;
  21755. with_single_response(response, [&](Client &cli) {
  21756. auto handle = cli.open_stream(c.method, "/");
  21757. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  21758. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  21759. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  21760. });
  21761. }
  21762. }
  21763. }
  21764. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  21765. // response, is faulty framing, so the connection is not reused after it.
  21766. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  21767. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21768. "Content-Length: 0\r\n"
  21769. "Transfer-Encoding: chunked\r\n"
  21770. "\r\n"
  21771. "5\r\nhello\r\n0\r\n\r\n",
  21772. "HTTP/1.0 200 Connection established\r\n"
  21773. "Connection: keep-alive\r\n"
  21774. "Transfer-Encoding: chunked\r\n"
  21775. "\r\n"
  21776. "5\r\nhello\r\n0\r\n\r\n"}) {
  21777. with_single_response(response, [&](Client &cli) {
  21778. cli.set_keep_alive(true);
  21779. auto res = cli.Get("/");
  21780. ASSERT_TRUE(res) << response;
  21781. EXPECT_EQ("hello", res->body);
  21782. EXPECT_FALSE(cli.is_socket_open()) << response;
  21783. });
  21784. }
  21785. }
  21786. // A payload max length of 0 means no limit, however the body is framed.
  21787. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  21788. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  21789. "Transfer-Encoding: chunked\r\n"
  21790. "\r\n"
  21791. "5\r\nhello\r\n0\r\n\r\n",
  21792. "HTTP/1.1 200 OK\r\n"
  21793. "Connection: close\r\n"
  21794. "\r\n"
  21795. "hello"}) {
  21796. with_single_response(response, [&](Client &cli) {
  21797. cli.set_payload_max_length(0);
  21798. auto res = cli.Get("/");
  21799. ASSERT_TRUE(res) << response;
  21800. EXPECT_EQ("hello", res->body) << response;
  21801. });
  21802. }
  21803. }
  21804. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  21805. Server svr;
  21806. svr.set_payload_max_length(0);
  21807. svr.Post("/echo", [](const Request &req, Response &res) {
  21808. res.set_content(req.body, "text/plain");
  21809. });
  21810. auto port = svr.bind_to_any_port(HOST);
  21811. thread t = thread([&] { svr.listen_after_bind(); });
  21812. auto se = detail::scope_exit([&] {
  21813. svr.stop();
  21814. t.join();
  21815. ASSERT_FALSE(svr.is_running());
  21816. });
  21817. svr.wait_until_ready();
  21818. Client cli(HOST, port);
  21819. auto res = cli.Post(
  21820. "/echo",
  21821. [](size_t /*offset*/, DataSink &sink) {
  21822. sink.write("hello", 5);
  21823. sink.done();
  21824. return true;
  21825. },
  21826. "text/plain");
  21827. ASSERT_TRUE(res);
  21828. EXPECT_EQ(StatusCode::OK_200, res->status);
  21829. EXPECT_EQ("hello", res->body);
  21830. }
  21831. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  21832. TEST_F(OpenStreamTest, Gzip) {
  21833. Client cli("127.0.0.1", port_);
  21834. auto handle = cli.open_stream("GET", "/compressible", {},
  21835. {{"Accept-Encoding", "gzip"}});
  21836. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21837. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21838. }
  21839. TEST_F(OpenStreamTest, TrailersWithGzip) {
  21840. Client cli("127.0.0.1", port_);
  21841. auto handle =
  21842. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  21843. {{"Accept-Encoding", "gzip"}});
  21844. ASSERT_TRUE(handle.is_valid());
  21845. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  21846. EXPECT_EQ("123456789", read_all(handle));
  21847. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  21848. }
  21849. #endif
  21850. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  21851. TEST_F(OpenStreamTest, Brotli) {
  21852. Client cli("127.0.0.1", port_);
  21853. auto handle =
  21854. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  21855. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  21856. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21857. }
  21858. #endif
  21859. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  21860. TEST_F(OpenStreamTest, Zstd) {
  21861. Client cli("127.0.0.1", port_);
  21862. auto handle = cli.open_stream("GET", "/compressible", {},
  21863. {{"Accept-Encoding", "zstd"}});
  21864. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  21865. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  21866. }
  21867. #endif
  21868. #ifdef CPPHTTPLIB_SSL_ENABLED
  21869. class SSLOpenStreamTest : public ::testing::Test {
  21870. protected:
  21871. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  21872. void SetUp() override {
  21873. svr_.Get("/hello", [](const Request &, Response &res) {
  21874. res.set_content("Hello SSL World!", "text/plain");
  21875. });
  21876. svr_.Get("/chunked", [](const Request &, Response &res) {
  21877. res.set_chunked_content_provider("text/plain",
  21878. [](size_t offset, DataSink &sink) {
  21879. if (offset < 15) {
  21880. sink.write("chunk", 5);
  21881. return true;
  21882. }
  21883. sink.done();
  21884. return true;
  21885. });
  21886. });
  21887. svr_.Post("/echo", [](const Request &req, Response &res) {
  21888. res.set_content(req.body, req.get_header_value("Content-Type"));
  21889. });
  21890. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  21891. std::string body = req.body;
  21892. res.set_chunked_content_provider(
  21893. "text/plain", [body](size_t offset, DataSink &sink) {
  21894. if (offset < body.size()) {
  21895. sink.write(body.data() + offset, body.size() - offset);
  21896. }
  21897. sink.done();
  21898. return true;
  21899. });
  21900. });
  21901. port_ = svr_.bind_to_any_port("127.0.0.1");
  21902. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  21903. svr_.wait_until_ready();
  21904. }
  21905. void TearDown() override {
  21906. svr_.stop();
  21907. if (thread_.joinable()) thread_.join();
  21908. }
  21909. SSLServer svr_;
  21910. std::thread thread_;
  21911. int port_ = 0;
  21912. };
  21913. TEST_F(SSLOpenStreamTest, Basic) {
  21914. SSLClient cli("127.0.0.1", port_);
  21915. cli.enable_server_certificate_verification(false);
  21916. auto handle = cli.open_stream("GET", "/hello");
  21917. ASSERT_TRUE(handle.is_valid());
  21918. EXPECT_EQ("Hello SSL World!", read_all(handle));
  21919. }
  21920. TEST_F(SSLOpenStreamTest, Chunked) {
  21921. SSLClient cli("127.0.0.1", port_);
  21922. cli.enable_server_certificate_verification(false);
  21923. auto handle = cli.open_stream("GET", "/chunked");
  21924. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21925. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  21926. "Transfer-Encoding") == "chunked");
  21927. auto body = read_all(handle);
  21928. EXPECT_EQ("chunkchunkchunk", body);
  21929. }
  21930. TEST_F(SSLOpenStreamTest, Post) {
  21931. SSLClient cli("127.0.0.1", port_);
  21932. cli.enable_server_certificate_verification(false);
  21933. auto handle =
  21934. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  21935. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  21936. EXPECT_EQ(200, handle.response->status);
  21937. auto body = read_all(handle);
  21938. EXPECT_EQ("Hello SSL POST", body);
  21939. }
  21940. TEST_F(SSLOpenStreamTest, PostChunked) {
  21941. SSLClient cli("127.0.0.1", port_);
  21942. cli.enable_server_certificate_verification(false);
  21943. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  21944. "Chunked SSL Data", "text/plain");
  21945. ASSERT_TRUE(handle.is_valid());
  21946. EXPECT_EQ(200, handle.response->status);
  21947. auto body = read_all(handle);
  21948. EXPECT_EQ("Chunked SSL Data", body);
  21949. }
  21950. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  21951. // Content-Length is terminated by the server closing the connection. When the
  21952. // SSL peer sends a close_notify after the body, the client must treat it as a
  21953. // clean EOF and return a successful response rather than an error.
  21954. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  21955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21956. ASSERT_TRUE(svr.is_valid());
  21957. svr.set_keep_alive_max_count(1);
  21958. const std::string expected_body = "Hello from connection-close response!";
  21959. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21960. res.set_content_provider("text/plain",
  21961. [&](size_t offset, DataSink &sink) -> bool {
  21962. if (offset < expected_body.size()) {
  21963. sink.write(expected_body.data() + offset,
  21964. expected_body.size() - offset);
  21965. }
  21966. sink.done();
  21967. return true;
  21968. });
  21969. });
  21970. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  21971. auto se = detail::scope_exit([&] {
  21972. svr.stop();
  21973. listen_thread.join();
  21974. ASSERT_FALSE(svr.is_running());
  21975. });
  21976. svr.wait_until_ready();
  21977. SSLClient cli(HOST, PORT);
  21978. cli.enable_server_certificate_verification(false);
  21979. auto res = cli.Get("/no-content-length");
  21980. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  21981. EXPECT_EQ(StatusCode::OK_200, res->status);
  21982. EXPECT_EQ(expected_body, res->body);
  21983. }
  21984. // Without Content-Length, the full buffer size reaches tls::read().
  21985. TEST(SSLTest, ReadIntoBufferOverIntMax) {
  21986. if (sizeof(size_t) <= sizeof(int)) {
  21987. GTEST_SKIP() << "size_t cannot exceed INT_MAX here";
  21988. }
  21989. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  21990. ASSERT_TRUE(svr.is_valid());
  21991. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  21992. res.set_content_provider("text/plain",
  21993. [&](size_t offset, DataSink &sink) -> bool {
  21994. if (offset == 0) { sink.write("Hello", 5); }
  21995. sink.done();
  21996. return true;
  21997. });
  21998. });
  21999. auto port = svr.bind_to_any_port(HOST);
  22000. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  22001. auto se = detail::scope_exit([&] {
  22002. svr.stop();
  22003. listen_thread.join();
  22004. });
  22005. svr.wait_until_ready();
  22006. SSLClient cli(HOST, port);
  22007. cli.enable_server_certificate_verification(false);
  22008. auto handle = cli.open_stream("GET", "/no-content-length");
  22009. ASSERT_TRUE(handle.is_valid()) << to_string(handle.error);
  22010. const auto len = static_cast<size_t>((std::numeric_limits<int>::max)()) + 1;
  22011. std::unique_ptr<char[]> buf(new char[len]);
  22012. std::string body;
  22013. ssize_t n;
  22014. while ((n = handle.read(buf.get(), len)) > 0) {
  22015. body.append(buf.get(), static_cast<size_t>(n));
  22016. }
  22017. EXPECT_EQ(0, n);
  22018. EXPECT_EQ("Hello", body);
  22019. }
  22020. #endif // CPPHTTPLIB_SSL_ENABLED
  22021. //==============================================================================
  22022. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  22023. // results for various scenarios.
  22024. //==============================================================================
  22025. TEST(ParityTest, GetVsOpenStream) {
  22026. Server svr;
  22027. const std::string path = "/parity";
  22028. const std::string content = "Parity test content: hello world";
  22029. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22030. res.set_content(content, "text/plain");
  22031. });
  22032. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22033. auto se = detail::scope_exit([&] {
  22034. svr.stop();
  22035. t.join();
  22036. ASSERT_FALSE(svr.is_running());
  22037. });
  22038. svr.wait_until_ready();
  22039. Client cli(HOST, PORT);
  22040. // Non-stream path
  22041. auto r1 = cli.Get(path);
  22042. ASSERT_TRUE(r1);
  22043. EXPECT_EQ(StatusCode::OK_200, r1->status);
  22044. // Stream path
  22045. auto h = cli.open_stream("GET", path);
  22046. ASSERT_TRUE(h.is_valid());
  22047. EXPECT_EQ(r1->body, read_all(h));
  22048. }
  22049. // Helper to compress data with provided compressor type T
  22050. template <typename Compressor>
  22051. static std::string compress_payload_for_parity(const std::string &in) {
  22052. std::string out;
  22053. Compressor compressor;
  22054. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  22055. [&](const char *data, size_t n) {
  22056. out.append(data, n);
  22057. return true;
  22058. });
  22059. EXPECT_TRUE(ok);
  22060. return out;
  22061. }
  22062. // Helper function for compression parity tests
  22063. template <typename Compressor>
  22064. static void test_compression_parity(const std::string &original,
  22065. const std::string &path,
  22066. const std::string &encoding) {
  22067. const std::string compressed =
  22068. compress_payload_for_parity<Compressor>(original);
  22069. Server svr;
  22070. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  22071. res.set_content(compressed, "application/octet-stream");
  22072. res.set_header("Content-Encoding", encoding);
  22073. });
  22074. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  22075. auto se = detail::scope_exit([&] {
  22076. svr.stop();
  22077. t.join();
  22078. ASSERT_FALSE(svr.is_running());
  22079. });
  22080. svr.wait_until_ready();
  22081. Client cli(HOST, PORT);
  22082. // Non-streaming
  22083. {
  22084. auto res = cli.Get(path);
  22085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22086. EXPECT_EQ(StatusCode::OK_200, res->status);
  22087. EXPECT_EQ(original, res->body);
  22088. }
  22089. // Streaming
  22090. {
  22091. auto h = cli.open_stream("GET", path);
  22092. ASSERT_TRUE(h.is_valid());
  22093. EXPECT_EQ(original, read_all(h));
  22094. }
  22095. }
  22096. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22097. TEST(ParityTest, Gzip) {
  22098. test_compression_parity<detail::gzip_compressor>(
  22099. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  22100. }
  22101. #endif
  22102. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  22103. TEST(ParityTest, Brotli) {
  22104. test_compression_parity<detail::brotli_compressor>(
  22105. "Hello, brotli parity test payload", "/parity-br", "br");
  22106. }
  22107. #endif
  22108. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  22109. TEST(ParityTest, Zstd) {
  22110. test_compression_parity<detail::zstd_compressor>(
  22111. "Zstandard parity test payload", "/parity-zstd", "zstd");
  22112. }
  22113. #endif
  22114. //==============================================================================
  22115. // New Stream API Tests
  22116. //==============================================================================
  22117. inline std::string read_body(httplib::stream::Result &result) {
  22118. std::string body;
  22119. while (result.next()) {
  22120. body.append(result.data(), result.size());
  22121. }
  22122. return body;
  22123. }
  22124. TEST(ClientConnectionTest, Basic) {
  22125. httplib::ClientConnection conn;
  22126. EXPECT_FALSE(conn.is_open());
  22127. conn.sock = 1;
  22128. EXPECT_TRUE(conn.is_open());
  22129. httplib::ClientConnection conn2(std::move(conn));
  22130. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  22131. conn2.sock = INVALID_SOCKET;
  22132. }
  22133. // Unified test server for all stream::* tests
  22134. class StreamApiTest : public ::testing::Test {
  22135. protected:
  22136. void SetUp() override {
  22137. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22138. res.set_content("Hello World!", "text/plain");
  22139. });
  22140. svr_.Get("/echo-params",
  22141. [](const httplib::Request &req, httplib::Response &res) {
  22142. std::string r;
  22143. for (const auto &p : req.params) {
  22144. if (!r.empty()) r += "&";
  22145. r += p.first + "=" + p.second;
  22146. }
  22147. res.set_content(r, "text/plain");
  22148. });
  22149. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22150. res.set_content(req.body, req.get_header_value("Content-Type"));
  22151. });
  22152. svr_.Post("/echo-headers",
  22153. [](const httplib::Request &req, httplib::Response &res) {
  22154. std::string r;
  22155. for (const auto &h : req.headers)
  22156. r += h.first + ": " + h.second + "\n";
  22157. res.set_content(r, "text/plain");
  22158. });
  22159. svr_.Post("/echo-params",
  22160. [](const httplib::Request &req, httplib::Response &res) {
  22161. std::string r = "params:";
  22162. for (const auto &p : req.params)
  22163. r += p.first + "=" + p.second + ";";
  22164. res.set_content(r + " body:" + req.body, "text/plain");
  22165. });
  22166. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  22167. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  22168. });
  22169. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22170. res.set_content("PUT:" + req.body, "text/plain");
  22171. });
  22172. svr_.Patch("/echo",
  22173. [](const httplib::Request &req, httplib::Response &res) {
  22174. res.set_content("PATCH:" + req.body, "text/plain");
  22175. });
  22176. svr_.Delete(
  22177. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  22178. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  22179. "text/plain");
  22180. });
  22181. svr_.Get("/head-test",
  22182. [](const httplib::Request &, httplib::Response &res) {
  22183. res.set_content("body for HEAD", "text/plain");
  22184. });
  22185. svr_.Options("/options",
  22186. [](const httplib::Request &, httplib::Response &res) {
  22187. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  22188. });
  22189. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  22190. svr_.wait_until_ready();
  22191. }
  22192. void TearDown() override {
  22193. svr_.stop();
  22194. if (thread_.joinable()) thread_.join();
  22195. }
  22196. httplib::Server svr_;
  22197. std::thread thread_;
  22198. };
  22199. // stream::Get tests
  22200. TEST_F(StreamApiTest, GetBasic) {
  22201. httplib::Client cli(HOST, PORT);
  22202. auto result = httplib::stream::Get(cli, "/hello");
  22203. ASSERT_TRUE(result.is_valid());
  22204. EXPECT_EQ(200, result.status());
  22205. EXPECT_EQ("Hello World!", read_body(result));
  22206. }
  22207. TEST_F(StreamApiTest, GetWithParams) {
  22208. httplib::Client cli(HOST, PORT);
  22209. httplib::Params params{{"foo", "bar"}};
  22210. auto result = httplib::stream::Get(cli, "/echo-params", params);
  22211. ASSERT_TRUE(result.is_valid());
  22212. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  22213. }
  22214. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22215. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  22216. httplib::Client cli(HOST, PORT);
  22217. cli.set_payload_max_length(0);
  22218. auto result = httplib::stream::Get(cli, "/hello");
  22219. ASSERT_TRUE(result.is_valid());
  22220. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  22221. EXPECT_EQ("Hello World!", read_body(result));
  22222. }
  22223. #endif
  22224. TEST_F(StreamApiTest, GetConnectionError) {
  22225. httplib::Client cli(HOST, 9999);
  22226. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  22227. }
  22228. TEST_F(StreamApiTest, Get404) {
  22229. httplib::Client cli(HOST, PORT);
  22230. auto result = httplib::stream::Get(cli, "/nonexistent");
  22231. EXPECT_TRUE(result.is_valid());
  22232. EXPECT_EQ(404, result.status());
  22233. }
  22234. // stream::Post tests
  22235. TEST_F(StreamApiTest, PostBasic) {
  22236. httplib::Client cli(HOST, PORT);
  22237. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  22238. "application/json");
  22239. ASSERT_TRUE(result.is_valid());
  22240. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  22241. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  22242. }
  22243. TEST_F(StreamApiTest, PostWithHeaders) {
  22244. httplib::Client cli(HOST, PORT);
  22245. httplib::Headers headers{{"X-Custom", "value"}};
  22246. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  22247. "text/plain");
  22248. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  22249. }
  22250. TEST_F(StreamApiTest, PostWithParams) {
  22251. httplib::Client cli(HOST, PORT);
  22252. httplib::Params params{{"k", "v"}};
  22253. auto result =
  22254. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  22255. auto body = read_body(result);
  22256. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  22257. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  22258. }
  22259. TEST_F(StreamApiTest, PostLarge) {
  22260. httplib::Client cli(HOST, PORT);
  22261. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  22262. size_t total = 0;
  22263. while (result.next()) {
  22264. total += result.size();
  22265. }
  22266. EXPECT_EQ(100u * 1024u, total);
  22267. }
  22268. // stream::Put/Patch tests
  22269. TEST_F(StreamApiTest, PutAndPatch) {
  22270. httplib::Client cli(HOST, PORT);
  22271. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  22272. EXPECT_EQ("PUT:test", read_body(put));
  22273. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  22274. EXPECT_EQ("PATCH:test", read_body(patch));
  22275. }
  22276. // stream::Delete tests
  22277. TEST_F(StreamApiTest, Delete) {
  22278. httplib::Client cli(HOST, PORT);
  22279. auto del1 = httplib::stream::Delete(cli, "/resource");
  22280. EXPECT_EQ("Deleted", read_body(del1));
  22281. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  22282. EXPECT_EQ("Deleted:data", read_body(del2));
  22283. }
  22284. // stream::Head/Options tests
  22285. TEST_F(StreamApiTest, HeadAndOptions) {
  22286. httplib::Client cli(HOST, PORT);
  22287. auto head = httplib::stream::Head(cli, "/head-test");
  22288. EXPECT_TRUE(head.is_valid());
  22289. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  22290. auto opts = httplib::stream::Options(cli, "/options");
  22291. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  22292. }
  22293. // SSL stream::* tests
  22294. #ifdef CPPHTTPLIB_SSL_ENABLED
  22295. class SSLStreamApiTest : public ::testing::Test {
  22296. protected:
  22297. void SetUp() override {
  22298. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  22299. res.set_content("Hello SSL!", "text/plain");
  22300. });
  22301. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  22302. res.set_content(req.body, "text/plain");
  22303. });
  22304. port_ = svr_.bind_to_any_port("127.0.0.1");
  22305. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  22306. svr_.wait_until_ready();
  22307. }
  22308. void TearDown() override {
  22309. svr_.stop();
  22310. if (thread_.joinable()) thread_.join();
  22311. }
  22312. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  22313. std::thread thread_;
  22314. int port_ = 0;
  22315. };
  22316. TEST_F(SSLStreamApiTest, GetAndPost) {
  22317. httplib::SSLClient cli("127.0.0.1", port_);
  22318. cli.enable_server_certificate_verification(false);
  22319. auto get = httplib::stream::Get(cli, "/hello");
  22320. EXPECT_EQ("Hello SSL!", read_body(get));
  22321. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  22322. EXPECT_EQ("test", read_body(post));
  22323. }
  22324. #endif
  22325. // Tests for Error::Timeout and Error::ConnectionClosed error types
  22326. // These errors are set in SocketStream/SSLSocketStream and propagated through
  22327. // BodyReader
  22328. TEST(ErrorHandlingTest, StreamReadTimeout) {
  22329. // Test that read timeout during streaming is detected
  22330. // Use a large content-length response where server delays mid-stream
  22331. Server svr;
  22332. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22333. // Send a large response with delay in the middle
  22334. res.set_content_provider(
  22335. 1000, // content_length
  22336. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  22337. if (offset < 100) {
  22338. // Send first 100 bytes immediately
  22339. std::string data(100, 'A');
  22340. sink.write(data.c_str(), data.size());
  22341. return true;
  22342. }
  22343. // Then delay longer than client timeout
  22344. std::this_thread::sleep_for(std::chrono::seconds(3));
  22345. std::string data(900, 'B');
  22346. sink.write(data.c_str(), data.size());
  22347. return true;
  22348. });
  22349. });
  22350. auto port = 8091;
  22351. std::thread t([&]() { svr.listen("localhost", port); });
  22352. svr.wait_until_ready();
  22353. Client cli("localhost", port);
  22354. cli.set_read_timeout(1, 0); // 1 second timeout
  22355. auto handle = cli.open_stream("GET", "/slow-stream");
  22356. ASSERT_TRUE(handle.is_valid());
  22357. char buf[256];
  22358. ssize_t total = 0;
  22359. ssize_t n;
  22360. bool got_error = false;
  22361. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22362. total += n;
  22363. }
  22364. if (n < 0) {
  22365. got_error = true;
  22366. // Should be timeout or read error
  22367. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22368. handle.get_read_error() == Error::Read)
  22369. << "Actual error: " << to_string(handle.get_read_error());
  22370. }
  22371. // Either we got an error, or we got less data than expected
  22372. EXPECT_TRUE(got_error || total < 1000)
  22373. << "Expected timeout but got all " << total << " bytes";
  22374. svr.stop();
  22375. t.join();
  22376. }
  22377. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  22378. // Test connection closed detection via BodyReader
  22379. Server svr;
  22380. std::atomic<bool> close_now{false};
  22381. svr.Get("/will-close", [&](const Request &, Response &res) {
  22382. res.set_content_provider(
  22383. 10000, // Large content_length that we won't fully send
  22384. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22385. if (offset < 100) {
  22386. std::string data(100, 'X');
  22387. sink.write(data.c_str(), data.size());
  22388. return true;
  22389. }
  22390. // Wait for signal then abort
  22391. while (!close_now) {
  22392. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22393. }
  22394. return false; // Abort - server will close connection
  22395. });
  22396. });
  22397. auto port = 8092;
  22398. std::thread t([&]() { svr.listen("localhost", port); });
  22399. svr.wait_until_ready();
  22400. Client cli("localhost", port);
  22401. auto handle = cli.open_stream("GET", "/will-close");
  22402. ASSERT_TRUE(handle.is_valid());
  22403. char buf[256];
  22404. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22405. EXPECT_GT(n, 0) << "First read should succeed";
  22406. // Signal server to close
  22407. close_now = true;
  22408. // Keep reading until error or EOF
  22409. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22410. // Keep reading
  22411. }
  22412. // Should get an error since content_length wasn't satisfied
  22413. if (n < 0) {
  22414. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22415. handle.get_read_error() == Error::Read)
  22416. << "Actual error: " << to_string(handle.get_read_error());
  22417. }
  22418. svr.stop();
  22419. t.join();
  22420. }
  22421. #ifdef CPPHTTPLIB_SSL_ENABLED
  22422. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  22423. // Test that read timeout during SSL streaming is detected
  22424. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22425. svr.Get("/slow-stream", [](const Request &, Response &res) {
  22426. res.set_content_provider(
  22427. 1000, "text/plain",
  22428. [](size_t offset, size_t /*length*/, DataSink &sink) {
  22429. if (offset < 100) {
  22430. std::string data(100, 'A');
  22431. sink.write(data.c_str(), data.size());
  22432. return true;
  22433. }
  22434. std::this_thread::sleep_for(std::chrono::seconds(3));
  22435. std::string data(900, 'B');
  22436. sink.write(data.c_str(), data.size());
  22437. return true;
  22438. });
  22439. });
  22440. auto port = 8093;
  22441. std::thread t([&]() { svr.listen("localhost", port); });
  22442. svr.wait_until_ready();
  22443. SSLClient cli("localhost", port);
  22444. cli.enable_server_certificate_verification(false);
  22445. cli.set_read_timeout(1, 0); // 1 second timeout
  22446. auto handle = cli.open_stream("GET", "/slow-stream");
  22447. ASSERT_TRUE(handle.is_valid());
  22448. char buf[256];
  22449. ssize_t total = 0;
  22450. ssize_t n;
  22451. bool got_error = false;
  22452. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22453. total += n;
  22454. }
  22455. if (n < 0) {
  22456. got_error = true;
  22457. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  22458. handle.get_read_error() == Error::Read)
  22459. << "Actual error: " << to_string(handle.get_read_error());
  22460. }
  22461. EXPECT_TRUE(got_error || total < 1000)
  22462. << "Expected timeout but got all " << total << " bytes";
  22463. svr.stop();
  22464. t.join();
  22465. }
  22466. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  22467. // Test SSL connection closed detection
  22468. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22469. std::atomic<bool> close_now{false};
  22470. svr.Get("/will-close", [&](const Request &, Response &res) {
  22471. res.set_content_provider(
  22472. 10000, "text/plain",
  22473. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  22474. if (offset < 100) {
  22475. std::string data(100, 'X');
  22476. sink.write(data.c_str(), data.size());
  22477. return true;
  22478. }
  22479. while (!close_now) {
  22480. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22481. }
  22482. return false;
  22483. });
  22484. });
  22485. auto port = 8094;
  22486. std::thread t([&]() { svr.listen("localhost", port); });
  22487. svr.wait_until_ready();
  22488. SSLClient cli("localhost", port);
  22489. cli.enable_server_certificate_verification(false);
  22490. auto handle = cli.open_stream("GET", "/will-close");
  22491. ASSERT_TRUE(handle.is_valid());
  22492. char buf[256];
  22493. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  22494. EXPECT_GT(n, 0);
  22495. // Signal server to close
  22496. close_now = true;
  22497. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  22498. // Keep reading
  22499. }
  22500. if (n < 0) {
  22501. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  22502. handle.get_read_error() == Error::Read)
  22503. << "Actual error: " << to_string(handle.get_read_error());
  22504. }
  22505. svr.stop();
  22506. t.join();
  22507. }
  22508. #endif
  22509. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  22510. using namespace httplib;
  22511. // Create a test file
  22512. const char *fname = "etag_testfile.txt";
  22513. const char *content = "etag-content";
  22514. {
  22515. std::ofstream ofs(fname);
  22516. ofs << content;
  22517. ASSERT_TRUE(ofs.good());
  22518. }
  22519. Server svr;
  22520. svr.set_mount_point("/static", ".");
  22521. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22522. svr.wait_until_ready();
  22523. Client cli(HOST, PORT);
  22524. // First request: should get 200 with ETag header
  22525. auto res1 = cli.Get("/static/etag_testfile.txt");
  22526. ASSERT_TRUE(res1);
  22527. ASSERT_EQ(200, res1->status);
  22528. ASSERT_TRUE(res1->has_header("ETag"));
  22529. std::string etag = res1->get_header_value("ETag");
  22530. EXPECT_FALSE(etag.empty());
  22531. // Verify ETag format: W/"hex-hex"
  22532. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  22533. EXPECT_EQ('W', etag[0]);
  22534. EXPECT_EQ('/', etag[1]);
  22535. EXPECT_EQ('"', etag[2]);
  22536. EXPECT_EQ('"', etag.back());
  22537. // Exact match: expect 304 Not Modified
  22538. Headers h2 = {{"If-None-Match", etag}};
  22539. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  22540. ASSERT_TRUE(res2);
  22541. EXPECT_EQ(304, res2->status);
  22542. // Wildcard match: expect 304 Not Modified
  22543. Headers h3 = {{"If-None-Match", "*"}};
  22544. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  22545. ASSERT_TRUE(res3);
  22546. EXPECT_EQ(304, res3->status);
  22547. // Non-matching ETag: expect 200
  22548. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  22549. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  22550. ASSERT_TRUE(res4);
  22551. EXPECT_EQ(200, res4->status);
  22552. // Multiple ETags with one matching: expect 304
  22553. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  22554. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  22555. ASSERT_TRUE(res5);
  22556. EXPECT_EQ(304, res5->status);
  22557. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  22558. // that equivalent to the single comma-separated list above, so the match on
  22559. // the second line must still be found.
  22560. Headers h6;
  22561. h6.emplace("If-None-Match", "W/\"other\"");
  22562. h6.emplace("If-None-Match", etag);
  22563. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  22564. ASSERT_TRUE(res6);
  22565. EXPECT_EQ(304, res6->status);
  22566. svr.stop();
  22567. t.join();
  22568. std::remove(fname);
  22569. }
  22570. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  22571. using namespace httplib;
  22572. Server svr;
  22573. svr.set_mount_point("/static", ".");
  22574. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22575. svr.wait_until_ready();
  22576. Client cli(HOST, PORT);
  22577. // Send If-None-Match: * to a non-existent file
  22578. Headers h = {{"If-None-Match", "*"}};
  22579. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  22580. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22581. EXPECT_EQ(404, res->status);
  22582. svr.stop();
  22583. t.join();
  22584. }
  22585. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  22586. using namespace httplib;
  22587. // Create a test file
  22588. const char *fname = "etag_boundary_testfile.txt";
  22589. const char *content = "boundary-test";
  22590. {
  22591. std::ofstream ofs(fname);
  22592. ofs << content;
  22593. ASSERT_TRUE(ofs.good());
  22594. }
  22595. Server svr;
  22596. svr.set_mount_point("/static", ".");
  22597. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  22598. svr.wait_until_ready();
  22599. Client cli(HOST, PORT);
  22600. // Get the actual ETag
  22601. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  22602. ASSERT_TRUE(res1);
  22603. ASSERT_EQ(200, res1->status);
  22604. ASSERT_TRUE(res1->has_header("ETag"));
  22605. std::string etag = res1->get_header_value("ETag");
  22606. // Test 1: Very long ETag value (longer than actual ETag)
  22607. // Should NOT match and return 200 (not trigger out-of-bounds read)
  22608. Headers h1 = {{"If-None-Match", "W/"
  22609. "\"very-long-etag-value-that-is-much-longer-"
  22610. "than-the-actual-etag-value\""}};
  22611. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  22612. ASSERT_TRUE(res2);
  22613. EXPECT_EQ(200, res2->status); // Should not match
  22614. // Test 2: Long string followed by wildcard
  22615. // Should match on "*" and return 304 (without out-of-bounds read on the long
  22616. // string)
  22617. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  22618. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  22619. ASSERT_TRUE(res3);
  22620. EXPECT_EQ(304, res3->status); // Should match on "*"
  22621. // Test 3: Wildcard followed by long string
  22622. // Should match on "*" immediately and return 304
  22623. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  22624. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  22625. ASSERT_TRUE(res4);
  22626. EXPECT_EQ(304, res4->status); // Should match on "*"
  22627. // Test 4: Multiple long non-matching values
  22628. // Should NOT match and return 200 (test that all comparisons are safe)
  22629. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  22630. "W/\"second-long-non-matching-value\", "
  22631. "W/\"third-long-non-matching-value\""}};
  22632. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  22633. ASSERT_TRUE(res5);
  22634. EXPECT_EQ(200, res5->status); // Should not match
  22635. // Test 5: Single character that is not "*" (edge case)
  22636. Headers h5 = {{"If-None-Match", "X"}};
  22637. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  22638. ASSERT_TRUE(res6);
  22639. EXPECT_EQ(200, res6->status); // Should not match
  22640. svr.stop();
  22641. t.join();
  22642. std::remove(fname);
  22643. }
  22644. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  22645. using namespace httplib;
  22646. // Create a test file
  22647. const char *fname = "ims_testfile.txt";
  22648. const char *content = "if-modified-since-test";
  22649. {
  22650. std::ofstream ofs(fname);
  22651. ofs << content;
  22652. ASSERT_TRUE(ofs.good());
  22653. }
  22654. Server svr;
  22655. svr.set_mount_point("/static", ".");
  22656. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22657. svr.wait_until_ready();
  22658. Client cli(HOST, PORT);
  22659. // First request: should get 200 with Last-Modified header
  22660. auto res1 = cli.Get("/static/ims_testfile.txt");
  22661. ASSERT_TRUE(res1);
  22662. ASSERT_EQ(200, res1->status);
  22663. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22664. std::string last_modified = res1->get_header_value("Last-Modified");
  22665. EXPECT_FALSE(last_modified.empty());
  22666. // If-Modified-Since with same time: expect 304
  22667. Headers h2 = {{"If-Modified-Since", last_modified}};
  22668. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  22669. ASSERT_TRUE(res2);
  22670. EXPECT_EQ(304, res2->status);
  22671. // If-Modified-Since with future time: expect 304
  22672. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22673. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  22674. ASSERT_TRUE(res3);
  22675. EXPECT_EQ(304, res3->status);
  22676. // If-Modified-Since with past time: expect 200
  22677. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22678. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  22679. ASSERT_TRUE(res4);
  22680. EXPECT_EQ(200, res4->status);
  22681. // If-None-Match takes precedence over If-Modified-Since
  22682. // (send matching ETag with old If-Modified-Since -> should still be 304)
  22683. ASSERT_TRUE(res1->has_header("ETag"));
  22684. std::string etag = res1->get_header_value("ETag");
  22685. Headers h5 = {{"If-None-Match", etag},
  22686. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22687. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  22688. ASSERT_TRUE(res5);
  22689. EXPECT_EQ(304, res5->status);
  22690. svr.stop();
  22691. t.join();
  22692. std::remove(fname);
  22693. }
  22694. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  22695. using namespace httplib;
  22696. Server svr;
  22697. // Endpoint that returns compressible content
  22698. svr.Get("/compressible", [](const Request &, Response &res) {
  22699. // Return a large enough body to trigger compression
  22700. std::string body(1000, 'a');
  22701. res.set_content(body, "text/plain");
  22702. });
  22703. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22704. svr.wait_until_ready();
  22705. Client cli(HOST, PORT);
  22706. // Request with gzip support: should get Vary header when compressed
  22707. cli.set_compress(true);
  22708. auto res1 = cli.Get("/compressible");
  22709. ASSERT_TRUE(res1);
  22710. EXPECT_EQ(200, res1->status);
  22711. // If Content-Encoding is set, Vary should also be set
  22712. if (res1->has_header("Content-Encoding")) {
  22713. EXPECT_TRUE(res1->has_header("Vary"));
  22714. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  22715. }
  22716. // Request without Accept-Encoding header: should not have compression
  22717. Headers h_no_compress;
  22718. auto res2 = cli.Get("/compressible", h_no_compress);
  22719. ASSERT_TRUE(res2);
  22720. EXPECT_EQ(200, res2->status);
  22721. // Verify Vary header is present when compression is applied
  22722. // (the exact behavior depends on server configuration)
  22723. svr.stop();
  22724. t.join();
  22725. }
  22726. TEST(ETagTest, IfRangeWithETag) {
  22727. using namespace httplib;
  22728. // Create a test file with known content
  22729. const char *fname = "if_range_testfile.txt";
  22730. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  22731. {
  22732. std::ofstream ofs(fname);
  22733. ofs << content;
  22734. ASSERT_TRUE(ofs.good());
  22735. }
  22736. Server svr;
  22737. svr.set_mount_point("/static", ".");
  22738. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22739. svr.wait_until_ready();
  22740. Client cli(HOST, PORT);
  22741. // First request: get ETag
  22742. auto res1 = cli.Get("/static/if_range_testfile.txt");
  22743. ASSERT_TRUE(res1);
  22744. ASSERT_EQ(200, res1->status);
  22745. ASSERT_TRUE(res1->has_header("ETag"));
  22746. std::string etag = res1->get_header_value("ETag");
  22747. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  22748. // Since our server generates weak ETags (W/"..."), If-Range with our
  22749. // ETag should NOT result in partial content - it should return full content.
  22750. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  22751. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  22752. ASSERT_TRUE(res2);
  22753. // Weak ETag in If-Range -> full content (200), not partial (206)
  22754. EXPECT_EQ(200, res2->status);
  22755. EXPECT_EQ(content, res2->body);
  22756. EXPECT_FALSE(res2->has_header("Content-Range"));
  22757. // Range request with non-matching If-Range (ETag): should get 200 (full
  22758. // content)
  22759. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  22760. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  22761. ASSERT_TRUE(res3);
  22762. EXPECT_EQ(200, res3->status);
  22763. EXPECT_EQ(content, res3->body);
  22764. EXPECT_FALSE(res3->has_header("Content-Range"));
  22765. // Range request with strong ETag (hypothetical - our server doesn't generate
  22766. // strong ETags, but if client sends a strong ETag that doesn't match, it
  22767. // should return full content)
  22768. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  22769. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  22770. ASSERT_TRUE(res4);
  22771. EXPECT_EQ(200, res4->status);
  22772. EXPECT_EQ(content, res4->body);
  22773. EXPECT_FALSE(res4->has_header("Content-Range"));
  22774. svr.stop();
  22775. t.join();
  22776. std::remove(fname);
  22777. }
  22778. TEST(ETagTest, IfRangeWithDate) {
  22779. using namespace httplib;
  22780. // Create a test file
  22781. const char *fname = "if_range_date_testfile.txt";
  22782. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  22783. {
  22784. std::ofstream ofs(fname);
  22785. ofs << content;
  22786. ASSERT_TRUE(ofs.good());
  22787. }
  22788. Server svr;
  22789. svr.set_mount_point("/static", ".");
  22790. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22791. svr.wait_until_ready();
  22792. Client cli(HOST, PORT);
  22793. // First request: get Last-Modified
  22794. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  22795. ASSERT_TRUE(res1);
  22796. ASSERT_EQ(200, res1->status);
  22797. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22798. std::string last_modified = res1->get_header_value("Last-Modified");
  22799. // Range request with matching If-Range (date): should get 206
  22800. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  22801. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  22802. ASSERT_TRUE(res2);
  22803. EXPECT_EQ(206, res2->status);
  22804. EXPECT_EQ("FGHIJ", res2->body);
  22805. // Range request with old If-Range date: should get 200 (full content)
  22806. Headers h3 = {{"Range", "bytes=5-9"},
  22807. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  22808. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  22809. ASSERT_TRUE(res3);
  22810. EXPECT_EQ(200, res3->status);
  22811. EXPECT_EQ(content, res3->body);
  22812. // Range request with future If-Range date: should get 206
  22813. Headers h4 = {{"Range", "bytes=0-4"},
  22814. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  22815. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  22816. ASSERT_TRUE(res4);
  22817. EXPECT_EQ(206, res4->status);
  22818. EXPECT_EQ("ABCDE", res4->body);
  22819. svr.stop();
  22820. t.join();
  22821. std::remove(fname);
  22822. }
  22823. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  22824. using namespace httplib;
  22825. const char *fname = "etag_malformed.txt";
  22826. const char *content = "malformed-etag";
  22827. {
  22828. std::ofstream ofs(fname);
  22829. ofs << content;
  22830. ASSERT_TRUE(ofs.good());
  22831. }
  22832. Server svr;
  22833. svr.set_mount_point("/static", ".");
  22834. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22835. svr.wait_until_ready();
  22836. Client cli(HOST, PORT);
  22837. // baseline: should get 200 and an ETag
  22838. auto res1 = cli.Get("/static/etag_malformed.txt");
  22839. ASSERT_TRUE(res1);
  22840. ASSERT_EQ(200, res1->status);
  22841. ASSERT_TRUE(res1->has_header("ETag"));
  22842. // Malformed ETag value (missing quotes) should be treated as non-matching
  22843. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  22844. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  22845. ASSERT_TRUE(res_bad);
  22846. EXPECT_EQ(200, res_bad->status);
  22847. // Whitespace-only header value should be considered invalid / non-matching
  22848. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  22849. "Host: localhost\r\n"
  22850. "If-None-Match: \r\n"
  22851. "Connection: close\r\n"
  22852. "\r\n";
  22853. std::string out;
  22854. ASSERT_TRUE(send_request(5, raw_req, &out));
  22855. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  22856. svr.stop();
  22857. t.join();
  22858. std::remove(fname);
  22859. }
  22860. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  22861. using namespace httplib;
  22862. const char *fname = "ims_invalid_format.txt";
  22863. const char *content = "ims-bad-format";
  22864. {
  22865. std::ofstream ofs(fname);
  22866. ofs << content;
  22867. ASSERT_TRUE(ofs.good());
  22868. }
  22869. Server svr;
  22870. svr.set_mount_point("/static", ".");
  22871. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22872. svr.wait_until_ready();
  22873. Client cli(HOST, PORT);
  22874. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  22875. ASSERT_TRUE(res1);
  22876. ASSERT_EQ(200, res1->status);
  22877. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22878. // If-Modified-Since with invalid format should not result in 304
  22879. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  22880. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  22881. ASSERT_TRUE(res_bad);
  22882. EXPECT_EQ(200, res_bad->status);
  22883. // If-Range with invalid date format should be treated as mismatch -> full
  22884. // content (200)
  22885. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  22886. {"If-Range", "invalid-date"}};
  22887. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  22888. ASSERT_TRUE(res_ifrange);
  22889. EXPECT_EQ(200, res_ifrange->status);
  22890. svr.stop();
  22891. t.join();
  22892. std::remove(fname);
  22893. }
  22894. TEST(ETagTest, IfRangeWithMalformedETag) {
  22895. using namespace httplib;
  22896. const char *fname = "ifrange_malformed.txt";
  22897. const std::string content = "0123456789";
  22898. {
  22899. std::ofstream ofs(fname);
  22900. ofs << content;
  22901. ASSERT_TRUE(ofs.good());
  22902. }
  22903. Server svr;
  22904. svr.set_mount_point("/static", ".");
  22905. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22906. svr.wait_until_ready();
  22907. Client cli(HOST, PORT);
  22908. // First request: get ETag
  22909. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  22910. ASSERT_TRUE(res1);
  22911. ASSERT_EQ(200, res1->status);
  22912. ASSERT_TRUE(res1->has_header("ETag"));
  22913. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  22914. // full content (200)
  22915. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  22916. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  22917. ASSERT_TRUE(res2);
  22918. EXPECT_EQ(200, res2->status);
  22919. EXPECT_EQ(content, res2->body);
  22920. svr.stop();
  22921. t.join();
  22922. std::remove(fname);
  22923. }
  22924. TEST(ETagTest, ExtremeLargeDateValues) {
  22925. using namespace httplib;
  22926. const char *fname = "ims_extreme_date.txt";
  22927. const char *content = "ims-extreme-date";
  22928. {
  22929. std::ofstream ofs(fname);
  22930. ofs << content;
  22931. ASSERT_TRUE(ofs.good());
  22932. }
  22933. Server svr;
  22934. svr.set_mount_point("/static", ".");
  22935. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22936. svr.wait_until_ready();
  22937. Client cli(HOST, PORT);
  22938. auto res1 = cli.Get(std::string("/static/") + fname);
  22939. ASSERT_TRUE(res1);
  22940. ASSERT_EQ(200, res1->status);
  22941. ASSERT_TRUE(res1->has_header("Last-Modified"));
  22942. // Extremely large year that may overflow date parsing routines.
  22943. Headers h_large_date = {
  22944. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22945. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  22946. ASSERT_TRUE(res_bad);
  22947. // Expect server to treat this as invalid/mismatch and return full content
  22948. EXPECT_EQ(200, res_bad->status);
  22949. // If-Range with extremely large date should be treated as mismatch -> full
  22950. // content (200)
  22951. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  22952. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  22953. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  22954. ASSERT_TRUE(res_ifrange);
  22955. EXPECT_EQ(200, res_ifrange->status);
  22956. svr.stop();
  22957. t.join();
  22958. std::remove(fname);
  22959. }
  22960. TEST(ETagTest, NegativeFileModificationTime) {
  22961. using namespace httplib;
  22962. const char *fname = "ims_negative_mtime.txt";
  22963. const std::string content = "negative-mtime";
  22964. {
  22965. std::ofstream ofs(fname);
  22966. ofs << content;
  22967. ASSERT_TRUE(ofs.good());
  22968. }
  22969. // Try to set file mtime to a negative value. This may fail on some
  22970. // platforms/filesystems; if it fails, the test will still verify server
  22971. // behaves safely by performing a regular conditional request.
  22972. #if defined(__APPLE__) || defined(__linux__)
  22973. bool set_negative = false;
  22974. do {
  22975. struct timeval times[2];
  22976. // access time: now
  22977. times[0].tv_sec = time(nullptr);
  22978. times[0].tv_usec = 0;
  22979. // modification time: negative (e.g., -1)
  22980. times[1].tv_sec = -1;
  22981. times[1].tv_usec = 0;
  22982. if (utimes(fname, times) == 0) { set_negative = true; }
  22983. } while (0);
  22984. #else
  22985. bool set_negative = false;
  22986. #endif
  22987. Server svr;
  22988. svr.set_mount_point("/static", ".");
  22989. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  22990. svr.wait_until_ready();
  22991. Client cli(HOST, PORT);
  22992. auto res1 = cli.Get(std::string("/static/") + fname);
  22993. ASSERT_TRUE(res1);
  22994. ASSERT_EQ(200, res1->status);
  22995. bool has_last_modified = res1->has_header("Last-Modified");
  22996. std::string last_modified;
  22997. if (has_last_modified) {
  22998. last_modified = res1->get_header_value("Last-Modified");
  22999. }
  23000. if (set_negative) {
  23001. // If we successfully set a negative mtime, ensure server returns a
  23002. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  23003. // with an old date and ensure server handles it without crash.
  23004. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  23005. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  23006. ASSERT_TRUE(res2);
  23007. // Behavior may vary; at minimum ensure server responds (200 or 304).
  23008. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  23009. } else {
  23010. // Could not set negative mtime on this platform; fall back to verifying
  23011. // that normal invalid/malformed dates are treated safely (non-304).
  23012. Headers h_bad_date = {
  23013. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  23014. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  23015. ASSERT_TRUE(res_bad);
  23016. EXPECT_EQ(200, res_bad->status);
  23017. }
  23018. svr.stop();
  23019. t.join();
  23020. std::remove(fname);
  23021. }
  23022. //==============================================================================
  23023. // Integration Tests with Server
  23024. //==============================================================================
  23025. class SSEIntegrationTest : public ::testing::Test {
  23026. protected:
  23027. void SetUp() override {
  23028. stop_server_.store(false);
  23029. events_.clear();
  23030. server_ = httplib::detail::make_unique<Server>();
  23031. setup_server();
  23032. start_server();
  23033. }
  23034. void TearDown() override {
  23035. stop_server_.store(true);
  23036. event_cv_.notify_all();
  23037. server_->stop();
  23038. if (server_thread_.joinable()) { server_thread_.join(); }
  23039. }
  23040. void setup_server() {
  23041. // Simple SSE endpoint
  23042. server_->Get("/events", [this](const Request &req, Response &res) {
  23043. auto last_id = req.get_header_value("Last-Event-ID");
  23044. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  23045. res.set_chunked_content_provider(
  23046. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  23047. std::unique_lock<std::mutex> lock(event_mutex_);
  23048. if (event_cv_.wait_for(
  23049. lock, std::chrono::milliseconds(200), [this] {
  23050. return !events_.empty() || stop_server_.load();
  23051. })) {
  23052. if (stop_server_.load()) { return false; }
  23053. if (!events_.empty()) {
  23054. std::string event = events_.front();
  23055. events_.erase(events_.begin());
  23056. sink.write(event.data(), event.size());
  23057. return true;
  23058. }
  23059. }
  23060. return !stop_server_.load();
  23061. });
  23062. });
  23063. // Endpoint that returns error
  23064. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  23065. res.status = 500;
  23066. res.set_content("Internal Server Error", "text/plain");
  23067. });
  23068. // Endpoint for custom event types
  23069. server_->Get("/custom-events", [](const Request &, Response &res) {
  23070. res.set_chunked_content_provider(
  23071. "text/event-stream", [](size_t offset, DataSink &sink) {
  23072. if (offset == 0) {
  23073. std::string event = "event: update\ndata: updated\n\n"
  23074. "event: delete\ndata: deleted\n\n";
  23075. sink.write(event.data(), event.size());
  23076. }
  23077. return false; // End stream after sending
  23078. });
  23079. });
  23080. }
  23081. void start_server() {
  23082. port_ = server_->bind_to_any_port(HOST);
  23083. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23084. // Wait for server to start
  23085. while (!server_->is_running()) {
  23086. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23087. }
  23088. }
  23089. int get_port() const { return port_; }
  23090. void send_event(const std::string &event) {
  23091. std::lock_guard<std::mutex> lock(event_mutex_);
  23092. events_.push_back(event);
  23093. event_cv_.notify_all();
  23094. }
  23095. std::unique_ptr<Server> server_;
  23096. std::thread server_thread_;
  23097. std::mutex event_mutex_;
  23098. std::condition_variable event_cv_;
  23099. std::vector<std::string> events_;
  23100. std::atomic<bool> stop_server_{false};
  23101. std::string last_received_event_id_;
  23102. int port_ = 0;
  23103. };
  23104. //==============================================================================
  23105. // SSE Parser Tests
  23106. //==============================================================================
  23107. struct SSEParseResult {
  23108. std::vector<sse::SSEMessage> events;
  23109. std::vector<std::string> ids;
  23110. std::vector<int> retries;
  23111. bool ok = true;
  23112. std::string trace; // Every handler call in order
  23113. };
  23114. static SSEParseResult
  23115. sse_parse(const std::vector<std::string> &chunks,
  23116. size_t max_event_length = CPPHTTPLIB_SSE_MAX_EVENT_LENGTH) {
  23117. SSEParseResult r;
  23118. detail::SSEParser parser(
  23119. [&](const sse::SSEMessage &msg) {
  23120. r.events.push_back(msg);
  23121. r.trace += "event[" + msg.event + "|" + msg.data + "|" + msg.id + "]";
  23122. },
  23123. [&](const std::string &id) {
  23124. r.ids.push_back(id);
  23125. r.trace += "id[" + id + "]";
  23126. },
  23127. [&](int retry_ms) {
  23128. r.retries.push_back(retry_ms);
  23129. r.trace += "retry[" + std::to_string(retry_ms) + "]";
  23130. },
  23131. max_event_length);
  23132. for (const auto &chunk : chunks) {
  23133. if (!parser.parse(chunk.data(), chunk.size())) {
  23134. r.ok = false;
  23135. break;
  23136. }
  23137. }
  23138. return r;
  23139. }
  23140. static SSEParseResult sse_parse(const std::string &stream) {
  23141. return sse_parse(std::vector<std::string>{stream});
  23142. }
  23143. TEST(SSEParserTest, SingleLineData) {
  23144. auto r = sse_parse("data: hello\n\n");
  23145. ASSERT_EQ(r.events.size(), 1u);
  23146. EXPECT_EQ(r.events[0].data, "hello");
  23147. EXPECT_EQ(r.events[0].event, "message");
  23148. }
  23149. TEST(SSEParserTest, MultiLineData) {
  23150. auto r = sse_parse("data: line1\ndata: line2\ndata: line3\n\n");
  23151. ASSERT_EQ(r.events.size(), 1u);
  23152. EXPECT_EQ(r.events[0].data, "line1\nline2\nline3");
  23153. }
  23154. TEST(SSEParserTest, CustomEventType) {
  23155. auto r = sse_parse("event: update\ndata: payload\n\n");
  23156. ASSERT_EQ(r.events.size(), 1u);
  23157. EXPECT_EQ(r.events[0].event, "update");
  23158. EXPECT_EQ(r.events[0].data, "payload");
  23159. }
  23160. TEST(SSEParserTest, EventIdHandling) {
  23161. auto r = sse_parse("id: 12345\ndata: test\n\n");
  23162. ASSERT_EQ(r.events.size(), 1u);
  23163. EXPECT_EQ(r.events[0].id, "12345");
  23164. EXPECT_EQ(r.ids, std::vector<std::string>{"12345"});
  23165. }
  23166. TEST(SSEParserTest, EmptyEventId) {
  23167. auto r = sse_parse("id:\ndata: test\n\n");
  23168. ASSERT_EQ(r.events.size(), 1u);
  23169. EXPECT_EQ(r.events[0].id, "");
  23170. EXPECT_EQ(r.ids, std::vector<std::string>{""});
  23171. }
  23172. TEST(SSEParserTest, CommentsIgnored) {
  23173. auto r = sse_parse(": this is a comment\ndata: hello\n\n");
  23174. ASSERT_EQ(r.events.size(), 1u);
  23175. EXPECT_EQ(r.events[0].data, "hello");
  23176. EXPECT_EQ(r.events[0].event, "message");
  23177. }
  23178. TEST(SSEParserTest, ColonInValue) {
  23179. auto r = sse_parse("data: hello:world:test\n\n");
  23180. ASSERT_EQ(r.events.size(), 1u);
  23181. EXPECT_EQ(r.events[0].data, "hello:world:test");
  23182. }
  23183. TEST(SSEParserTest, FieldNameOnly) {
  23184. // A line without a colon is a field name with an empty value
  23185. auto r = sse_parse("data\n\n");
  23186. ASSERT_EQ(r.events.size(), 1u);
  23187. EXPECT_EQ(r.events[0].data, "");
  23188. }
  23189. TEST(SSEParserTest, TrailingCarriageReturn) {
  23190. auto r = sse_parse("event: update\r\ndata: hello\r\n\r\n");
  23191. ASSERT_EQ(r.events.size(), 1u);
  23192. EXPECT_EQ(r.events[0].event, "update");
  23193. EXPECT_EQ(r.events[0].data, "hello");
  23194. }
  23195. TEST(SSEParserTest, FieldNameOnlyWithCarriageReturn) {
  23196. auto r = sse_parse("data\r\n\r\n");
  23197. ASSERT_EQ(r.events.size(), 1u);
  23198. EXPECT_EQ(r.events[0].data, "");
  23199. }
  23200. TEST(SSEParserTest, CarriageReturnLineEnding) {
  23201. auto r = sse_parse("event: update\rdata: hello\r\r");
  23202. ASSERT_EQ(r.events.size(), 1u);
  23203. EXPECT_EQ(r.events[0].event, "update");
  23204. EXPECT_EQ(r.events[0].data, "hello");
  23205. }
  23206. TEST(SSEParserTest, LineEndingSplitAcrossChunks) {
  23207. // Chunk boundaries fall inside every \r\n and right before the first one
  23208. auto r = sse_parse(std::vector<std::string>{"event: update", "\r",
  23209. "\ndata: hello\r", "\n\r", "\n"});
  23210. ASSERT_EQ(r.events.size(), 1u);
  23211. EXPECT_EQ(r.events[0].event, "update");
  23212. EXPECT_EQ(r.events[0].data, "hello");
  23213. }
  23214. TEST(SSEParserTest, LeadingByteOrderMarkIgnored) {
  23215. // Only a BOM at the start of the stream is ignored
  23216. auto r = sse_parse("\xEF\xBB\xBF"
  23217. "data: first\n\n"
  23218. "\xEF\xBB\xBF"
  23219. "data: second\n\n");
  23220. ASSERT_EQ(r.events.size(), 1u);
  23221. EXPECT_EQ(r.events[0].data, "first");
  23222. }
  23223. TEST(SSEParserTest, UnknownFieldsIgnored) {
  23224. auto r = sse_parse("unknown: value\ndata: hello\n\n");
  23225. ASSERT_EQ(r.events.size(), 1u);
  23226. EXPECT_EQ(r.events[0].data, "hello");
  23227. EXPECT_EQ(r.events[0].event, "message");
  23228. }
  23229. TEST(SSEParserTest, SpaceAfterColonOptional) {
  23230. auto r = sse_parse("data: hello\n\ndata:hello\n\n");
  23231. ASSERT_EQ(r.events.size(), 2u);
  23232. EXPECT_EQ(r.events[0].data, "hello");
  23233. EXPECT_EQ(r.events[1].data, "hello");
  23234. }
  23235. TEST(SSEParserTest, EventWithoutDataResetsEventType) {
  23236. // An event without data is not dispatched, and its type must not leak
  23237. // into the next event
  23238. auto r = sse_parse("event: update\n\ndata: hello\n\n");
  23239. ASSERT_EQ(r.events.size(), 1u);
  23240. EXPECT_EQ(r.events[0].event, "message");
  23241. EXPECT_EQ(r.events[0].data, "hello");
  23242. }
  23243. TEST(SSEParserTest, EmptyEventTypeIsMessage) {
  23244. // Also when the empty field replaces an earlier type
  23245. auto r = sse_parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  23246. ASSERT_EQ(r.events.size(), 2u);
  23247. EXPECT_EQ(r.events[0].event, "message");
  23248. EXPECT_EQ(r.events[1].event, "message");
  23249. }
  23250. TEST(SSEParserTest, EventWithoutDataReportsId) {
  23251. auto r = sse_parse("id: 42\n\n");
  23252. EXPECT_TRUE(r.events.empty());
  23253. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23254. }
  23255. TEST(SSEParserTest, EmptyEventIdClearsId) {
  23256. auto r = sse_parse("id: 1\ndata: first\n\nid:\ndata: second\n\n");
  23257. ASSERT_EQ(r.events.size(), 2u);
  23258. EXPECT_EQ(r.events[0].id, "1");
  23259. EXPECT_EQ(r.events[1].id, "");
  23260. EXPECT_EQ(r.ids, (std::vector<std::string>{"1", ""}));
  23261. }
  23262. TEST(SSEParserTest, UnsendableEventIdIgnored) {
  23263. // Ids that cannot be carried in a Last-Event-ID header
  23264. auto r = sse_parse(std::string("id: 42\n\nid: a") + '\0' +
  23265. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n");
  23266. EXPECT_EQ(r.ids, std::vector<std::string>{"42"});
  23267. }
  23268. TEST(SSEParserTest, RetryDigitsOnly) {
  23269. auto r = sse_parse("retry: 1000\n");
  23270. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23271. // A value that is not all ASCII digits, or does not fit, is ignored
  23272. r = sse_parse("retry: -1\nretry: 1.5\nretry:\nretry: 99999999999\n");
  23273. EXPECT_TRUE(r.retries.empty());
  23274. }
  23275. TEST(SSEParserTest, CompleteEventParsing) {
  23276. auto r = sse_parse("event: notification\nid: evt-42\n"
  23277. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  23278. ASSERT_EQ(r.events.size(), 1u);
  23279. EXPECT_EQ(r.events[0].event, "notification");
  23280. EXPECT_EQ(r.events[0].id, "evt-42");
  23281. EXPECT_EQ(r.events[0].data, "{\"type\":\"alert\"}");
  23282. EXPECT_EQ(r.retries, std::vector<int>{1000});
  23283. }
  23284. TEST(SSEParserTest, IncompleteEventNotReported) {
  23285. // An event still waiting for its blank line when the stream ends is
  23286. // discarded per the SSE spec
  23287. auto r = sse_parse("id: 1\ndata: x\n");
  23288. EXPECT_TRUE(r.events.empty());
  23289. EXPECT_TRUE(r.ids.empty());
  23290. }
  23291. TEST(SSEParserTest, SameResultAtEveryChunkBoundary) {
  23292. const std::vector<std::string> streams = {
  23293. "\xEF\xBB\xBF"
  23294. "data: bom\r\n\r\n",
  23295. "event: a\r\ndata: 1\r\nid: x\r\n\r\ndata: 2\rretry: 7\r\r",
  23296. ": comment\ndata\nid:\n\nid: y\n\ndata: tail\r\n\r\n",
  23297. };
  23298. for (const auto &stream : streams) {
  23299. auto expected = sse_parse(stream).trace;
  23300. ASSERT_FALSE(expected.empty());
  23301. for (size_t i = 0; i <= stream.size(); i++) {
  23302. auto r = sse_parse(
  23303. std::vector<std::string>{stream.substr(0, i), stream.substr(i)});
  23304. EXPECT_EQ(r.trace, expected) << "split at " << i;
  23305. }
  23306. std::vector<std::string> bytes;
  23307. for (auto c : stream) {
  23308. bytes.emplace_back(1, c);
  23309. }
  23310. EXPECT_EQ(sse_parse(bytes).trace, expected) << "byte by byte";
  23311. }
  23312. }
  23313. TEST(SSEParserTest, MaxEventLength) {
  23314. // A line still waiting for its end
  23315. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 12"}, 8).ok);
  23316. EXPECT_FALSE(sse_parse(std::vector<std::string>{"data: 123"}, 8).ok);
  23317. // Data accumulated over the lines of one event
  23318. EXPECT_TRUE(
  23319. sse_parse(std::vector<std::string>{"data: 1234\ndata: 567\n"}, 8).ok);
  23320. EXPECT_FALSE(
  23321. sse_parse(std::vector<std::string>{"data: 1234\ndata: 5678\n"}, 8).ok);
  23322. // 0 means no limit
  23323. EXPECT_TRUE(sse_parse(std::vector<std::string>{"data: 123"}, 0).ok);
  23324. // Events completed in the same chunk are still reported
  23325. auto r = sse_parse(std::vector<std::string>{"data: a\n\ndata: 123456789"}, 8);
  23326. EXPECT_FALSE(r.ok);
  23327. ASSERT_EQ(r.events.size(), 1u);
  23328. EXPECT_EQ(r.events[0].data, "a");
  23329. }
  23330. TEST(SSEMessageTest, Clear) {
  23331. sse::SSEMessage msg;
  23332. msg.event = "custom";
  23333. msg.data = "some data";
  23334. msg.id = "123";
  23335. msg.clear();
  23336. EXPECT_EQ(msg.event, "message");
  23337. EXPECT_EQ(msg.data, "");
  23338. EXPECT_EQ(msg.id, "");
  23339. }
  23340. //==============================================================================
  23341. // SSE Integration Tests
  23342. //==============================================================================
  23343. // Test: Successful connection and on_open callback
  23344. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  23345. // Add a simple endpoint that sends one event and closes
  23346. server_->Get("/simple-event", [](const Request &, Response &res) {
  23347. res.set_chunked_content_provider(
  23348. "text/event-stream", [](size_t offset, DataSink &sink) {
  23349. if (offset == 0) {
  23350. std::string event = "data: hello\n\n";
  23351. sink.write(event.data(), event.size());
  23352. }
  23353. return false; // Close stream after sending
  23354. });
  23355. });
  23356. Client client("localhost", get_port());
  23357. sse::SSEClient sse(client, "/simple-event");
  23358. std::atomic<bool> open_called{false};
  23359. std::atomic<bool> message_received{false};
  23360. sse.on_open([&open_called]() { open_called.store(true); });
  23361. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  23362. if (msg.data == "hello") { message_received.store(true); }
  23363. });
  23364. sse.set_reconnect_interval(100);
  23365. sse.set_max_reconnect_attempts(1);
  23366. // Start async
  23367. sse.start_async();
  23368. // Wait for message to be processed
  23369. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23370. sse.stop();
  23371. EXPECT_TRUE(open_called.load());
  23372. EXPECT_TRUE(message_received.load());
  23373. }
  23374. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  23375. // A data line that never ends.
  23376. server_->Get("/endless-line", [](const Request &, Response &res) {
  23377. res.set_chunked_content_provider(
  23378. "text/event-stream", [](size_t offset, DataSink &sink) {
  23379. if (offset == 0) { sink.write("data: ", 6); }
  23380. std::string chunk(64 * 1024, 'A');
  23381. return sink.write(chunk.data(), chunk.size());
  23382. });
  23383. });
  23384. Client client("localhost", get_port());
  23385. sse::SSEClient sse(client, "/endless-line");
  23386. std::atomic<bool> too_long{false};
  23387. sse.on_error([&](Error err) {
  23388. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  23389. });
  23390. sse.set_max_reconnect_attempts(1);
  23391. sse.start_async();
  23392. for (int i = 0; i < 500 && !too_long; i++) {
  23393. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23394. }
  23395. sse.stop();
  23396. EXPECT_TRUE(too_long);
  23397. }
  23398. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  23399. // Far more in all than the client's payload limit below.
  23400. server_->Get("/many-events", [](const Request &, Response &res) {
  23401. res.set_chunked_content_provider(
  23402. "text/event-stream", [](size_t offset, DataSink &sink) {
  23403. if (offset == 0) {
  23404. std::string events;
  23405. for (int i = 0; i < 1000; i++) {
  23406. events += "data: message\n\n";
  23407. }
  23408. sink.write(events.data(), events.size());
  23409. }
  23410. return false;
  23411. });
  23412. });
  23413. Client client("localhost", get_port());
  23414. client.set_payload_max_length(1024);
  23415. sse::SSEClient sse(client, "/many-events");
  23416. std::atomic<int> messages{0};
  23417. std::atomic<bool> too_large{false};
  23418. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  23419. sse.on_error([&](Error err) {
  23420. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  23421. });
  23422. sse.set_max_reconnect_attempts(1);
  23423. sse.start_async();
  23424. for (int i = 0; i < 500 && messages < 1000; i++) {
  23425. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23426. }
  23427. sse.stop();
  23428. EXPECT_GE(messages.load(), 1000);
  23429. EXPECT_FALSE(too_large);
  23430. }
  23431. // Test: on_message callback
  23432. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  23433. // Endpoint that sends multiple events then closes
  23434. server_->Get("/multi-event", [](const Request &, Response &res) {
  23435. res.set_chunked_content_provider(
  23436. "text/event-stream", [](size_t offset, DataSink &sink) {
  23437. if (offset == 0) {
  23438. std::string events = "data: message1\n\ndata: message2\n\n";
  23439. sink.write(events.data(), events.size());
  23440. }
  23441. return false;
  23442. });
  23443. });
  23444. Client client("localhost", get_port());
  23445. sse::SSEClient sse(client, "/multi-event");
  23446. std::vector<std::string> received_messages;
  23447. std::mutex messages_mutex;
  23448. sse.on_message([&](const sse::SSEMessage &msg) {
  23449. std::lock_guard<std::mutex> lock(messages_mutex);
  23450. received_messages.push_back(msg.data);
  23451. });
  23452. sse.set_reconnect_interval(100);
  23453. sse.set_max_reconnect_attempts(1);
  23454. sse.start_async();
  23455. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23456. sse.stop();
  23457. std::lock_guard<std::mutex> lock(messages_mutex);
  23458. EXPECT_GE(received_messages.size(), 2u);
  23459. if (received_messages.size() >= 2) {
  23460. EXPECT_EQ(received_messages[0], "message1");
  23461. EXPECT_EQ(received_messages[1], "message2");
  23462. }
  23463. }
  23464. // Test: on_event for specific types
  23465. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  23466. Client client("localhost", get_port());
  23467. sse::SSEClient sse(client, "/custom-events");
  23468. std::atomic<bool> update_received{false};
  23469. std::atomic<bool> delete_received{false};
  23470. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  23471. if (msg.data == "updated") { update_received.store(true); }
  23472. });
  23473. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  23474. if (msg.data == "deleted") { delete_received.store(true); }
  23475. });
  23476. sse.set_max_reconnect_attempts(1);
  23477. sse.start_async();
  23478. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  23479. sse.stop();
  23480. EXPECT_TRUE(update_received.load());
  23481. EXPECT_TRUE(delete_received.load());
  23482. }
  23483. // Test: on_error callback on connection failure
  23484. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  23485. // Connect to a non-existent port
  23486. Client client("localhost", 59999);
  23487. sse::SSEClient sse(client, "/events");
  23488. std::atomic<bool> error_called{false};
  23489. Error received_error = Error::Success;
  23490. sse.on_error([&](Error err) {
  23491. error_called.store(true);
  23492. received_error = err;
  23493. });
  23494. sse.set_reconnect_interval(50);
  23495. sse.set_max_reconnect_attempts(1);
  23496. sse.start_async();
  23497. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23498. sse.stop();
  23499. EXPECT_TRUE(error_called.load());
  23500. EXPECT_NE(received_error, Error::Success);
  23501. }
  23502. // Test: Last-Event-ID header sent on reconnect
  23503. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  23504. // Endpoint that sends event with ID
  23505. server_->Get("/event-with-id", [](const Request &, Response &res) {
  23506. res.set_chunked_content_provider(
  23507. "text/event-stream", [](size_t offset, DataSink &sink) {
  23508. if (offset == 0) {
  23509. std::string event = "id: evt-123\ndata: test\n\n";
  23510. sink.write(event.data(), event.size());
  23511. }
  23512. return false;
  23513. });
  23514. });
  23515. Client client("localhost", get_port());
  23516. sse::SSEClient sse(client, "/event-with-id");
  23517. std::atomic<bool> id_received{false};
  23518. sse.on_message([&](const sse::SSEMessage &msg) {
  23519. if (!msg.id.empty()) { id_received.store(true); }
  23520. });
  23521. sse.set_reconnect_interval(100);
  23522. sse.set_max_reconnect_attempts(1);
  23523. sse.start_async();
  23524. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23525. sse.stop();
  23526. EXPECT_TRUE(id_received.load());
  23527. EXPECT_EQ(sse.last_event_id(), "evt-123");
  23528. }
  23529. // Test: last_event_id() read from another thread while start_async() runs
  23530. TEST_F(SSEIntegrationTest, LastEventIdWhileRunning) {
  23531. // Ids of every length up to 200, so the stored id keeps changing size
  23532. server_->Get("/many-ids", [](const Request &, Response &res) {
  23533. res.set_chunked_content_provider(
  23534. "text/event-stream", [](size_t offset, DataSink &sink) {
  23535. if (offset == 0) {
  23536. std::string events;
  23537. for (size_t i = 0; i < 2000; i++) {
  23538. events += "id: " + std::string(1 + i % 200, 'a') + "\n";
  23539. events += "data: x\n\n";
  23540. }
  23541. events += "id: end\ndata: x\n\n";
  23542. sink.write(events.data(), events.size());
  23543. }
  23544. return false;
  23545. });
  23546. });
  23547. Client client("localhost", get_port());
  23548. sse::SSEClient sse(client, "/many-ids");
  23549. // Wait out the rest of the test rather than replay the stream
  23550. sse.set_reconnect_interval(10000);
  23551. sse.set_max_reconnect_attempts(1);
  23552. sse.start_async();
  23553. auto well_formed = true;
  23554. std::string id;
  23555. auto deadline = std::chrono::steady_clock::now() + std::chrono::seconds(5);
  23556. while (id != "end" && std::chrono::steady_clock::now() < deadline) {
  23557. id = sse.last_event_id();
  23558. if (id != "end" && id.find_first_not_of('a') != std::string::npos) {
  23559. well_formed = false;
  23560. }
  23561. }
  23562. sse.stop();
  23563. EXPECT_TRUE(well_formed);
  23564. EXPECT_EQ(sse.last_event_id(), "end");
  23565. }
  23566. // Test: Manual stop
  23567. TEST_F(SSEIntegrationTest, ManualStop) {
  23568. // Endpoint that sends one event and stays open briefly. The server outlives
  23569. // this test body, so the provider uses the fixture's flag, not a local.
  23570. server_->Get("/stay-open", [this](const Request &, Response &res) {
  23571. res.set_chunked_content_provider(
  23572. "text/event-stream", [this](size_t offset, DataSink &sink) {
  23573. if (offset == 0) {
  23574. std::string event = "data: connected\n\n";
  23575. sink.write(event.data(), event.size());
  23576. }
  23577. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  23578. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23579. }
  23580. return false;
  23581. });
  23582. });
  23583. Client client("localhost", get_port());
  23584. sse::SSEClient sse(client, "/stay-open");
  23585. std::atomic<bool> connected{false};
  23586. sse.on_open([&connected]() { connected.store(true); });
  23587. sse.set_reconnect_interval(100);
  23588. sse.set_max_reconnect_attempts(1);
  23589. sse.start_async();
  23590. // Wait for connection to establish
  23591. for (int i = 0; i < 20 && !connected.load(); ++i) {
  23592. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  23593. }
  23594. EXPECT_TRUE(connected.load());
  23595. EXPECT_TRUE(sse.is_connected());
  23596. // Signal handler to stop
  23597. stop_server_.store(true);
  23598. // Stop SSE client
  23599. sse.stop();
  23600. EXPECT_FALSE(sse.is_connected());
  23601. }
  23602. // Sends one event, then nothing until stop is set
  23603. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  23604. return [&stop](const Request &, Response &res) {
  23605. res.set_chunked_content_provider(
  23606. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  23607. if (offset == 0) {
  23608. std::string event = "data: hello\n\n";
  23609. sink.write(event.data(), event.size());
  23610. }
  23611. while (!stop.load()) {
  23612. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23613. }
  23614. return false;
  23615. });
  23616. };
  23617. }
  23618. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  23619. static void check_stop_interrupts_blocked_read(Client &client) {
  23620. client.set_read_timeout(30, 0);
  23621. for (auto by_destructor : {false, true}) {
  23622. std::atomic<bool> received{false};
  23623. std::chrono::steady_clock::time_point start;
  23624. {
  23625. sse::SSEClient sse(client, "/idle-stream");
  23626. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  23627. sse.start_async();
  23628. for (int i = 0; i < 500 && !received.load(); ++i) {
  23629. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23630. }
  23631. ASSERT_TRUE(received.load());
  23632. // Let the client block in the next read
  23633. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  23634. start = std::chrono::steady_clock::now();
  23635. if (!by_destructor) { sse.stop(); }
  23636. }
  23637. EXPECT_LT(std::chrono::steady_clock::now() - start,
  23638. std::chrono::seconds(2));
  23639. }
  23640. }
  23641. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  23642. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  23643. Client client("localhost", get_port());
  23644. check_stop_interrupts_blocked_read(client);
  23645. }
  23646. #ifdef CPPHTTPLIB_SSL_ENABLED
  23647. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  23648. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  23649. std::atomic<bool> done{false};
  23650. svr.Get("/idle-stream", idle_event_stream(done));
  23651. auto port = svr.bind_to_any_port(HOST);
  23652. std::thread t([&] { svr.listen_after_bind(); });
  23653. auto se = detail::scope_exit([&] {
  23654. done.store(true);
  23655. svr.stop();
  23656. t.join();
  23657. });
  23658. svr.wait_until_ready();
  23659. Client client("https://localhost:" + std::to_string(port));
  23660. client.enable_server_certificate_verification(false);
  23661. check_stop_interrupts_blocked_read(client);
  23662. }
  23663. #endif
  23664. // Test: SSEClient with custom headers
  23665. TEST_F(SSEIntegrationTest, CustomHeaders) {
  23666. // Setup a server endpoint that checks for custom header
  23667. std::atomic<bool> header_received{false};
  23668. server_->Get("/header-check", [&](const Request &req, Response &res) {
  23669. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  23670. header_received.store(true);
  23671. }
  23672. res.set_chunked_content_provider("text/event-stream",
  23673. [](size_t, DataSink &) { return false; });
  23674. });
  23675. Client client("localhost", get_port());
  23676. Headers headers = {{"X-Custom-Header", "custom-value"}};
  23677. sse::SSEClient sse(client, "/header-check", headers);
  23678. sse.set_max_reconnect_attempts(1);
  23679. sse.start_async();
  23680. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  23681. sse.stop();
  23682. EXPECT_TRUE(header_received.load());
  23683. }
  23684. // Test: Reconnect interval configuration
  23685. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  23686. Client client("localhost", get_port());
  23687. sse::SSEClient sse(client, "/events");
  23688. auto &result = sse.set_reconnect_interval(500);
  23689. // Builder pattern should return reference to self
  23690. EXPECT_EQ(&result, &sse);
  23691. }
  23692. // Test: Max reconnect attempts
  23693. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  23694. // Connect to non-existent port to force reconnects
  23695. Client client("localhost", 59998);
  23696. sse::SSEClient sse(client, "/events");
  23697. std::atomic<int> error_count{0};
  23698. sse.on_error([&](Error) { error_count.fetch_add(1); });
  23699. sse.set_reconnect_interval(50);
  23700. sse.set_max_reconnect_attempts(2);
  23701. auto start = std::chrono::steady_clock::now();
  23702. sse.start(); // Blocking call
  23703. auto end = std::chrono::steady_clock::now();
  23704. // Should have stopped after 2 failed attempts
  23705. EXPECT_GE(error_count.load(), 2);
  23706. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  23707. auto duration =
  23708. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  23709. #ifdef _WIN32
  23710. // Windows is much slower for socket connection failures
  23711. EXPECT_LT(duration.count(), 7000);
  23712. #else
  23713. EXPECT_LT(duration.count(), 1000);
  23714. #endif
  23715. }
  23716. // Test: Multi-line data in integration
  23717. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  23718. // Endpoint with multi-line data
  23719. server_->Get("/multiline-data", [](const Request &, Response &res) {
  23720. res.set_chunked_content_provider(
  23721. "text/event-stream", [](size_t offset, DataSink &sink) {
  23722. if (offset == 0) {
  23723. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  23724. sink.write(event.data(), event.size());
  23725. }
  23726. return false;
  23727. });
  23728. });
  23729. Client client("localhost", get_port());
  23730. sse::SSEClient sse(client, "/multiline-data");
  23731. std::string received_data;
  23732. std::mutex data_mutex;
  23733. sse.on_message([&](const sse::SSEMessage &msg) {
  23734. std::lock_guard<std::mutex> lock(data_mutex);
  23735. received_data = msg.data;
  23736. });
  23737. sse.set_reconnect_interval(100);
  23738. sse.set_max_reconnect_attempts(1);
  23739. sse.start_async();
  23740. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23741. sse.stop();
  23742. std::lock_guard<std::mutex> lock(data_mutex);
  23743. EXPECT_EQ(received_data, "line1\nline2\nline3");
  23744. }
  23745. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  23746. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  23747. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  23748. DataSink &sink) {
  23749. if (offset == 0) {
  23750. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  23751. sink.write(events.data(), events.size());
  23752. }
  23753. return false;
  23754. });
  23755. });
  23756. Client client("localhost", get_port());
  23757. sse::SSEClient sse(client, "/empty-data-lines");
  23758. std::mutex mutex;
  23759. std::condition_variable cv;
  23760. std::vector<std::string> received;
  23761. sse.on_message([&](const sse::SSEMessage &msg) {
  23762. std::lock_guard<std::mutex> lock(mutex);
  23763. received.push_back(msg.data);
  23764. cv.notify_all();
  23765. });
  23766. sse.set_max_reconnect_attempts(1);
  23767. sse.start_async();
  23768. {
  23769. std::unique_lock<std::mutex> lock(mutex);
  23770. cv.wait_for(lock, std::chrono::seconds(2),
  23771. [&] { return received.size() >= 3; });
  23772. }
  23773. sse.stop();
  23774. ASSERT_GE(received.size(), 3u);
  23775. EXPECT_EQ(received[0], "");
  23776. EXPECT_EQ(received[1], "\nhello");
  23777. EXPECT_EQ(received[2], "");
  23778. }
  23779. // Test: Auto-reconnect after server disconnection
  23780. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  23781. std::atomic<int> connection_count{0};
  23782. std::atomic<int> message_count{0};
  23783. // Endpoint that sends one event and closes, forcing reconnect
  23784. server_->Get("/reconnect-test",
  23785. [&connection_count](const Request &, Response &res) {
  23786. connection_count.fetch_add(1);
  23787. res.set_chunked_content_provider(
  23788. "text/event-stream", [](size_t offset, DataSink &sink) {
  23789. if (offset == 0) {
  23790. std::string event = "data: hello\n\n";
  23791. sink.write(event.data(), event.size());
  23792. }
  23793. return false; // Close connection after sending
  23794. });
  23795. });
  23796. Client client("localhost", get_port());
  23797. sse::SSEClient sse(client, "/reconnect-test");
  23798. sse.on_message([&message_count](const sse::SSEMessage &) {
  23799. message_count.fetch_add(1);
  23800. });
  23801. sse.set_reconnect_interval(100);
  23802. sse.set_max_reconnect_attempts(3);
  23803. sse.start_async();
  23804. // Wait long enough for multiple reconnects
  23805. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23806. sse.stop();
  23807. // Should have connected multiple times (initial + reconnects)
  23808. EXPECT_GE(connection_count.load(), 2);
  23809. // Should have received messages from multiple connections
  23810. EXPECT_GE(message_count.load(), 2);
  23811. }
  23812. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  23813. std::atomic<int> connection_count{0};
  23814. // Neither Content-Length nor chunked: the close ends the stream
  23815. server_->Get("/close-delimited",
  23816. [&connection_count](const Request &, Response &res) {
  23817. connection_count.fetch_add(1);
  23818. res.set_content_provider(
  23819. "text/event-stream", [](size_t offset, DataSink &sink) {
  23820. if (offset == 0) {
  23821. std::string event = "data: hello\n\n";
  23822. sink.write(event.data(), event.size());
  23823. } else {
  23824. sink.done();
  23825. }
  23826. return true;
  23827. });
  23828. });
  23829. Client client("localhost", get_port());
  23830. sse::SSEClient sse(client, "/close-delimited");
  23831. std::atomic<int> error_count{0};
  23832. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  23833. sse.set_reconnect_interval(100);
  23834. sse.start_async();
  23835. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  23836. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  23837. }
  23838. sse.stop();
  23839. // Reconnects as after any end of the stream, but reports no error
  23840. EXPECT_GE(connection_count.load(), 2);
  23841. EXPECT_EQ(0, error_count.load());
  23842. }
  23843. // Test: A retry field of all ASCII digits sets the reconnection time
  23844. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  23845. std::mutex mutex;
  23846. std::condition_variable cv;
  23847. std::vector<std::chrono::steady_clock::time_point> connected_at;
  23848. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  23849. {
  23850. std::lock_guard<std::mutex> lock(mutex);
  23851. connected_at.push_back(std::chrono::steady_clock::now());
  23852. cv.notify_all();
  23853. }
  23854. res.set_chunked_content_provider(
  23855. "text/event-stream", [](size_t offset, DataSink &sink) {
  23856. if (offset == 0) {
  23857. std::string event = "retry: 0\ndata: hello\n\n";
  23858. sink.write(event.data(), event.size());
  23859. }
  23860. return false;
  23861. });
  23862. });
  23863. Client client("localhost", get_port());
  23864. sse::SSEClient sse(client, "/zero-retry");
  23865. sse.set_reconnect_interval(10000);
  23866. sse.start_async();
  23867. {
  23868. std::unique_lock<std::mutex> lock(mutex);
  23869. cv.wait_for(lock, std::chrono::seconds(5),
  23870. [&] { return connected_at.size() >= 2; });
  23871. }
  23872. sse.stop();
  23873. // The server-supplied interval is applied, but never below 100ms, so
  23874. // "retry: 0" does not cause a busy reconnect loop
  23875. std::lock_guard<std::mutex> lock(mutex);
  23876. ASSERT_GE(connected_at.size(), 2u);
  23877. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  23878. connected_at[1] - connected_at[0])
  23879. .count();
  23880. EXPECT_GE(interval_ms, 100);
  23881. }
  23882. // Test: Last-Event-ID sent on reconnect
  23883. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  23884. std::atomic<int> connection_count{0};
  23885. std::vector<std::string> received_last_event_ids;
  23886. std::mutex id_mutex;
  23887. // Endpoint that checks Last-Event-ID header and sends event with ID
  23888. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  23889. int conn = connection_count.fetch_add(1);
  23890. // Capture the Last-Event-ID header from each connection
  23891. {
  23892. std::lock_guard<std::mutex> lock(id_mutex);
  23893. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  23894. }
  23895. res.set_chunked_content_provider(
  23896. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  23897. if (offset == 0) {
  23898. std::string event =
  23899. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  23900. sink.write(event.data(), event.size());
  23901. }
  23902. return false;
  23903. });
  23904. });
  23905. Client client("localhost", get_port());
  23906. sse::SSEClient sse(client, "/reconnect-with-id");
  23907. sse.set_reconnect_interval(100);
  23908. sse.set_max_reconnect_attempts(3);
  23909. sse.start_async();
  23910. // Wait for at least 2 connections
  23911. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  23912. sse.stop();
  23913. // Verify behavior
  23914. std::lock_guard<std::mutex> lock(id_mutex);
  23915. EXPECT_GE(received_last_event_ids.size(), 2u);
  23916. // First connection should have no Last-Event-ID
  23917. if (!received_last_event_ids.empty()) {
  23918. EXPECT_EQ(received_last_event_ids[0], "");
  23919. }
  23920. // Second connection should have Last-Event-ID from first connection
  23921. if (received_last_event_ids.size() >= 2) {
  23922. EXPECT_EQ(received_last_event_ids[1], "event-0");
  23923. }
  23924. }
  23925. // Test: set_headers updates headers used on reconnect
  23926. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  23927. std::vector<std::string> received_tokens;
  23928. std::mutex token_mutex;
  23929. // Endpoint that captures Authorization header
  23930. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  23931. {
  23932. std::lock_guard<std::mutex> lock(token_mutex);
  23933. received_tokens.push_back(req.get_header_value("Authorization"));
  23934. }
  23935. res.set_chunked_content_provider(
  23936. "text/event-stream", [](size_t offset, DataSink &sink) {
  23937. if (offset == 0) {
  23938. std::string event = "data: hello\n\n";
  23939. sink.write(event.data(), event.size());
  23940. }
  23941. return false; // Close connection to trigger reconnect
  23942. });
  23943. });
  23944. Client client("localhost", get_port());
  23945. Headers headers = {{"Authorization", "Bearer old-token"}};
  23946. sse::SSEClient sse(client, "/auth-check", headers);
  23947. // Update headers on each successful connection
  23948. sse.on_open(
  23949. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  23950. sse.set_reconnect_interval(100);
  23951. sse.set_max_reconnect_attempts(3);
  23952. sse.start_async();
  23953. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23954. sse.stop();
  23955. std::lock_guard<std::mutex> lock(token_mutex);
  23956. ASSERT_GE(received_tokens.size(), 2u);
  23957. // First connection uses original header
  23958. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  23959. // Second connection uses updated header from set_headers
  23960. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  23961. }
  23962. // Test: 401 allows reconnection (so on_error can refresh headers)
  23963. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  23964. std::atomic<int> connection_count{0};
  23965. // Endpoint: returns 401 on first attempt, 200 on second
  23966. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  23967. int conn = connection_count.fetch_add(1);
  23968. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  23969. res.status = StatusCode::Unauthorized_401;
  23970. res.set_content("Unauthorized", "text/plain");
  23971. return;
  23972. }
  23973. res.set_chunked_content_provider(
  23974. "text/event-stream", [](size_t offset, DataSink &sink) {
  23975. if (offset == 0) {
  23976. std::string event = "data: authenticated\n\n";
  23977. sink.write(event.data(), event.size());
  23978. }
  23979. return false;
  23980. });
  23981. });
  23982. Client client("localhost", get_port());
  23983. Headers headers = {{"Authorization", "Bearer expired"}};
  23984. sse::SSEClient sse(client, "/auth-retry", headers);
  23985. std::atomic<bool> message_received{false};
  23986. // Refresh token on error
  23987. sse.on_error(
  23988. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  23989. sse.on_message([&](const sse::SSEMessage &msg) {
  23990. if (msg.data == "authenticated") { message_received.store(true); }
  23991. });
  23992. sse.set_reconnect_interval(100);
  23993. sse.set_max_reconnect_attempts(3);
  23994. sse.start_async();
  23995. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  23996. sse.stop();
  23997. // Should have reconnected after 401 and succeeded with new token
  23998. EXPECT_GE(connection_count.load(), 2);
  23999. EXPECT_TRUE(message_received.load());
  24000. }
  24001. TEST(Issue2318Test, EmptyHostString) {
  24002. {
  24003. httplib::Client cli_empty("", PORT);
  24004. auto res = cli_empty.Get("/");
  24005. ASSERT_FALSE(res);
  24006. EXPECT_EQ(httplib::Error::Connection, res.error());
  24007. }
  24008. {
  24009. httplib::Client cli(" ", PORT);
  24010. auto res = cli.Get("/");
  24011. ASSERT_FALSE(res);
  24012. EXPECT_EQ(httplib::Error::Connection, res.error());
  24013. }
  24014. }
  24015. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  24016. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  24017. Server svr;
  24018. // Set a small payload limit (1KB)
  24019. svr.set_payload_max_length(1024);
  24020. svr.Post("/test", [&](const Request &req, Response &res) {
  24021. res.set_content("Body size: " + std::to_string(req.body.size()),
  24022. "text/plain");
  24023. });
  24024. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  24025. auto se = detail::scope_exit([&] {
  24026. svr.stop();
  24027. listen_thread.join();
  24028. });
  24029. svr.wait_until_ready();
  24030. // Create data that compresses well but exceeds limit when decompressed
  24031. // 8KB of repeated null bytes compresses to a very small size
  24032. std::string original_data(8 * 1024, '\0');
  24033. // Compress the data using gzip
  24034. std::string compressed_data;
  24035. detail::gzip_compressor compressor;
  24036. compressor.compress(original_data.data(), original_data.size(), true,
  24037. [&](const char *data, size_t size) {
  24038. compressed_data.append(data, size);
  24039. return true;
  24040. });
  24041. // Verify compression worked (compressed should be much smaller)
  24042. ASSERT_LT(compressed_data.size(), original_data.size());
  24043. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  24044. // Send compressed data with Content-Encoding: gzip
  24045. Client cli(HOST, PORT);
  24046. Headers headers = {{"Content-Encoding", "gzip"}};
  24047. auto res =
  24048. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  24049. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  24050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24051. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  24052. }
  24053. #endif
  24054. // ============================================================================
  24055. // OpenSSL-Specific Tests
  24056. // ============================================================================
  24057. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24058. X509 *readCertificate(const std::string &strFileName) {
  24059. std::ifstream inStream(strFileName);
  24060. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  24061. std::istreambuf_iterator<char>());
  24062. if (strCertPEM.empty()) return (nullptr);
  24063. BIO *pbCert = BIO_new(BIO_s_mem());
  24064. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  24065. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  24066. BIO_free(pbCert);
  24067. return (pCert);
  24068. }
  24069. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  24070. std::ifstream inStream(strFileName);
  24071. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  24072. std::istreambuf_iterator<char>());
  24073. if (strPrivateKeyPEM.empty()) return (nullptr);
  24074. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  24075. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  24076. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  24077. BIO_free(pbPrivKey);
  24078. return (pPrivateKey);
  24079. }
  24080. TEST(BindServerTest, UpdateCerts) {
  24081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24082. int port = svr.bind_to_any_port("0.0.0.0");
  24083. ASSERT_TRUE(svr.is_valid());
  24084. ASSERT_TRUE(port > 0);
  24085. X509 *cert = readCertificate(SERVER_CERT_FILE);
  24086. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  24087. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  24088. ASSERT_TRUE(cert != nullptr);
  24089. ASSERT_TRUE(ca_cert != nullptr);
  24090. ASSERT_TRUE(key != nullptr);
  24091. X509_STORE *cert_store = X509_STORE_new();
  24092. X509_STORE_add_cert(cert_store, ca_cert);
  24093. // svr.update_certs(cert, key, cert_store); // deprecated
  24094. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  24095. CLIENT_CA_CERT_FILE);
  24096. ASSERT_TRUE(svr.is_valid());
  24097. svr.stop();
  24098. X509_STORE_free(cert_store);
  24099. X509_free(cert);
  24100. X509_free(ca_cert);
  24101. EVP_PKEY_free(key);
  24102. }
  24103. // Test that update_certs() updates client CA list correctly
  24104. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  24105. // Start with file-based constructor
  24106. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24107. ASSERT_TRUE(svr.is_valid());
  24108. // Initially no client CA list should be set
  24109. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24110. ASSERT_TRUE(ssl_ctx != nullptr);
  24111. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  24112. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  24113. // Now update with client CA (PEM string)
  24114. std::string cert_pem, key_pem, ca_pem;
  24115. read_file(SERVER_CERT_FILE, cert_pem);
  24116. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  24117. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  24118. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  24119. ASSERT_TRUE(svr.is_valid());
  24120. // Now client CA list should be set
  24121. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  24122. ASSERT_TRUE(ca_list_after != nullptr);
  24123. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  24124. }
  24125. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  24126. // Test that the file-path SSLServer constructor properly sets the client CA
  24127. // list that is sent to clients during the TLS handshake (CertificateRequest)
  24128. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24129. ASSERT_TRUE(svr.is_valid());
  24130. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  24131. ASSERT_TRUE(ssl_ctx != nullptr);
  24132. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  24133. ASSERT_TRUE(ca_list != nullptr);
  24134. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  24135. }
  24136. #endif
  24137. // ============================================================================
  24138. // MbedTLS-Specific Tests
  24139. // ============================================================================
  24140. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  24141. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  24142. using namespace httplib::tls;
  24143. // Track if callback was invoked
  24144. bool callback_invoked = false;
  24145. // The callback receives void* ctx which is actually MbedTlsContext*
  24146. // We can access the mbedtls_ssl_config via the context
  24147. auto setup_callback = [&callback_invoked](void *ctx) {
  24148. callback_invoked = true;
  24149. // Cast to MbedTlsContext* to access the ssl config
  24150. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  24151. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  24152. // Use static variables to hold certificate data (simplified for test)
  24153. static mbedtls_x509_crt own_cert;
  24154. static mbedtls_pk_context own_key;
  24155. static mbedtls_x509_crt ca_chain;
  24156. static bool initialized = false;
  24157. if (!initialized) {
  24158. mbedtls_x509_crt_init(&own_cert);
  24159. mbedtls_pk_init(&own_key);
  24160. mbedtls_x509_crt_init(&ca_chain);
  24161. // Load server certificate
  24162. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  24163. return false;
  24164. }
  24165. // Load server private key.
  24166. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  24167. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  24168. #if MBEDTLS_VERSION_MAJOR == 3
  24169. ,
  24170. mbedtls_ctr_drbg_random, nullptr
  24171. #endif
  24172. ) != 0) {
  24173. return false;
  24174. }
  24175. // Load CA chain for client verification
  24176. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  24177. return false;
  24178. }
  24179. initialized = true;
  24180. }
  24181. // Configure the SSL config
  24182. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  24183. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  24184. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  24185. // Set minimum TLS version using mbedTLS native API
  24186. #if MBEDTLS_VERSION_MAJOR >= 3
  24187. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  24188. #else
  24189. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  24190. MBEDTLS_SSL_MINOR_VERSION_3);
  24191. #endif
  24192. return true;
  24193. };
  24194. SSLServer svr(setup_callback);
  24195. ASSERT_TRUE(svr.is_valid());
  24196. ASSERT_TRUE(callback_invoked);
  24197. svr.Get("/test", [&](const Request &req, Response &res) {
  24198. res.set_content("test", "text/plain");
  24199. auto cert = req.peer_cert();
  24200. ASSERT_TRUE(static_cast<bool>(cert));
  24201. auto common_name = cert.subject_cn();
  24202. EXPECT_EQ("Common Name", common_name);
  24203. });
  24204. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24205. auto se = detail::scope_exit([&] {
  24206. svr.stop();
  24207. t.join();
  24208. ASSERT_FALSE(svr.is_running());
  24209. });
  24210. svr.wait_until_ready();
  24211. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  24212. cli.enable_server_certificate_verification(false);
  24213. cli.set_connection_timeout(30);
  24214. auto res = cli.Get("/test");
  24215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24216. ASSERT_EQ(StatusCode::OK_200, res->status);
  24217. }
  24218. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  24219. // context (owning mbedtls_ssl_config) before shutting down a still-open
  24220. // keep-alive SSL session, which reads through that config in
  24221. // mbedtls_ssl_close_notify.
  24222. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  24223. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24224. ASSERT_TRUE(svr.is_valid());
  24225. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  24226. res.set_content("test", "text/plain");
  24227. });
  24228. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  24229. auto se = detail::scope_exit([&] {
  24230. svr.stop();
  24231. t.join();
  24232. ASSERT_FALSE(svr.is_running());
  24233. });
  24234. svr.wait_until_ready();
  24235. {
  24236. SSLClient cli(HOST, PORT);
  24237. cli.enable_server_certificate_verification(false);
  24238. cli.set_keep_alive(true);
  24239. auto res = cli.Get("/test");
  24240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  24241. ASSERT_EQ(StatusCode::OK_200, res->status);
  24242. // cli is destructed here with the keep-alive SSL session still open.
  24243. }
  24244. }
  24245. #endif
  24246. // WebSocket Tests
  24247. TEST(WebSocketTest, RSVBitsMustBeZero) {
  24248. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  24249. // defining the meaning of these bits has been negotiated.
  24250. auto make_frame = [](uint8_t first_byte) {
  24251. std::string frame;
  24252. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  24253. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  24254. frame += "Hello";
  24255. return frame;
  24256. };
  24257. // RSV1 set (0x40)
  24258. {
  24259. detail::BufferStream strm;
  24260. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  24261. ws::Opcode opcode;
  24262. std::string payload;
  24263. bool fin;
  24264. EXPECT_EQ(
  24265. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24266. ws::impl::FrameRead::ProtocolError);
  24267. }
  24268. // RSV2 set (0x20)
  24269. {
  24270. detail::BufferStream strm;
  24271. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  24272. ws::Opcode opcode;
  24273. std::string payload;
  24274. bool fin;
  24275. EXPECT_EQ(
  24276. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24277. ws::impl::FrameRead::ProtocolError);
  24278. }
  24279. // RSV3 set (0x10)
  24280. {
  24281. detail::BufferStream strm;
  24282. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  24283. ws::Opcode opcode;
  24284. std::string payload;
  24285. bool fin;
  24286. EXPECT_EQ(
  24287. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24288. ws::impl::FrameRead::ProtocolError);
  24289. }
  24290. // No RSV bits set - should succeed
  24291. {
  24292. detail::BufferStream strm;
  24293. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  24294. ws::Opcode opcode;
  24295. std::string payload;
  24296. bool fin;
  24297. EXPECT_EQ(
  24298. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24299. ws::impl::FrameRead::Ok);
  24300. EXPECT_EQ(ws::Opcode::Text, opcode);
  24301. EXPECT_EQ("Hello", payload);
  24302. EXPECT_TRUE(fin);
  24303. }
  24304. }
  24305. TEST(WebSocketTest, ControlFrameValidation) {
  24306. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  24307. // payload length <= 125.
  24308. // Ping with FIN=0 - must be rejected
  24309. {
  24310. detail::BufferStream strm;
  24311. std::string frame;
  24312. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  24313. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24314. strm.write(frame.data(), frame.size());
  24315. ws::Opcode opcode;
  24316. std::string payload;
  24317. bool fin;
  24318. EXPECT_EQ(
  24319. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24320. ws::impl::FrameRead::ProtocolError);
  24321. }
  24322. // Close with FIN=0 - must be rejected
  24323. {
  24324. detail::BufferStream strm;
  24325. std::string frame;
  24326. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  24327. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  24328. strm.write(frame.data(), frame.size());
  24329. ws::Opcode opcode;
  24330. std::string payload;
  24331. bool fin;
  24332. EXPECT_EQ(
  24333. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24334. ws::impl::FrameRead::ProtocolError);
  24335. }
  24336. // Ping with payload_len=126 (extended length) - must be rejected
  24337. {
  24338. detail::BufferStream strm;
  24339. std::string frame;
  24340. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24341. frame += static_cast<char>(126); // payload_len=126 (>125)
  24342. frame += static_cast<char>(0x00); // extended length high byte
  24343. frame += static_cast<char>(126); // extended length low byte
  24344. frame += std::string(126, 'x');
  24345. strm.write(frame.data(), frame.size());
  24346. ws::Opcode opcode;
  24347. std::string payload;
  24348. bool fin;
  24349. EXPECT_EQ(
  24350. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24351. ws::impl::FrameRead::ProtocolError);
  24352. }
  24353. // Ping with FIN=1 and payload_len=125 - should succeed
  24354. {
  24355. detail::BufferStream strm;
  24356. std::string frame;
  24357. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  24358. frame += static_cast<char>(125); // payload_len=125
  24359. frame += std::string(125, 'x');
  24360. strm.write(frame.data(), frame.size());
  24361. ws::Opcode opcode;
  24362. std::string payload;
  24363. bool fin;
  24364. EXPECT_EQ(
  24365. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24366. ws::impl::FrameRead::Ok);
  24367. EXPECT_EQ(ws::Opcode::Ping, opcode);
  24368. EXPECT_EQ(125u, payload.size());
  24369. EXPECT_TRUE(fin);
  24370. }
  24371. }
  24372. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  24373. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  24374. // length MUST be 0.
  24375. // MSB set - must be rejected
  24376. {
  24377. detail::BufferStream strm;
  24378. std::string frame;
  24379. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24380. frame += static_cast<char>(127); // 64-bit extended length
  24381. frame += static_cast<char>(0x80); // MSB set (invalid)
  24382. frame += std::string(7, '\0'); // remaining 7 bytes of length
  24383. strm.write(frame.data(), frame.size());
  24384. ws::Opcode opcode;
  24385. std::string payload;
  24386. bool fin;
  24387. EXPECT_EQ(
  24388. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24389. ws::impl::FrameRead::ProtocolError);
  24390. }
  24391. // MSB clear - should pass length parsing (will be rejected by max_len,
  24392. // but that's a different check; use a small length to verify)
  24393. {
  24394. detail::BufferStream strm;
  24395. std::string frame;
  24396. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  24397. frame += static_cast<char>(127); // 64-bit extended length
  24398. frame += std::string(7, '\0'); // high bytes = 0
  24399. frame += static_cast<char>(0x03); // length = 3
  24400. frame += "abc";
  24401. strm.write(frame.data(), frame.size());
  24402. ws::Opcode opcode;
  24403. std::string payload;
  24404. bool fin;
  24405. EXPECT_EQ(
  24406. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  24407. ws::impl::FrameRead::Ok);
  24408. EXPECT_EQ(ws::Opcode::Text, opcode);
  24409. EXPECT_EQ("abc", payload);
  24410. }
  24411. }
  24412. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  24413. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  24414. // Valid UTF-8
  24415. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  24416. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  24417. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  24418. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  24419. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  24420. // Invalid UTF-8
  24421. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  24422. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  24423. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  24424. EXPECT_FALSE(
  24425. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  24426. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  24427. }
  24428. TEST(WebSocketTest, ConnectAndDisconnect) {
  24429. Server svr;
  24430. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24431. std::string msg;
  24432. while (ws.read(msg)) {}
  24433. });
  24434. auto port = svr.bind_to_any_port(HOST);
  24435. std::thread t([&]() { svr.listen_after_bind(); });
  24436. svr.wait_until_ready();
  24437. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24438. auto res = client.connect();
  24439. ASSERT_TRUE(res);
  24440. EXPECT_EQ(Error::Success, res.error());
  24441. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  24442. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  24443. EXPECT_TRUE(client.is_open());
  24444. client.close();
  24445. EXPECT_FALSE(client.is_open());
  24446. svr.stop();
  24447. t.join();
  24448. }
  24449. TEST(WebSocketTest, ValidURL) {
  24450. ws::WebSocketClient ws1("ws://localhost:8080/path");
  24451. EXPECT_TRUE(ws1.is_valid());
  24452. ws::WebSocketClient ws2("ws://example.com/path");
  24453. EXPECT_TRUE(ws2.is_valid());
  24454. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  24455. EXPECT_TRUE(ws3.is_valid());
  24456. #ifdef CPPHTTPLIB_SSL_ENABLED
  24457. ws::WebSocketClient wss1("wss://example.com/path");
  24458. EXPECT_TRUE(wss1.is_valid());
  24459. ws::WebSocketClient wss2("wss://example.com:443/path");
  24460. EXPECT_TRUE(wss2.is_valid());
  24461. #endif
  24462. }
  24463. TEST(WebSocketTest, InvalidURL) {
  24464. // No scheme
  24465. ws::WebSocketClient ws1("localhost:8080/path");
  24466. EXPECT_FALSE(ws1.is_valid());
  24467. // No path
  24468. ws::WebSocketClient ws2("ws://localhost:8080");
  24469. EXPECT_FALSE(ws2.is_valid());
  24470. // Empty string
  24471. ws::WebSocketClient ws3("");
  24472. EXPECT_FALSE(ws3.is_valid());
  24473. // Missing host
  24474. ws::WebSocketClient ws4("ws://:8080/path");
  24475. EXPECT_FALSE(ws4.is_valid());
  24476. // Port number overflow — should not crash
  24477. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  24478. EXPECT_FALSE(ws5.is_valid());
  24479. // Port out of range
  24480. ws::WebSocketClient ws6("ws://localhost:99999/path");
  24481. EXPECT_FALSE(ws6.is_valid());
  24482. }
  24483. TEST(WebSocketTest, UnsupportedScheme) {
  24484. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  24485. ws::WebSocketClient ws1("http://localhost:8080/path");
  24486. EXPECT_FALSE(ws1.is_valid());
  24487. ws::WebSocketClient ws2("https://localhost:8080/path");
  24488. EXPECT_FALSE(ws2.is_valid());
  24489. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  24490. EXPECT_FALSE(ws3.is_valid());
  24491. #else
  24492. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  24493. std::invalid_argument);
  24494. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  24495. std::invalid_argument);
  24496. #endif
  24497. }
  24498. TEST(WebSocketTest, ConnectWhenInvalid) {
  24499. ws::WebSocketClient ws("not a valid url");
  24500. EXPECT_FALSE(ws.is_valid());
  24501. auto res = ws.connect();
  24502. EXPECT_FALSE(res);
  24503. EXPECT_EQ(Error::Connection, res.error());
  24504. EXPECT_EQ(-1, res.status());
  24505. }
  24506. TEST(WebSocketTest, ConnectRefusedReportsError) {
  24507. // Grab a port that is free, then close it again so nothing listens there
  24508. Server svr;
  24509. auto port = svr.bind_to_any_port(HOST);
  24510. svr.stop();
  24511. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24512. auto res = client.connect();
  24513. ASSERT_FALSE(res);
  24514. EXPECT_EQ(Error::Connection, res.error());
  24515. EXPECT_EQ(-1, res.status());
  24516. }
  24517. TEST(WebSocketTest, DefaultPort) {
  24518. ws::WebSocketClient ws1("ws://example.com/path");
  24519. EXPECT_TRUE(ws1.is_valid());
  24520. // ws:// defaults to port 80 (verified by successful parse)
  24521. #ifdef CPPHTTPLIB_SSL_ENABLED
  24522. ws::WebSocketClient ws2("wss://example.com/path");
  24523. EXPECT_TRUE(ws2.is_valid());
  24524. // wss:// defaults to port 443 (verified by successful parse)
  24525. #endif
  24526. }
  24527. TEST(WebSocketTest, IPv6LiteralAddress) {
  24528. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  24529. EXPECT_TRUE(ws1.is_valid());
  24530. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  24531. EXPECT_TRUE(ws2.is_valid());
  24532. }
  24533. TEST(WebSocketTest, ComplexPath) {
  24534. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  24535. EXPECT_TRUE(ws1.is_valid());
  24536. ws::WebSocketClient ws2("ws://localhost:8080/");
  24537. EXPECT_TRUE(ws2.is_valid());
  24538. }
  24539. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  24540. Server svr;
  24541. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24542. std::string msg;
  24543. while (ws.read(msg)) {}
  24544. });
  24545. auto port = svr.bind_to_any_port(HOST);
  24546. std::thread t([&]() { svr.listen_after_bind(); });
  24547. svr.wait_until_ready();
  24548. auto another_host = "example.com";
  24549. auto wrong_ip = "192.0.2.1";
  24550. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24551. client.set_direct_hostname_addr_map({{another_host, wrong_ip}});
  24552. ASSERT_TRUE(client.connect());
  24553. EXPECT_TRUE(client.is_open());
  24554. client.close();
  24555. svr.stop();
  24556. t.join();
  24557. }
  24558. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  24559. Server svr;
  24560. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  24561. std::string msg;
  24562. while (ws.read(msg)) {}
  24563. });
  24564. auto port = svr.bind_to_any_port(HOST);
  24565. std::thread t([&]() { svr.listen_after_bind(); });
  24566. svr.wait_until_ready();
  24567. auto wrong_ip = "192.0.2.1";
  24568. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24569. client.set_direct_hostname_addr_map({{"localhost", wrong_ip}});
  24570. client.set_connection_timeout(1);
  24571. client.set_read_timeout(1);
  24572. client.set_write_timeout(1);
  24573. EXPECT_FALSE(client.connect());
  24574. EXPECT_FALSE(client.is_open());
  24575. svr.stop();
  24576. t.join();
  24577. }
  24578. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  24579. // A mapped value that is not an IP literal must be resolved. HOST resolves
  24580. // from the hosts file, so this test needs no external DNS. "target.invalid"
  24581. // (RFC 6761) is only a map key and the Host header value.
  24582. auto host = "target.invalid";
  24583. Server svr;
  24584. std::string received_host;
  24585. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24586. received_host = req.get_header_value("Host");
  24587. std::string msg;
  24588. while (ws.read(msg)) {}
  24589. });
  24590. auto port = svr.bind_to_any_port(HOST);
  24591. std::thread t([&]() { svr.listen_after_bind(); });
  24592. // ASSERT_* below returns from the test body, which would leave t joinable
  24593. // and make ~thread call std::terminate.
  24594. auto se = detail::scope_exit([&] {
  24595. svr.stop();
  24596. if (t.joinable()) { t.join(); }
  24597. });
  24598. svr.wait_until_ready();
  24599. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  24600. std::to_string(port) + "/ws");
  24601. client.set_direct_hostname_addr_map({{host, HOST}});
  24602. ASSERT_TRUE(client.connect());
  24603. EXPECT_TRUE(client.is_open());
  24604. client.close();
  24605. svr.stop();
  24606. t.join();
  24607. // The mapping only redirects the connection; the identity stays host_.
  24608. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  24609. }
  24610. class WebSocketIntegrationTest : public ::testing::Test {
  24611. protected:
  24612. void SetUp() override {
  24613. server_ = httplib::detail::make_unique<Server>();
  24614. setup_server();
  24615. start_server();
  24616. }
  24617. void TearDown() override {
  24618. server_->stop();
  24619. if (server_thread_.joinable()) { server_thread_.join(); }
  24620. }
  24621. void setup_server() {
  24622. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24623. std::string msg;
  24624. ws::ReadResult ret;
  24625. while ((ret = ws.read(msg))) {
  24626. if (ret == ws::Binary) {
  24627. ws.send(msg.data(), msg.size());
  24628. } else {
  24629. ws.send(msg);
  24630. }
  24631. }
  24632. });
  24633. server_->WebSocket("/ws-echo-string",
  24634. [](const Request &, ws::WebSocket &ws) {
  24635. std::string msg;
  24636. while (ws.read(msg)) {
  24637. ws.send("echo: " + msg);
  24638. }
  24639. });
  24640. server_->WebSocket(
  24641. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  24642. // Echo back request metadata
  24643. ws.send("path:" + req.path);
  24644. ws.send("header:" + req.get_header_value("X-Test-Header"));
  24645. std::string msg;
  24646. while (ws.read(msg)) {}
  24647. });
  24648. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  24649. std::string msg;
  24650. ws.read(msg); // wait for a message
  24651. ws.close();
  24652. });
  24653. server_->WebSocket("/ws-close-status",
  24654. [](const Request &, ws::WebSocket &ws) {
  24655. std::string msg;
  24656. ws.read(msg); // wait for a message
  24657. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  24658. });
  24659. server_->WebSocket(
  24660. "/ws-subprotocol",
  24661. [](const Request &, ws::WebSocket &ws) {
  24662. std::string msg;
  24663. while (ws.read(msg)) {
  24664. ws.send(msg);
  24665. }
  24666. },
  24667. [](const std::vector<std::string> &protocols) -> std::string {
  24668. for (const auto &p : protocols) {
  24669. if (p == "graphql-ws") { return p; }
  24670. }
  24671. return "";
  24672. });
  24673. server_->WebSocket(
  24674. "/ws-subprotocol-unoffered",
  24675. [](const Request &, ws::WebSocket &ws) {
  24676. std::string msg;
  24677. while (ws.read(msg)) {
  24678. ws.send(msg);
  24679. }
  24680. },
  24681. [](const std::vector<std::string> &) -> std::string {
  24682. return "admin";
  24683. });
  24684. }
  24685. void start_server() {
  24686. port_ = server_->bind_to_any_port(HOST);
  24687. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24688. server_->wait_until_ready();
  24689. }
  24690. std::unique_ptr<Server> server_;
  24691. std::thread server_thread_;
  24692. int port_ = 0;
  24693. };
  24694. TEST_F(WebSocketIntegrationTest, TextEcho) {
  24695. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24696. "/ws-echo");
  24697. ASSERT_TRUE(client.connect());
  24698. ASSERT_TRUE(client.is_open());
  24699. ASSERT_TRUE(client.send("Hello WebSocket"));
  24700. std::string msg;
  24701. EXPECT_EQ(ws::Text, client.read(msg));
  24702. EXPECT_EQ("Hello WebSocket", msg);
  24703. client.close();
  24704. }
  24705. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  24706. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24707. "/ws-echo");
  24708. ASSERT_TRUE(client.connect());
  24709. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  24710. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  24711. std::string msg;
  24712. EXPECT_EQ(ws::Binary, client.read(msg));
  24713. EXPECT_EQ(binary_data, msg);
  24714. client.close();
  24715. }
  24716. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  24717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24718. "/ws-echo");
  24719. ASSERT_TRUE(client.connect());
  24720. for (int i = 0; i < 10; i++) {
  24721. auto text = "message " + std::to_string(i);
  24722. ASSERT_TRUE(client.send(text));
  24723. std::string msg;
  24724. ASSERT_TRUE(client.read(msg));
  24725. EXPECT_EQ(text, msg);
  24726. }
  24727. client.close();
  24728. }
  24729. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  24730. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24731. "/ws-close");
  24732. ASSERT_TRUE(client.connect());
  24733. // Send a message to trigger the server to close
  24734. ASSERT_TRUE(client.send("trigger close"));
  24735. // The server will close, so read should return false
  24736. std::string msg;
  24737. EXPECT_FALSE(client.read(msg));
  24738. EXPECT_FALSE(client.is_open());
  24739. EXPECT_EQ(ws::CloseStatus::Normal, client.close_status());
  24740. EXPECT_EQ("", client.close_reason());
  24741. }
  24742. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  24743. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24744. "/ws-echo");
  24745. ASSERT_TRUE(client.connect());
  24746. // 128KB message
  24747. std::string large_data(128 * 1024, 'X');
  24748. ASSERT_TRUE(client.send(large_data));
  24749. std::string msg;
  24750. ASSERT_TRUE(client.read(msg));
  24751. EXPECT_EQ(large_data, msg);
  24752. client.close();
  24753. }
  24754. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  24755. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24756. "/ws-echo");
  24757. ASSERT_TRUE(client.connect());
  24758. const int num_threads = 4;
  24759. std::vector<std::thread> threads;
  24760. std::atomic<int> send_count{0};
  24761. for (int t = 0; t < num_threads; t++) {
  24762. threads.emplace_back([&client, &send_count, t]() {
  24763. for (int i = 0; i < 5; i++) {
  24764. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  24765. if (client.send(text)) { send_count++; }
  24766. }
  24767. });
  24768. }
  24769. for (auto &th : threads) {
  24770. th.join();
  24771. }
  24772. int received = 0;
  24773. std::string msg;
  24774. while (received < send_count.load()) {
  24775. if (!client.read(msg)) { break; }
  24776. received++;
  24777. }
  24778. EXPECT_EQ(send_count.load(), received);
  24779. client.close();
  24780. }
  24781. TEST_F(WebSocketIntegrationTest, ReadString) {
  24782. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24783. "/ws-echo-string");
  24784. ASSERT_TRUE(client.connect());
  24785. ASSERT_TRUE(client.send("hello"));
  24786. std::string msg;
  24787. ASSERT_TRUE(client.read(msg));
  24788. EXPECT_EQ("echo: hello", msg);
  24789. ASSERT_TRUE(client.send("world"));
  24790. ASSERT_TRUE(client.read(msg));
  24791. EXPECT_EQ("echo: world", msg);
  24792. client.close();
  24793. }
  24794. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  24795. Headers headers = {{"X-Test-Header", "test-value"}};
  24796. ws::WebSocketClient client(
  24797. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  24798. ASSERT_TRUE(client.connect());
  24799. std::string msg;
  24800. ASSERT_TRUE(client.read(msg));
  24801. EXPECT_EQ("path:/ws-request-info", msg);
  24802. ASSERT_TRUE(client.read(msg));
  24803. EXPECT_EQ("header:test-value", msg);
  24804. client.close();
  24805. }
  24806. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  24807. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24808. "/ws-echo");
  24809. client.set_read_timeout(1, 0); // 1 second
  24810. ASSERT_TRUE(client.connect());
  24811. // Don't send anything — server echo handler waits for a message, so read()
  24812. // should time out. The connection survives it: nothing was consumed.
  24813. std::string msg;
  24814. EXPECT_EQ(client.read(msg), ws::Timeout);
  24815. EXPECT_TRUE(client.is_open());
  24816. // And it is still usable afterwards.
  24817. EXPECT_TRUE(client.send("after timeout"));
  24818. EXPECT_EQ(client.read(msg), ws::Text);
  24819. EXPECT_EQ(msg, "after timeout");
  24820. }
  24821. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  24822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24823. "/ws-echo");
  24824. client.set_read_timeout(1, 0);
  24825. ASSERT_TRUE(client.connect());
  24826. ASSERT_TRUE(client.send("first"));
  24827. std::string msg;
  24828. ASSERT_EQ(client.read(msg), ws::Text);
  24829. ASSERT_EQ(msg, "first");
  24830. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  24831. // not be used with a read timeout: it would reprocess the previous message.
  24832. EXPECT_EQ(client.read(msg), ws::Timeout);
  24833. EXPECT_EQ(msg, "first");
  24834. }
  24835. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  24836. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24837. "/ws-echo");
  24838. ASSERT_TRUE(client.connect());
  24839. // Setting it once the connection is open reaches the live stream, not just
  24840. // the seed for the next connect().
  24841. client.set_read_timeout(1, 0);
  24842. std::string msg;
  24843. EXPECT_EQ(client.read(msg), ws::Timeout);
  24844. EXPECT_TRUE(client.is_open());
  24845. }
  24846. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  24847. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24848. "/nonexistent");
  24849. auto res = client.connect();
  24850. EXPECT_FALSE(res);
  24851. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24852. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  24853. EXPECT_FALSE(client.is_open());
  24854. }
  24855. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  24856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24857. "/ws-echo");
  24858. ASSERT_TRUE(client.connect());
  24859. ASSERT_TRUE(client.send(""));
  24860. std::string msg;
  24861. EXPECT_EQ(ws::Text, client.read(msg));
  24862. EXPECT_EQ("", msg);
  24863. client.close();
  24864. }
  24865. TEST_F(WebSocketIntegrationTest, Reconnect) {
  24866. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24867. "/ws-echo");
  24868. // First connection
  24869. ASSERT_TRUE(client.connect());
  24870. ASSERT_TRUE(client.send("first"));
  24871. std::string msg;
  24872. ASSERT_TRUE(client.read(msg));
  24873. EXPECT_EQ("first", msg);
  24874. client.close();
  24875. EXPECT_FALSE(client.is_open());
  24876. // Reconnect using the same client object
  24877. ASSERT_TRUE(client.connect());
  24878. ASSERT_TRUE(client.is_open());
  24879. ASSERT_TRUE(client.send("second"));
  24880. ASSERT_TRUE(client.read(msg));
  24881. EXPECT_EQ("second", msg);
  24882. client.close();
  24883. }
  24884. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  24885. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24886. "/ws-close-status");
  24887. ASSERT_TRUE(client.connect());
  24888. // Trigger the server to close with GoingAway status
  24889. ASSERT_TRUE(client.send("trigger"));
  24890. // read() should return false after receiving the close frame
  24891. std::string msg;
  24892. EXPECT_FALSE(client.read(msg));
  24893. EXPECT_FALSE(client.is_open());
  24894. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  24895. EXPECT_EQ("shutting down", client.close_reason());
  24896. // A copy, so it outlives a reconnect that replaces the connection
  24897. static_assert(
  24898. std::is_same<decltype(client.close_reason()), std::string>::value, "");
  24899. }
  24900. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  24901. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24902. "/ws-echo");
  24903. EXPECT_EQ(ws::CloseStatus::Abnormal, client.close_status());
  24904. ASSERT_TRUE(client.connect());
  24905. client.close(ws::CloseStatus::GoingAway, "client leaving");
  24906. EXPECT_FALSE(client.is_open());
  24907. // The server echoes the Close it receives
  24908. EXPECT_EQ(ws::CloseStatus::GoingAway, client.close_status());
  24909. EXPECT_EQ("client leaving", client.close_reason());
  24910. }
  24911. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  24912. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  24913. ws::WebSocketClient client(
  24914. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24915. ASSERT_TRUE(client.connect());
  24916. // Server should have selected graphql-ws
  24917. EXPECT_EQ("graphql-ws", client.subprotocol());
  24918. client.close();
  24919. }
  24920. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  24921. Headers headers;
  24922. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  24923. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  24924. ws::WebSocketClient client(
  24925. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24926. ASSERT_TRUE(client.connect());
  24927. // The offer on the second field line counts too, so graphql-ws is selected
  24928. EXPECT_EQ("graphql-ws", client.subprotocol());
  24929. client.close();
  24930. }
  24931. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  24932. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  24933. ws::WebSocketClient client(
  24934. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  24935. ASSERT_TRUE(client.connect());
  24936. // Server should not have selected any subprotocol
  24937. EXPECT_TRUE(client.subprotocol().empty());
  24938. client.close();
  24939. }
  24940. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  24941. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24942. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24943. "/ws-subprotocol-unoffered",
  24944. headers);
  24945. ASSERT_TRUE(client.connect());
  24946. EXPECT_TRUE(client.subprotocol().empty());
  24947. client.close();
  24948. }
  24949. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  24950. // Connect without requesting any subprotocol
  24951. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24952. "/ws-subprotocol");
  24953. ASSERT_TRUE(client.connect());
  24954. EXPECT_TRUE(client.subprotocol().empty());
  24955. client.close();
  24956. }
  24957. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  24958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24959. "/ws-echo");
  24960. client.set_tcp_nodelay(true);
  24961. client.set_connection_timeout(3, 0);
  24962. bool socket_options_called = false;
  24963. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  24964. ASSERT_TRUE(client.connect());
  24965. ASSERT_TRUE(client.is_open());
  24966. EXPECT_TRUE(socket_options_called);
  24967. ASSERT_TRUE(client.send("hello"));
  24968. std::string msg;
  24969. auto result = client.read(msg);
  24970. EXPECT_EQ(result, ws::ReadResult::Text);
  24971. EXPECT_EQ(msg, "hello");
  24972. client.close();
  24973. }
  24974. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  24975. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  24976. "/ws-echo");
  24977. client.set_connection_timeout(std::chrono::seconds(3));
  24978. client.set_write_timeout(std::chrono::seconds(3));
  24979. // A sub-second remainder exercises the seconds/microseconds split.
  24980. client.set_read_timeout(std::chrono::milliseconds(1500));
  24981. ASSERT_TRUE(client.connect());
  24982. auto start = std::chrono::steady_clock::now();
  24983. std::string msg;
  24984. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  24985. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  24986. std::chrono::steady_clock::now() - start)
  24987. .count();
  24988. // Above 1s so that dropping the microseconds half of the split fails here.
  24989. // Ignoring the setter altogether would not reach this line at all: a client
  24990. // waits forever by default.
  24991. EXPECT_GE(elapsed, 1400);
  24992. EXPECT_LT(elapsed, 30000);
  24993. }
  24994. #ifndef _WIN32
  24995. // A send() that times out after part of the data went out returns the count
  24996. // written so far. Every byte of the frame must still be sent, or the peer reads
  24997. // the next frame's header and payload as the rest of this one.
  24998. TEST(WebSocketPartialWriteTest, FrameIsWrittenWhole) {
  24999. signal(SIGPIPE, SIG_IGN);
  25000. const std::string large(4 * 1024 * 1024, 'A');
  25001. std::atomic<bool> large_sent{false};
  25002. std::atomic<bool> small_sent{false};
  25003. Server svr;
  25004. svr.set_write_timeout(0, 500000);
  25005. svr.set_socket_options([](socket_t sock) {
  25006. int size = 8192;
  25007. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25008. reinterpret_cast<const char *>(&size), sizeof(size));
  25009. });
  25010. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25011. large_sent = ws.send(large.data(), large.size());
  25012. small_sent = ws.send("after");
  25013. std::string msg;
  25014. while (ws.read(msg)) {}
  25015. });
  25016. auto port = svr.bind_to_any_port(HOST);
  25017. std::thread t([&]() { svr.listen_after_bind(); });
  25018. auto se = detail::scope_exit([&] {
  25019. svr.stop();
  25020. t.join();
  25021. });
  25022. svr.wait_until_ready();
  25023. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25024. std::to_string(port) + "/ws");
  25025. client.set_read_timeout(5);
  25026. client.set_socket_options([](socket_t sock) {
  25027. int size = 8192;
  25028. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25029. reinterpret_cast<const char *>(&size), sizeof(size));
  25030. });
  25031. ASSERT_TRUE(client.connect());
  25032. // Outlast the server's write timeout, then drain.
  25033. std::this_thread::sleep_for(std::chrono::milliseconds(750));
  25034. std::string msg;
  25035. EXPECT_EQ(ws::ReadResult::Binary, client.read(msg));
  25036. EXPECT_TRUE(msg == large);
  25037. EXPECT_EQ(ws::ReadResult::Text, client.read(msg));
  25038. EXPECT_EQ("after", msg);
  25039. EXPECT_TRUE(large_sent);
  25040. EXPECT_TRUE(small_sent);
  25041. client.close();
  25042. }
  25043. // A send() that fails partway leaves a frame on the wire whose header announces
  25044. // more than was sent. Nothing may follow it, or the peer reads the next frames
  25045. // as the rest of it and a later payload's bytes as a frame of their own.
  25046. TEST(WebSocketPartialWriteTest, FailedWriteClosesConnection) {
  25047. signal(SIGPIPE, SIG_IGN);
  25048. const std::string large(4 * 1024 * 1024, 'A');
  25049. std::atomic<bool> large_sent{true};
  25050. std::atomic<bool> open_after_failure{true};
  25051. std::atomic<bool> handler_done{false};
  25052. Server svr;
  25053. svr.set_write_timeout(0, 200000);
  25054. svr.set_socket_options([](socket_t sock) {
  25055. int size = 8192;
  25056. setsockopt(sock, SOL_SOCKET, SO_SNDBUF,
  25057. reinterpret_cast<const char *>(&size), sizeof(size));
  25058. });
  25059. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  25060. large_sent = ws.send(large.data(), large.size());
  25061. open_after_failure = ws.is_open();
  25062. handler_done = true;
  25063. });
  25064. auto port = svr.bind_to_any_port(HOST);
  25065. std::thread t([&]() { svr.listen_after_bind(); });
  25066. auto se = detail::scope_exit([&] {
  25067. svr.stop();
  25068. t.join();
  25069. });
  25070. svr.wait_until_ready();
  25071. ws::WebSocketClient client("ws://" + std::string(HOST) + ":" +
  25072. std::to_string(port) + "/ws");
  25073. client.set_socket_options([](socket_t sock) {
  25074. int size = 8192;
  25075. setsockopt(sock, SOL_SOCKET, SO_RCVBUF,
  25076. reinterpret_cast<const char *>(&size), sizeof(size));
  25077. });
  25078. ASSERT_TRUE(client.connect());
  25079. // Read nothing, so the server's write times out partway through the frame.
  25080. for (int i = 0; i < 100 && !handler_done; i++) {
  25081. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  25082. }
  25083. ASSERT_TRUE(handler_done);
  25084. ASSERT_FALSE(large_sent);
  25085. EXPECT_FALSE(open_after_failure);
  25086. client.close();
  25087. }
  25088. #endif
  25089. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  25090. Server svr;
  25091. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25092. if (!req.has_header("Authorization")) {
  25093. res.status = StatusCode::Unauthorized_401;
  25094. res.set_content("Unauthorized", "text/plain");
  25095. return Server::HandlerResponse::Handled;
  25096. }
  25097. return Server::HandlerResponse::Unhandled;
  25098. });
  25099. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25100. std::string msg;
  25101. while (ws.read(msg)) {
  25102. ws.send(msg);
  25103. }
  25104. });
  25105. auto port = svr.bind_to_any_port("localhost");
  25106. std::thread t([&]() { svr.listen_after_bind(); });
  25107. svr.wait_until_ready();
  25108. // Without Authorization header - should be rejected before upgrade
  25109. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  25110. EXPECT_FALSE(client1.connect());
  25111. // The rejection is framed like any other HTTP response
  25112. {
  25113. Client cli("localhost", port);
  25114. Headers headers = {{"Upgrade", "websocket"},
  25115. {"Connection", "Upgrade"},
  25116. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25117. {"Sec-WebSocket-Version", "13"}};
  25118. auto res = cli.Get("/ws", headers);
  25119. ASSERT_TRUE(res);
  25120. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25121. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25122. EXPECT_EQ("Unauthorized", res->body);
  25123. }
  25124. // With Authorization header - should succeed
  25125. Headers headers = {{"Authorization", "Bearer token123"}};
  25126. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  25127. headers);
  25128. ASSERT_TRUE(client2.connect());
  25129. ASSERT_TRUE(client2.send("hello"));
  25130. std::string msg;
  25131. ASSERT_TRUE(client2.read(msg));
  25132. EXPECT_EQ("hello", msg);
  25133. client2.close();
  25134. svr.stop();
  25135. t.join();
  25136. }
  25137. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  25138. Server svr;
  25139. std::atomic<int> pre_routing_calls{0};
  25140. std::atomic<int> pre_request_calls{0};
  25141. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  25142. pre_routing_calls++;
  25143. if (req.path == "/handled") {
  25144. res.set_content("handled", "text/plain");
  25145. return Server::HandlerResponse::Handled;
  25146. }
  25147. return Server::HandlerResponse::Unhandled;
  25148. });
  25149. svr.set_pre_request_handler([&](const Request &, Response &) {
  25150. pre_request_calls++;
  25151. return Server::HandlerResponse::Unhandled;
  25152. });
  25153. svr.Get("/http", [](const Request &, Response &res) {
  25154. res.set_content("http", "text/plain");
  25155. });
  25156. svr.WebSocket("/ws",
  25157. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25158. auto port = svr.bind_to_any_port("localhost");
  25159. std::thread t([&]() { svr.listen_after_bind(); });
  25160. auto se = detail::scope_exit([&] {
  25161. svr.stop();
  25162. t.join();
  25163. });
  25164. svr.wait_until_ready();
  25165. Headers upgrade = {{"Upgrade", "websocket"},
  25166. {"Connection", "Upgrade"},
  25167. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25168. {"Sec-WebSocket-Version", "13"}};
  25169. auto get = [&](const char *path) {
  25170. pre_routing_calls = 0;
  25171. return Client("localhost", port).Get(path, upgrade);
  25172. };
  25173. // No WebSocket route, but an HTTP one
  25174. auto res = get("/http");
  25175. ASSERT_TRUE(res);
  25176. EXPECT_EQ(StatusCode::OK_200, res->status);
  25177. EXPECT_EQ("http", res->body);
  25178. EXPECT_EQ(1, pre_routing_calls);
  25179. EXPECT_EQ(1, pre_request_calls);
  25180. // No route at all
  25181. res = get("/none");
  25182. ASSERT_TRUE(res);
  25183. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25184. EXPECT_EQ(1, pre_routing_calls);
  25185. // Answered by the pre-routing handler
  25186. res = get("/handled");
  25187. ASSERT_TRUE(res);
  25188. EXPECT_EQ(StatusCode::OK_200, res->status);
  25189. EXPECT_EQ("handled", res->body);
  25190. EXPECT_EQ(1, pre_routing_calls);
  25191. // A WebSocket route
  25192. pre_routing_calls = 0;
  25193. pre_request_calls = 0;
  25194. {
  25195. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25196. "/ws");
  25197. ASSERT_TRUE(client.connect());
  25198. std::string msg;
  25199. ASSERT_TRUE(client.read(msg));
  25200. EXPECT_EQ("ws", msg);
  25201. client.close();
  25202. }
  25203. EXPECT_EQ(1, pre_routing_calls);
  25204. EXPECT_EQ(1, pre_request_calls);
  25205. }
  25206. // An upgrade request answered by a hook leaves its body unread, so that body
  25207. // must not be served as the next request on the connection.
  25208. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  25209. Server svr;
  25210. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  25211. if (req.path == "/pre-routing") {
  25212. res.set_content("pre-routing", "text/plain");
  25213. return Server::HandlerResponse::Handled;
  25214. }
  25215. return Server::HandlerResponse::Unhandled;
  25216. });
  25217. svr.set_pre_request_handler([](const Request &req, Response &res) {
  25218. if (req.matched_route == "/pre-request") {
  25219. res.set_content("pre-request", "text/plain");
  25220. return Server::HandlerResponse::Handled;
  25221. }
  25222. return Server::HandlerResponse::Unhandled;
  25223. });
  25224. svr.Get("/smuggled", [](const Request &, Response &res) {
  25225. res.set_content("smuggled", "text/plain");
  25226. });
  25227. svr.WebSocket("/pre-request",
  25228. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  25229. auto port = svr.bind_to_any_port(HOST);
  25230. std::thread t([&]() { svr.listen_after_bind(); });
  25231. auto se = detail::scope_exit([&] {
  25232. svr.stop();
  25233. t.join();
  25234. });
  25235. svr.wait_until_ready();
  25236. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25237. for (auto path : {"/pre-routing", "/pre-request"}) {
  25238. std::string req = std::string("GET ") + path +
  25239. " HTTP/1.1\r\n"
  25240. "Host: localhost\r\n"
  25241. "Upgrade: websocket\r\n"
  25242. "Connection: Upgrade\r\n"
  25243. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  25244. "Sec-WebSocket-Version: 13\r\n"
  25245. "Content-Length: " +
  25246. std::to_string(body.size()) + "\r\n\r\n" + body;
  25247. std::string res;
  25248. ASSERT_TRUE(send_request(5, req, &res, port));
  25249. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  25250. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  25251. // Only one response, and the body was not served as a request
  25252. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  25253. }
  25254. }
  25255. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  25256. Server svr;
  25257. std::atomic<int> pre_request_calls{0};
  25258. std::atomic<bool> route_matched{false};
  25259. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  25260. pre_request_calls++;
  25261. if (req.matched_route == "/ws/:id") { route_matched = true; }
  25262. if (req.get_header_value("Authorization") != "Bearer token123") {
  25263. res.status = StatusCode::Unauthorized_401;
  25264. res.set_content("Unauthorized", "text/plain");
  25265. return Server::HandlerResponse::Handled;
  25266. }
  25267. return Server::HandlerResponse::Unhandled;
  25268. });
  25269. std::atomic<bool> handler_called{false};
  25270. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  25271. handler_called = true;
  25272. ws.send(req.matched_route + " " + req.path_params.at("id"));
  25273. });
  25274. auto port = svr.bind_to_any_port("localhost");
  25275. std::thread t([&]() { svr.listen_after_bind(); });
  25276. svr.wait_until_ready();
  25277. // Without Authorization header - should be rejected before upgrade
  25278. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  25279. "/ws/1");
  25280. EXPECT_FALSE(client1.connect());
  25281. EXPECT_FALSE(handler_called);
  25282. EXPECT_EQ(1, pre_request_calls);
  25283. EXPECT_TRUE(route_matched);
  25284. // The rejection is an ordinary HTTP response, not a protocol switch
  25285. {
  25286. Client cli("localhost", port);
  25287. Headers headers = {{"Upgrade", "websocket"},
  25288. {"Connection", "Upgrade"},
  25289. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25290. {"Sec-WebSocket-Version", "13"}};
  25291. auto res = cli.Get("/ws/1", headers);
  25292. ASSERT_TRUE(res);
  25293. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  25294. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  25295. EXPECT_EQ("Unauthorized", res->body);
  25296. }
  25297. EXPECT_FALSE(handler_called);
  25298. // With Authorization header - should succeed
  25299. Headers headers = {{"Authorization", "Bearer token123"}};
  25300. ws::WebSocketClient client2(
  25301. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  25302. ASSERT_TRUE(client2.connect());
  25303. std::string msg;
  25304. ASSERT_TRUE(client2.read(msg));
  25305. EXPECT_EQ("/ws/:id 2", msg);
  25306. EXPECT_TRUE(handler_called);
  25307. client2.close();
  25308. svr.stop();
  25309. t.join();
  25310. }
  25311. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  25312. static Headers websocket_upgrade_headers() {
  25313. return {{"Upgrade", "websocket"},
  25314. {"Connection", "Upgrade"},
  25315. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25316. {"Sec-WebSocket-Version", "13"},
  25317. {"Sec-WebSocket-Protocol", "chat"}};
  25318. }
  25319. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  25320. Server svr;
  25321. svr.set_pre_routing_handler([](const Request &req, Response &) {
  25322. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  25323. return Server::HandlerResponse::Unhandled;
  25324. });
  25325. svr.set_pre_request_handler([](const Request &req, Response &) {
  25326. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  25327. return Server::HandlerResponse::Unhandled;
  25328. });
  25329. svr.set_exception_handler(
  25330. [](const Request &, Response &res, std::exception_ptr ep) {
  25331. try {
  25332. std::rethrow_exception(ep);
  25333. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  25334. });
  25335. auto handler = [](const Request &, ws::WebSocket &) {};
  25336. svr.WebSocket("/pre-routing", handler);
  25337. svr.WebSocket("/pre-request", handler);
  25338. svr.WebSocket("/sub-protocol", handler,
  25339. [](const std::vector<std::string> &) -> std::string {
  25340. throw std::runtime_error("/sub-protocol");
  25341. });
  25342. auto port = svr.bind_to_any_port(HOST);
  25343. ASSERT_GT(port, 0);
  25344. thread t = thread([&] { svr.listen_after_bind(); });
  25345. auto se = detail::scope_exit([&] {
  25346. svr.stop();
  25347. t.join();
  25348. ASSERT_FALSE(svr.is_running());
  25349. });
  25350. svr.wait_until_ready();
  25351. Client cli(HOST, port);
  25352. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  25353. auto res = cli.Get(path, websocket_upgrade_headers());
  25354. if (!res) {
  25355. ADD_FAILURE() << path << ": " << to_string(res.error());
  25356. continue;
  25357. }
  25358. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  25359. EXPECT_EQ(path, res->body);
  25360. }
  25361. }
  25362. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  25363. Server svr;
  25364. svr.set_pre_routing_handler(
  25365. [](const Request &, Response &) -> Server::HandlerResponse {
  25366. throw std::runtime_error("pre-routing");
  25367. });
  25368. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25369. auto port = svr.bind_to_any_port(HOST);
  25370. ASSERT_GT(port, 0);
  25371. thread t = thread([&] { svr.listen_after_bind(); });
  25372. auto se = detail::scope_exit([&] {
  25373. svr.stop();
  25374. t.join();
  25375. ASSERT_FALSE(svr.is_running());
  25376. });
  25377. svr.wait_until_ready();
  25378. Client cli(HOST, port);
  25379. auto res = cli.Get("/ws", websocket_upgrade_headers());
  25380. ASSERT_TRUE(res) << to_string(res.error());
  25381. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  25382. }
  25383. #endif
  25384. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  25385. Server svr;
  25386. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  25387. // A read timeout is how a handler gets control back. Without it, a handler
  25388. // parked in read() can never write on the connection it is reading.
  25389. ws.set_read_timeout(std::chrono::milliseconds(100));
  25390. std::string msg;
  25391. while (ws.is_open()) {
  25392. auto r = ws.read(msg);
  25393. if (r == httplib::ws::Timeout) {
  25394. ws.send("tick");
  25395. continue;
  25396. }
  25397. if (r == httplib::ws::Fail) { break; }
  25398. ws.send(msg);
  25399. }
  25400. });
  25401. auto port = svr.bind_to_any_port("localhost");
  25402. std::thread t([&]() { svr.listen_after_bind(); });
  25403. svr.wait_until_ready();
  25404. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25405. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  25406. ASSERT_TRUE(client.connect());
  25407. // The client sends nothing, so anything it receives came out of the
  25408. // handler's timeout path.
  25409. std::string msg;
  25410. ASSERT_EQ(client.read(msg), ws::Text);
  25411. EXPECT_EQ("tick", msg);
  25412. client.close();
  25413. svr.stop();
  25414. t.join();
  25415. }
  25416. // Stream::read may return fewer bytes than asked for. This is that contract at
  25417. // its worst -- one byte per call -- which is what a frame header straddling a
  25418. // read buffer's boundary looks like to the frame parser.
  25419. class WsByteAtATimeStream : public Stream {
  25420. public:
  25421. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  25422. bool is_readable() const override { return true; }
  25423. bool wait_readable() const override { return true; }
  25424. bool wait_writable() const override { return true; }
  25425. ssize_t read(char *ptr, size_t size) override {
  25426. if (size == 0 || pos_ >= data_.size()) { return 0; }
  25427. *ptr = data_[pos_++];
  25428. return 1;
  25429. }
  25430. ssize_t write(const char *, size_t size) override {
  25431. return static_cast<ssize_t>(size);
  25432. }
  25433. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25434. ip = "127.0.0.1";
  25435. port = 0;
  25436. }
  25437. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25438. ip = "127.0.0.1";
  25439. port = 0;
  25440. }
  25441. socket_t socket() const override { return INVALID_SOCKET; }
  25442. time_t duration() const override { return 0; }
  25443. private:
  25444. std::string data_;
  25445. size_t pos_ = 0;
  25446. };
  25447. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  25448. // The payload uses the 16-bit extended length, so the header, the length
  25449. // and the mask key are all multi-byte fields here. Each used to be read
  25450. // with a single read() call, which fails as soon as one is split. The
  25451. // payload is also a little over one read chunk, so it is read in two.
  25452. std::string body;
  25453. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  25454. body += static_cast<char>(i % 251);
  25455. }
  25456. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  25457. std::string frame;
  25458. frame += static_cast<char>(0x81); // FIN + Text
  25459. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  25460. frame += static_cast<char>(body.size() >> 8);
  25461. frame += static_cast<char>(body.size() & 0xff);
  25462. for (size_t i = 0; i < 4; i++) {
  25463. frame += static_cast<char>(mask[i]);
  25464. }
  25465. for (size_t i = 0; i < body.size(); i++) {
  25466. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  25467. }
  25468. WsByteAtATimeStream strm(frame);
  25469. ws::Opcode opcode;
  25470. std::string payload;
  25471. bool fin = false;
  25472. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  25473. /*expect_masked=*/true, body.size()),
  25474. ws::impl::FrameRead::Ok);
  25475. EXPECT_TRUE(fin);
  25476. EXPECT_EQ(opcode, ws::Opcode::Text);
  25477. EXPECT_EQ(payload, body);
  25478. }
  25479. // Keeps what is written, counting the writes, and reads it back.
  25480. class WsWriteCountingStream : public Stream {
  25481. public:
  25482. bool is_readable() const override { return true; }
  25483. bool wait_readable() const override { return true; }
  25484. bool wait_writable() const override { return true; }
  25485. ssize_t read(char *ptr, size_t size) override {
  25486. auto n = (std::min)(size, data_.size() - pos_);
  25487. if (n == 0) { return 0; }
  25488. memcpy(ptr, data_.data() + pos_, n);
  25489. pos_ += n;
  25490. return static_cast<ssize_t>(n);
  25491. }
  25492. ssize_t write(const char *ptr, size_t size) override {
  25493. writes++;
  25494. data_.append(ptr, size);
  25495. return static_cast<ssize_t>(size);
  25496. }
  25497. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25498. ip = "127.0.0.1";
  25499. port = 0;
  25500. }
  25501. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25502. ip = "127.0.0.1";
  25503. port = 0;
  25504. }
  25505. socket_t socket() const override { return INVALID_SOCKET; }
  25506. time_t duration() const override { return 0; }
  25507. int writes = 0;
  25508. private:
  25509. std::string data_;
  25510. size_t pos_ = 0;
  25511. };
  25512. TEST(WebSocketFrameTest, AFrameGoesOutWithItsHeaderInOneWrite) {
  25513. // Under TCP_NODELAY each write is a segment of its own. Each length form,
  25514. // masked and not, reads back as written; a payload over one chunk follows
  25515. // its first in more writes.
  25516. for (auto len : {size_t(5), size_t(200), size_t(70000)}) {
  25517. for (auto mask : {false, true}) {
  25518. std::string body(len, '\0');
  25519. for (size_t i = 0; i < len; i++) {
  25520. body[i] = static_cast<char>(i % 251);
  25521. }
  25522. WsWriteCountingStream strm;
  25523. ASSERT_TRUE(detail::write_websocket_frame(
  25524. strm, ws::Opcode::Binary, body.data(), body.size(), true, mask));
  25525. if (len <= 4096) { EXPECT_EQ(1, strm.writes) << len << " " << mask; }
  25526. ws::Opcode opcode;
  25527. std::string payload;
  25528. bool fin = false;
  25529. ASSERT_EQ(
  25530. ws::impl::read_websocket_frame(strm, opcode, payload, fin, mask, 0),
  25531. ws::impl::FrameRead::Ok)
  25532. << len << " " << mask;
  25533. EXPECT_TRUE(fin);
  25534. EXPECT_EQ(ws::Opcode::Binary, opcode);
  25535. EXPECT_EQ(body, payload) << len << " " << mask;
  25536. }
  25537. }
  25538. }
  25539. // Hands out its pieces one read at a time, timing out between each two.
  25540. class WsTimeoutBetweenPiecesStream : public Stream {
  25541. public:
  25542. explicit WsTimeoutBetweenPiecesStream(std::vector<std::string> pieces)
  25543. : pieces_(std::move(pieces)) {}
  25544. bool is_readable() const override { return true; }
  25545. bool wait_readable() const override { return true; }
  25546. bool wait_writable() const override { return true; }
  25547. ssize_t read(char *ptr, size_t size) override {
  25548. if (time_out_) {
  25549. time_out_ = false;
  25550. error_ = Error::Timeout;
  25551. return -1;
  25552. }
  25553. if (i_ >= pieces_.size()) {
  25554. error_ = Error::ConnectionClosed;
  25555. return 0;
  25556. }
  25557. auto &piece = pieces_[i_];
  25558. auto n = (std::min)(size, piece.size() - at_);
  25559. memcpy(ptr, piece.data() + at_, n);
  25560. at_ += n;
  25561. if (at_ == piece.size()) {
  25562. i_++;
  25563. at_ = 0;
  25564. time_out_ = true;
  25565. }
  25566. return static_cast<ssize_t>(n);
  25567. }
  25568. ssize_t write(const char *, size_t size) override {
  25569. return static_cast<ssize_t>(size);
  25570. }
  25571. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  25572. ip = "127.0.0.1";
  25573. port = 0;
  25574. }
  25575. void get_local_ip_and_port(std::string &ip, int &port) const override {
  25576. ip = "127.0.0.1";
  25577. port = 0;
  25578. }
  25579. socket_t socket() const override { return INVALID_SOCKET; }
  25580. time_t duration() const override { return 0; }
  25581. private:
  25582. std::vector<std::string> pieces_;
  25583. size_t i_ = 0;
  25584. size_t at_ = 0;
  25585. bool time_out_ = false;
  25586. };
  25587. TEST(WebSocketFrameTest, ATimeoutInsideAFrameKeepsWhatWasRead) {
  25588. // FIN + Text, masked with an all-zero key: "Hello" goes out verbatim
  25589. std::string frame = "\x81\x85";
  25590. frame.append(4, '\0');
  25591. frame += "Hello";
  25592. // The header's first byte, then its second with half the mask key, then
  25593. // the rest
  25594. std::vector<std::string> pieces = {frame.substr(0, 1), frame.substr(1, 3),
  25595. frame.substr(4)};
  25596. WsTimeoutBetweenPiecesStream strm(pieces);
  25597. ws::impl::FrameReader reader;
  25598. ws::Opcode opcode;
  25599. std::string payload;
  25600. bool fin = false;
  25601. for (int i = 0; i < 2; i++) {
  25602. EXPECT_EQ(ws::impl::FrameRead::Timeout,
  25603. reader.read(strm, opcode, payload, fin, true, 0));
  25604. EXPECT_TRUE(reader.begun());
  25605. }
  25606. ASSERT_EQ(ws::impl::FrameRead::Ok,
  25607. reader.read(strm, opcode, payload, fin, true, 0));
  25608. EXPECT_FALSE(reader.begun());
  25609. EXPECT_TRUE(fin);
  25610. EXPECT_EQ(ws::Opcode::Text, opcode);
  25611. EXPECT_EQ("Hello", payload);
  25612. // Read in one go, the frame cannot be gone on with after a timeout
  25613. WsTimeoutBetweenPiecesStream again(pieces);
  25614. EXPECT_EQ(
  25615. ws::impl::FrameRead::Fail,
  25616. ws::impl::read_websocket_frame(again, opcode, payload, fin, true, 0));
  25617. }
  25618. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  25619. std::string body(2000, 'x');
  25620. std::string frame;
  25621. frame += static_cast<char>(0x82); // FIN + Binary
  25622. frame += static_cast<char>(126); // 16-bit length follows
  25623. frame += static_cast<char>(body.size() >> 8);
  25624. frame += static_cast<char>(body.size() & 0xff);
  25625. frame += body;
  25626. detail::BufferStream strm;
  25627. strm.write(frame.data(), frame.size());
  25628. ws::Opcode opcode;
  25629. std::string payload;
  25630. bool fin;
  25631. EXPECT_EQ(
  25632. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  25633. ws::impl::FrameRead::Ok);
  25634. EXPECT_EQ(body, payload);
  25635. }
  25636. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  25637. // The header announces the largest payload allowed, and only 3 bytes of it
  25638. // ever arrive.
  25639. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  25640. std::string frame;
  25641. frame += static_cast<char>(0x82); // FIN + Binary
  25642. frame += static_cast<char>(127); // 64-bit length follows
  25643. for (int shift = 56; shift >= 0; shift -= 8) {
  25644. frame += static_cast<char>((len >> shift) & 0xff);
  25645. }
  25646. frame += "abc";
  25647. detail::BufferStream strm;
  25648. strm.write(frame.data(), frame.size());
  25649. ws::Opcode opcode;
  25650. std::string payload;
  25651. bool fin;
  25652. EXPECT_EQ(
  25653. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  25654. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  25655. ws::impl::FrameRead::Fail);
  25656. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  25657. }
  25658. TEST(WebSocketTest, QueryStringInHandshake) {
  25659. Server svr;
  25660. std::mutex mtx;
  25661. std::string received_target;
  25662. std::string received_token;
  25663. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25664. {
  25665. std::lock_guard<std::mutex> lock(mtx);
  25666. received_target = req.target;
  25667. if (req.has_param("token")) {
  25668. received_token = req.get_param_value("token");
  25669. }
  25670. }
  25671. std::string msg;
  25672. while (ws.read(msg)) {
  25673. ws.send(msg);
  25674. }
  25675. });
  25676. auto port = svr.bind_to_any_port("localhost");
  25677. std::thread t([&]() { svr.listen_after_bind(); });
  25678. svr.wait_until_ready();
  25679. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  25680. "/ws?token=ABC&session=123");
  25681. ASSERT_TRUE(client.connect());
  25682. // Round-trip ensures the handler has run and captured the request.
  25683. ASSERT_TRUE(client.send("hello"));
  25684. std::string msg;
  25685. ASSERT_TRUE(client.read(msg));
  25686. EXPECT_EQ("hello", msg);
  25687. client.close();
  25688. {
  25689. std::lock_guard<std::mutex> lock(mtx);
  25690. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  25691. EXPECT_EQ("ABC", received_token);
  25692. }
  25693. svr.stop();
  25694. t.join();
  25695. }
  25696. // Run a handshake against a throwaway server and hand the request the server
  25697. // received back to the caller, so tests can assert on the headers the client
  25698. // actually put on the wire.
  25699. static void capture_websocket_handshake_request(
  25700. const Headers &client_headers,
  25701. std::function<void(const Request &, int port)> verify) {
  25702. Server svr;
  25703. std::mutex mtx;
  25704. Request received;
  25705. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25706. {
  25707. std::lock_guard<std::mutex> lock(mtx);
  25708. received = req;
  25709. }
  25710. std::string msg;
  25711. while (ws.read(msg)) {
  25712. ws.send(msg);
  25713. }
  25714. });
  25715. auto port = svr.bind_to_any_port("localhost");
  25716. std::thread t([&]() { svr.listen_after_bind(); });
  25717. auto se = detail::scope_exit([&] {
  25718. svr.stop();
  25719. t.join();
  25720. });
  25721. svr.wait_until_ready();
  25722. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  25723. client_headers);
  25724. ASSERT_TRUE(client.connect());
  25725. ASSERT_TRUE(client.send("hello"));
  25726. std::string msg;
  25727. ASSERT_TRUE(client.read(msg));
  25728. client.close();
  25729. {
  25730. std::lock_guard<std::mutex> lock(mtx);
  25731. verify(received, port);
  25732. }
  25733. }
  25734. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  25735. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  25736. // Non-default port must be present in the Host header. Default ports
  25737. // (80/443) are omitted; that logic is covered by
  25738. // MakeHostAndPortStringTest.
  25739. EXPECT_EQ("localhost:" + std::to_string(port),
  25740. req.get_header_value("Host"));
  25741. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  25742. req.get_header_value("User-Agent"));
  25743. EXPECT_FALSE(req.has_header("Accept"));
  25744. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  25745. EXPECT_FALSE(req.has_header("Content-Length"));
  25746. });
  25747. }
  25748. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  25749. capture_websocket_handshake_request(
  25750. {{"Host", "example.com"},
  25751. {"User-Agent", "custom-agent"},
  25752. {"X-Custom", "value"}},
  25753. [](const Request &req, int) {
  25754. EXPECT_EQ("example.com", req.get_header_value("Host"));
  25755. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  25756. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  25757. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  25758. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  25759. });
  25760. }
  25761. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  25762. capture_websocket_handshake_request(
  25763. {{"Upgrade", "bogus"},
  25764. {"Connection", "close"},
  25765. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  25766. {"Sec-WebSocket-Version", "8"}},
  25767. [](const Request &req, int) {
  25768. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  25769. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  25770. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  25771. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  25772. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  25773. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  25774. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  25775. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  25776. req.get_header_value("Sec-WebSocket-Key"));
  25777. });
  25778. }
  25779. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  25780. // A header the client refuses to send must abort the handshake before any
  25781. // part of it reaches the wire; a lone request line would otherwise sit in
  25782. // the peer's buffer as a truncated request.
  25783. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  25784. ASSERT_NE(INVALID_SOCKET, srv);
  25785. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  25786. sockaddr_in addr{};
  25787. addr.sin_family = AF_INET;
  25788. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  25789. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  25790. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  25791. ASSERT_EQ(0, ::listen(srv, 1));
  25792. sockaddr_in bound{};
  25793. socklen_t bound_len = sizeof(bound);
  25794. ASSERT_EQ(
  25795. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  25796. auto port = ntohs(bound.sin_port);
  25797. ssize_t received = -1;
  25798. std::thread t([&] {
  25799. // Bound every blocking call so a regression fails the test with a bad
  25800. // value instead of hanging the suite.
  25801. fd_set rfds;
  25802. FD_ZERO(&rfds);
  25803. FD_SET(srv, &rfds);
  25804. timeval tv{5, 0};
  25805. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  25806. 0) {
  25807. return;
  25808. }
  25809. sockaddr_in cli_addr{};
  25810. socklen_t cli_len = sizeof(cli_addr);
  25811. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  25812. if (cli == INVALID_SOCKET) { return; }
  25813. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  25814. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  25815. char buf[4096];
  25816. received = ::recv(cli, buf, sizeof(buf), 0);
  25817. });
  25818. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  25819. // connect() has already shut the socket down by the time it returns false,
  25820. // so the peer sees EOF without waiting for the client to be destroyed.
  25821. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  25822. {{"X-Bad", "a\r\nInjected: 1"}});
  25823. EXPECT_FALSE(client.connect());
  25824. t.join();
  25825. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  25826. EXPECT_EQ(0, received);
  25827. }
  25828. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  25829. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  25830. // contains "upgrade" as a substring is a different token and must not
  25831. // start a WebSocket handshake.
  25832. auto make_request = [](const std::vector<std::string> &connection_values) {
  25833. Request req;
  25834. req.method = "GET";
  25835. req.headers.emplace("Upgrade", "websocket");
  25836. for (const auto &value : connection_values) {
  25837. req.headers.emplace("Connection", value);
  25838. }
  25839. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25840. req.headers.emplace("Sec-WebSocket-Version", "13");
  25841. return req;
  25842. };
  25843. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  25844. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  25845. EXPECT_TRUE(
  25846. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  25847. EXPECT_TRUE(
  25848. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  25849. EXPECT_TRUE(
  25850. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  25851. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  25852. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  25853. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  25854. EXPECT_FALSE(
  25855. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  25856. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  25857. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25858. }
  25859. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  25860. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  25861. // asks recipients to match each protocol-name case-insensitively, and RFC
  25862. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  25863. // client naming websocket alongside another protocol, or on a second field
  25864. // line, is offering websocket; a value that merely contains "websocket" as a
  25865. // substring is a different protocol name and is not.
  25866. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  25867. Request req;
  25868. req.method = "GET";
  25869. for (const auto &value : upgrade_values) {
  25870. req.headers.emplace("Upgrade", value);
  25871. }
  25872. req.headers.emplace("Connection", "Upgrade");
  25873. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  25874. req.headers.emplace("Sec-WebSocket-Version", "13");
  25875. return req;
  25876. };
  25877. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  25878. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  25879. EXPECT_TRUE(
  25880. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  25881. EXPECT_TRUE(
  25882. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  25883. EXPECT_TRUE(
  25884. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  25885. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  25886. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  25887. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  25888. EXPECT_FALSE(
  25889. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  25890. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  25891. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  25892. }
  25893. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  25894. Server svr;
  25895. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  25896. auto port = svr.bind_to_any_port("localhost");
  25897. std::thread t([&]() { svr.listen_after_bind(); });
  25898. auto se = detail::scope_exit([&] {
  25899. svr.stop();
  25900. t.join();
  25901. });
  25902. svr.wait_until_ready();
  25903. Headers headers = {{"Upgrade", "websocket"},
  25904. {"Connection", "notupgrade"},
  25905. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  25906. {"Sec-WebSocket-Version", "13"}};
  25907. Client cli("localhost", port);
  25908. auto res = cli.Get("/ws", headers);
  25909. // The route exists only as a WebSocket route, so a request that fails the
  25910. // handshake check falls through to ordinary routing.
  25911. ASSERT_TRUE(res);
  25912. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  25913. }
  25914. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  25915. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  25916. // Connection value is the only thing left for the client to reject.
  25917. Server svr;
  25918. svr.Get("/ws", [](const Request &req, Response &res) {
  25919. res.status = StatusCode::SwitchingProtocol_101;
  25920. res.set_header("Upgrade", "websocket");
  25921. res.set_header("Connection", "notupgrade");
  25922. res.set_header("Sec-WebSocket-Accept",
  25923. detail::websocket_accept_key(
  25924. req.get_header_value("Sec-WebSocket-Key")));
  25925. });
  25926. auto port = svr.bind_to_any_port("localhost");
  25927. std::thread t([&]() { svr.listen_after_bind(); });
  25928. auto se = detail::scope_exit([&] {
  25929. svr.stop();
  25930. t.join();
  25931. });
  25932. svr.wait_until_ready();
  25933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  25934. auto res = client.connect();
  25935. EXPECT_FALSE(res);
  25936. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25937. EXPECT_FALSE(client.is_open());
  25938. }
  25939. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  25940. Server svr;
  25941. svr.Get("/ws", [](const Request &req, Response &res) {
  25942. res.status = StatusCode::SwitchingProtocol_101;
  25943. res.set_header("Upgrade", "websocket");
  25944. res.set_header("Connection", "Upgrade");
  25945. res.set_header("Sec-WebSocket-Accept",
  25946. detail::websocket_accept_key(
  25947. req.get_header_value("Sec-WebSocket-Key")));
  25948. res.set_header("Sec-WebSocket-Protocol", "admin");
  25949. });
  25950. auto port = svr.bind_to_any_port("localhost");
  25951. std::thread t([&]() { svr.listen_after_bind(); });
  25952. auto se = detail::scope_exit([&] {
  25953. svr.stop();
  25954. t.join();
  25955. });
  25956. svr.wait_until_ready();
  25957. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  25958. // Server selects a subprotocol the client never offered
  25959. {
  25960. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  25961. ws::WebSocketClient client(url, headers);
  25962. auto res = client.connect();
  25963. EXPECT_FALSE(res);
  25964. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25965. EXPECT_FALSE(client.is_open());
  25966. EXPECT_TRUE(client.subprotocol().empty());
  25967. }
  25968. // Client offered none but the server named one anyway
  25969. {
  25970. ws::WebSocketClient client(url);
  25971. auto res = client.connect();
  25972. EXPECT_FALSE(res);
  25973. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  25974. EXPECT_FALSE(client.is_open());
  25975. EXPECT_TRUE(client.subprotocol().empty());
  25976. }
  25977. }
  25978. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  25979. // The socket path doubles as the URL host, so it must not contain '/'.
  25980. const char *shard = getenv("GTEST_SHARD_INDEX");
  25981. const std::string sock_path =
  25982. shard ? std::string("httplib-ws-") + shard + ".sock"
  25983. : std::string("httplib-ws.sock");
  25984. std::remove(sock_path.c_str());
  25985. Server svr;
  25986. std::mutex mtx;
  25987. std::string received_host;
  25988. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  25989. {
  25990. std::lock_guard<std::mutex> lock(mtx);
  25991. received_host = req.get_header_value("Host");
  25992. }
  25993. std::string msg;
  25994. while (ws.read(msg)) {
  25995. ws.send(msg);
  25996. }
  25997. });
  25998. svr.set_address_family(AF_UNIX);
  25999. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  26000. auto se = detail::scope_exit([&] {
  26001. svr.stop();
  26002. t.join();
  26003. std::remove(sock_path.c_str());
  26004. });
  26005. svr.wait_until_ready();
  26006. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  26007. client.set_address_family(AF_UNIX);
  26008. ASSERT_TRUE(client.connect());
  26009. ASSERT_TRUE(client.send("hello"));
  26010. std::string msg;
  26011. ASSERT_TRUE(client.read(msg));
  26012. client.close();
  26013. {
  26014. std::lock_guard<std::mutex> lock(mtx);
  26015. // There is no host:port for a Unix socket, so the same "localhost"
  26016. // placeholder the HTTP client uses is expected.
  26017. EXPECT_EQ("localhost", received_host);
  26018. }
  26019. }
  26020. // Two threads must never parse WebSocket frames from the same stream.
  26021. // close() used to read the peer's Close reply with its own frame read, so it
  26022. // raced a reader thread that was in the middle of a payload: the payload loop
  26023. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  26024. // so bytes taken by close() were replaced with bytes from further along the
  26025. // stream. The message kept its length and silently changed content.
  26026. //
  26027. // The raw peer below sends a frame header plus part of the payload, waits for
  26028. // the handler to call close(), and only then sends the rest. Whichever thread
  26029. // would win the race for those bytes, the message must arrive intact, because
  26030. // close() must not touch the stream while read() owns it.
  26031. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  26032. #ifndef _WIN32
  26033. signal(SIGPIPE, SIG_IGN);
  26034. #endif
  26035. const size_t payload_len = 120; // fits the 7-bit length field
  26036. const size_t prefix_len = 8;
  26037. const int attempts = 8;
  26038. std::string expected(payload_len, '\0');
  26039. for (size_t i = 0; i < payload_len; i++) {
  26040. expected[i] = static_cast<char>('a' + i % 26);
  26041. }
  26042. std::atomic<bool> peer_stalled{false};
  26043. std::atomic<bool> handler_done{false};
  26044. std::mutex received_mutex;
  26045. std::vector<std::string> received;
  26046. // Bound every wait, so a regression fails the test instead of hanging the
  26047. // suite.
  26048. auto wait_for = [](const std::atomic<bool> &flag) {
  26049. for (int i = 0; i < 500 && !flag; i++) {
  26050. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26051. }
  26052. };
  26053. Server svr;
  26054. svr.set_websocket_ping_interval(0);
  26055. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26056. std::thread reader([&]() {
  26057. std::string msg;
  26058. while (ws.read(msg)) {
  26059. std::lock_guard<std::mutex> guard(received_mutex);
  26060. received.push_back(msg);
  26061. }
  26062. });
  26063. // Wait until the peer stalls mid-payload, so the reader thread is parked
  26064. // inside a frame when close() runs.
  26065. wait_for(peer_stalled);
  26066. ws.close();
  26067. reader.join();
  26068. handler_done = true;
  26069. });
  26070. auto port = svr.bind_to_any_port("127.0.0.1");
  26071. std::thread t([&]() { svr.listen_after_bind(); });
  26072. auto se = detail::scope_exit([&] {
  26073. svr.stop();
  26074. t.join();
  26075. });
  26076. svr.wait_until_ready();
  26077. auto send_bytes = [](socket_t s, const std::string &data) {
  26078. #ifdef _WIN32
  26079. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  26080. #else
  26081. auto n = ::send(s, data.data(), data.size(), 0);
  26082. #endif
  26083. return n == static_cast<decltype(n)>(data.size());
  26084. };
  26085. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  26086. // Every length used here fits the 7-bit length field.
  26087. auto masked_header = [](uint8_t first_byte, size_t len) {
  26088. std::string h;
  26089. h += static_cast<char>(first_byte);
  26090. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  26091. h.append(4, '\0'); // mask key
  26092. return h;
  26093. };
  26094. for (int attempt = 0; attempt < attempts; attempt++) {
  26095. peer_stalled = false;
  26096. handler_done = false;
  26097. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26098. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  26099. auto se_sock = detail::scope_exit([&] {
  26100. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  26101. });
  26102. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26103. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  26104. sockaddr_in addr{};
  26105. addr.sin_family = AF_INET;
  26106. addr.sin_port = htons(static_cast<uint16_t>(port));
  26107. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26108. ASSERT_EQ(
  26109. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  26110. << "attempt " << attempt;
  26111. ASSERT_TRUE(send_bytes(sock,
  26112. "GET /ws HTTP/1.1\r\n"
  26113. "Host: 127.0.0.1\r\n"
  26114. "Upgrade: websocket\r\n"
  26115. "Connection: Upgrade\r\n"
  26116. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26117. "Sec-WebSocket-Version: 13\r\n"
  26118. "\r\n"))
  26119. << "attempt " << attempt;
  26120. std::string response;
  26121. while (response.find("\r\n\r\n") == std::string::npos) {
  26122. char buf[512];
  26123. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  26124. if (n <= 0) { break; }
  26125. response.append(buf, static_cast<size_t>(n));
  26126. }
  26127. ASSERT_NE(std::string::npos, response.find(" 101 "))
  26128. << "attempt " << attempt;
  26129. // Send the header of a Binary message but only the first prefix_len bytes
  26130. // of its payload, leaving the reader thread stalled inside the payload.
  26131. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  26132. expected.substr(0, prefix_len)))
  26133. << "attempt " << attempt;
  26134. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26135. peer_stalled = true;
  26136. // Let close() send its Close frame and park in its own read before the
  26137. // rest of the payload arrives, so both threads are waiting for it.
  26138. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26139. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  26140. close_frame += static_cast<char>(0x03); // status 1000
  26141. close_frame += static_cast<char>(0xE8);
  26142. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  26143. << "attempt " << attempt;
  26144. // Closing the peer releases the reader thread even on the buggy path,
  26145. // where it waits for bytes another thread already consumed.
  26146. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  26147. detail::close_socket(sock);
  26148. sock = INVALID_SOCKET;
  26149. wait_for(handler_done);
  26150. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  26151. }
  26152. std::lock_guard<std::mutex> guard(received_mutex);
  26153. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  26154. << "a message in flight when close() ran was dropped";
  26155. for (size_t i = 0; i < received.size(); i++) {
  26156. EXPECT_EQ(expected, received[i]) << "message " << i;
  26157. }
  26158. }
  26159. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  26160. // returning the socket, or INVALID_SOCKET.
  26161. static socket_t connect_raw_websocket(int port, const std::string &path) {
  26162. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26163. if (sock == INVALID_SOCKET) { return sock; }
  26164. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  26165. sockaddr_in addr{};
  26166. addr.sin_family = AF_INET;
  26167. addr.sin_port = htons(static_cast<uint16_t>(port));
  26168. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  26169. std::string req = "GET " + path +
  26170. " HTTP/1.1\r\n"
  26171. "Host: 127.0.0.1\r\n"
  26172. "Upgrade: websocket\r\n"
  26173. "Connection: Upgrade\r\n"
  26174. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  26175. "Sec-WebSocket-Version: 13\r\n"
  26176. "\r\n";
  26177. std::string res;
  26178. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  26179. detail::send_socket(sock, req.data(), req.size(), 0) ==
  26180. static_cast<ssize_t>(req.size())) {
  26181. char c;
  26182. while (res.find("\r\n\r\n") == std::string::npos &&
  26183. ::recv(sock, &c, 1, 0) == 1) {
  26184. res += c;
  26185. }
  26186. }
  26187. if (res.find(" 101 ") == std::string::npos) {
  26188. detail::close_socket(sock);
  26189. return INVALID_SOCKET;
  26190. }
  26191. return sock;
  26192. }
  26193. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  26194. // The payload must fit the 7-bit length field.
  26195. static std::string masked_frame(uint8_t first_byte,
  26196. const std::string &payload) {
  26197. std::string f;
  26198. f += static_cast<char>(first_byte);
  26199. f += static_cast<char>(0x80 | payload.size());
  26200. f.append(4, '\0');
  26201. return f + payload;
  26202. }
  26203. // Sends frames on a new raw connection to /ws and returns the first n bytes the
  26204. // server sends back, or what came before it closed.
  26205. static std::string raw_websocket_reply(int port, const std::string &frames,
  26206. size_t n) {
  26207. auto sock = connect_raw_websocket(port, "/ws");
  26208. if (sock == INVALID_SOCKET) { return std::string(); }
  26209. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26210. std::string reply;
  26211. char buf[256];
  26212. while (reply.size() < n) {
  26213. auto got = ::recv(sock, buf, sizeof(buf), 0);
  26214. if (got <= 0) { break; }
  26215. reply.append(buf, static_cast<size_t>(got));
  26216. }
  26217. detail::close_socket(sock);
  26218. return reply;
  26219. }
  26220. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  26221. std::atomic<bool> done{false};
  26222. std::string received;
  26223. Server svr;
  26224. svr.set_websocket_ping_interval(0);
  26225. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26226. std::string msg;
  26227. if (ws.read(msg) == ws::Binary) { received = msg; }
  26228. done = true;
  26229. });
  26230. auto port = svr.bind_to_any_port("127.0.0.1");
  26231. std::thread t([&]() { svr.listen_after_bind(); });
  26232. auto se = detail::scope_exit([&] {
  26233. svr.stop();
  26234. t.join();
  26235. });
  26236. svr.wait_until_ready();
  26237. auto sock = connect_raw_websocket(port, "/ws");
  26238. ASSERT_NE(INVALID_SOCKET, sock);
  26239. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26240. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  26241. masked_frame(0x89, "p") + // FIN + Ping
  26242. masked_frame(0x80, "lo"); // FIN + Continuation
  26243. detail::send_socket(sock, frames.data(), frames.size(), 0);
  26244. for (int i = 0; i < 500 && !done; i++) {
  26245. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26246. }
  26247. ASSERT_TRUE(done);
  26248. EXPECT_EQ("Hello", received);
  26249. // The Ping between the fragments is answered with a Pong.
  26250. char pong[3];
  26251. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  26252. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  26253. }
  26254. TEST(WebSocketTest, CloseEndsAReadOfEndlessFragments) {
  26255. #ifndef _WIN32
  26256. signal(SIGPIPE, SIG_IGN);
  26257. #endif
  26258. std::atomic<bool> read_ended{false};
  26259. std::atomic<bool> sending{true};
  26260. Server svr;
  26261. svr.set_websocket_ping_interval(0);
  26262. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26263. std::thread reader([&]() {
  26264. std::string msg;
  26265. while (ws.read(msg)) {}
  26266. read_ended = true;
  26267. });
  26268. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  26269. ws.close();
  26270. reader.join();
  26271. });
  26272. auto port = svr.bind_to_any_port("127.0.0.1");
  26273. std::thread t([&]() { svr.listen_after_bind(); });
  26274. auto se = detail::scope_exit([&] {
  26275. svr.stop();
  26276. t.join();
  26277. });
  26278. svr.wait_until_ready();
  26279. auto sock = connect_raw_websocket(port, "/ws");
  26280. ASSERT_NE(INVALID_SOCKET, sock);
  26281. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26282. // A Text message whose empty continuation frames never end
  26283. std::thread sender([&]() {
  26284. auto data = masked_frame(0x01, "");
  26285. while (sending) {
  26286. data += masked_frame(0x00, "");
  26287. if (detail::send_socket(sock, data.data(), data.size(), 0) <= 0) {
  26288. return;
  26289. }
  26290. data.clear();
  26291. }
  26292. });
  26293. for (int i = 0; i < 300 && !read_ended; i++) {
  26294. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  26295. }
  26296. sending = false;
  26297. sender.join();
  26298. EXPECT_TRUE(read_ended);
  26299. }
  26300. TEST(WebSocketTest, ServerMaxMessageLength) {
  26301. Server svr;
  26302. svr.set_websocket_ping_interval(0);
  26303. svr.set_websocket_max_message_length(100);
  26304. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26305. std::string msg;
  26306. while (ws.read(msg)) {
  26307. ws.send(msg);
  26308. }
  26309. });
  26310. auto port = svr.bind_to_any_port("127.0.0.1");
  26311. std::thread t([&]() { svr.listen_after_bind(); });
  26312. auto se = detail::scope_exit([&] {
  26313. svr.stop();
  26314. t.join();
  26315. });
  26316. svr.wait_until_ready();
  26317. const std::string ping(110, 'p');
  26318. const std::string half(50, 'a');
  26319. const std::string over(60, 'b');
  26320. const std::string too_big("\x88\x02\x03\xf1"); // Close 1009
  26321. // A Ping longer than the limit is answered, since the limit is for
  26322. // messages. A message at the limit is echoed, and one over it is refused
  26323. // although each of its frames is within it.
  26324. EXPECT_EQ(std::string("\x8a\x6e") + ping + "\x81\x64" + half + half + too_big,
  26325. raw_websocket_reply(
  26326. port,
  26327. masked_frame(0x89, ping) + masked_frame(0x01, half) +
  26328. masked_frame(0x80, half) + masked_frame(0x01, over) +
  26329. masked_frame(0x80, over),
  26330. 2 + ping.size() + 2 + 2 * half.size() + too_big.size()));
  26331. // A header that announces more than the limit is refused before its payload
  26332. EXPECT_EQ(too_big, raw_websocket_reply(port,
  26333. std::string("\x82\xfe\x03\xe8", 4) +
  26334. std::string(4, '\0'),
  26335. too_big.size()));
  26336. }
  26337. TEST(WebSocketTest, ClientMaxMessageLength) {
  26338. Server svr;
  26339. svr.set_websocket_ping_interval(0);
  26340. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26341. ws.send(std::string(1024, 'a'));
  26342. ws.send(std::string(2048, 'b'));
  26343. std::string msg;
  26344. while (ws.read(msg)) {}
  26345. });
  26346. auto port = svr.bind_to_any_port(HOST);
  26347. std::thread t([&]() { svr.listen_after_bind(); });
  26348. auto se = detail::scope_exit([&] {
  26349. svr.stop();
  26350. t.join();
  26351. });
  26352. svr.wait_until_ready();
  26353. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  26354. client.set_read_timeout(5, 0);
  26355. client.set_websocket_max_message_length(1024);
  26356. ASSERT_TRUE(client.connect());
  26357. std::string msg;
  26358. ASSERT_EQ(ws::Text, client.read(msg));
  26359. EXPECT_EQ(1024u, msg.size());
  26360. EXPECT_EQ(ws::Fail, client.read(msg));
  26361. EXPECT_FALSE(client.is_open());
  26362. // 0 lifts the limit
  26363. client.set_websocket_max_message_length(0);
  26364. ASSERT_TRUE(client.connect());
  26365. EXPECT_EQ(ws::Text, client.read(msg));
  26366. EXPECT_EQ(ws::Text, client.read(msg));
  26367. EXPECT_EQ(2048u, msg.size());
  26368. }
  26369. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  26370. Server svr;
  26371. svr.set_websocket_ping_interval(-1);
  26372. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26373. std::string msg;
  26374. while (ws.read(msg)) {}
  26375. });
  26376. auto port = svr.bind_to_any_port("127.0.0.1");
  26377. std::thread t([&]() { svr.listen_after_bind(); });
  26378. auto se = detail::scope_exit([&] {
  26379. svr.stop();
  26380. t.join();
  26381. });
  26382. svr.wait_until_ready();
  26383. auto sock = connect_raw_websocket(port, "/ws");
  26384. ASSERT_NE(INVALID_SOCKET, sock);
  26385. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26386. // Nothing comes while the client stays quiet.
  26387. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  26388. char c;
  26389. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  26390. }
  26391. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  26392. // and that has to end a read() already waiting on the peer, on every platform.
  26393. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  26394. // The peer sends no pings, and its handler never calls read(), which is
  26395. // where pongs are written.
  26396. std::mutex mutex;
  26397. std::condition_variable cv;
  26398. auto release = false;
  26399. svr.set_websocket_ping_interval(0);
  26400. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  26401. std::unique_lock<std::mutex> lock(mutex);
  26402. cv.wait(lock, [&] { return release; });
  26403. });
  26404. auto port = svr.bind_to_any_port(HOST);
  26405. std::thread t([&]() { svr.listen_after_bind(); });
  26406. auto se = detail::scope_exit([&] {
  26407. {
  26408. std::lock_guard<std::mutex> lock(mutex);
  26409. release = true;
  26410. }
  26411. cv.notify_all();
  26412. svr.stop();
  26413. t.join();
  26414. });
  26415. svr.wait_until_ready();
  26416. ws::WebSocketClient client(std::string(scheme) +
  26417. "://localhost:" + std::to_string(port) + "/ws");
  26418. #ifdef CPPHTTPLIB_SSL_ENABLED
  26419. client.enable_server_certificate_verification(false);
  26420. #endif
  26421. // A ping a second, given up on after two go unanswered: about 3s
  26422. client.set_websocket_ping_interval(1);
  26423. client.set_websocket_max_missed_pongs(2);
  26424. // Well past that, so that a read the timeout ends instead stands out
  26425. client.set_read_timeout(10);
  26426. ASSERT_TRUE(client.connect());
  26427. auto start = std::chrono::steady_clock::now();
  26428. std::string msg;
  26429. EXPECT_EQ(ws::Fail, client.read(msg));
  26430. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  26431. std::chrono::steady_clock::now() - start)
  26432. .count(),
  26433. 6000);
  26434. EXPECT_FALSE(client.is_open());
  26435. }
  26436. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  26437. Server svr;
  26438. check_pong_timeout_ends_read(svr, "ws");
  26439. }
  26440. #ifdef CPPHTTPLIB_SSL_ENABLED
  26441. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  26442. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26443. ASSERT_TRUE(svr.is_valid());
  26444. check_pong_timeout_ends_read(svr, "wss");
  26445. }
  26446. #endif
  26447. // listen() returns only after every handler has, so Server::stop() has to end
  26448. // a WebSocket handler's read() waiting on a client that stays connected and
  26449. // quiet, whether or not the handler bounded its reads, and the client's
  26450. // connection ends with it.
  26451. static void check_stop_ends_websocket_read(Server &svr, const char *scheme,
  26452. bool bounded) {
  26453. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26454. if (bounded) { ws.set_read_timeout(0, 50000); }
  26455. std::string msg;
  26456. while (ws.read(msg) != ws::Fail) {}
  26457. });
  26458. auto port = svr.bind_to_any_port(HOST);
  26459. std::thread t([&]() { svr.listen_after_bind(); });
  26460. auto se = detail::scope_exit([&] {
  26461. if (t.joinable()) {
  26462. svr.stop();
  26463. t.join();
  26464. }
  26465. });
  26466. svr.wait_until_ready();
  26467. ws::WebSocketClient client(std::string(scheme) +
  26468. "://localhost:" + std::to_string(port) + "/ws");
  26469. #ifdef CPPHTTPLIB_SSL_ENABLED
  26470. client.enable_server_certificate_verification(false);
  26471. #endif
  26472. client.set_read_timeout(2);
  26473. ASSERT_TRUE(client.connect());
  26474. auto stopped = std::async(std::launch::async, [&] {
  26475. svr.stop();
  26476. t.join();
  26477. });
  26478. std::string msg;
  26479. EXPECT_EQ(ws::Fail, client.read(msg));
  26480. EXPECT_FALSE(client.is_open());
  26481. auto in_time =
  26482. stopped.wait_for(std::chrono::seconds(5)) == std::future_status::ready;
  26483. // A handler the stop did not reach ends when the client leaves
  26484. if (!in_time) { client.close(); }
  26485. stopped.wait();
  26486. EXPECT_TRUE(in_time);
  26487. }
  26488. TEST(WebSocketTest, StopEndsAWaitingRead) {
  26489. Server svr;
  26490. check_stop_ends_websocket_read(svr, "ws", false);
  26491. }
  26492. TEST(WebSocketTest, StopEndsAWaitingBoundedRead) {
  26493. Server svr;
  26494. check_stop_ends_websocket_read(svr, "ws", true);
  26495. }
  26496. #ifdef CPPHTTPLIB_SSL_ENABLED
  26497. TEST(WebSocketTest, StopEndsAWaitingReadOverTLS) {
  26498. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  26499. ASSERT_TRUE(svr.is_valid());
  26500. check_stop_ends_websocket_read(svr, "wss", false);
  26501. }
  26502. #endif
  26503. // The stop reaches the client as a Close with 1001 Going Away, not as a
  26504. // dropped connection, whether the handler waits for a message or for the rest
  26505. // of one: `sent` is what the client sends first. A `bounded` handler's reads
  26506. // time out inside the message as well, and the stop ends them too.
  26507. static void check_stop_closes_with_going_away(const std::string &sent,
  26508. bool bounded = false) {
  26509. Server svr;
  26510. svr.set_websocket_ping_interval(0);
  26511. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26512. if (bounded) { ws.set_read_timeout(0, 10000); }
  26513. std::string msg;
  26514. while (ws.read(msg) != ws::Fail) {}
  26515. });
  26516. auto port = svr.bind_to_any_port("127.0.0.1");
  26517. std::thread t([&]() { svr.listen_after_bind(); });
  26518. auto se = detail::scope_exit([&] {
  26519. svr.stop();
  26520. t.join();
  26521. });
  26522. svr.wait_until_ready();
  26523. // Closed before the join above, which a handler the stop did not reach
  26524. // would otherwise hold up.
  26525. auto sock = connect_raw_websocket(port, "/ws");
  26526. ASSERT_NE(INVALID_SOCKET, sock);
  26527. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26528. ASSERT_EQ(static_cast<ssize_t>(sent.size()),
  26529. detail::send_socket(sock, sent.data(), sent.size(), 0));
  26530. // Let the handler take what was sent and wait for more
  26531. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  26532. svr.stop();
  26533. // FIN + Close, its length, then the code: unmasked, from a server
  26534. std::string head;
  26535. char c;
  26536. while (head.size() < 4 && ::recv(sock, &c, 1, 0) == 1) {
  26537. head += c;
  26538. }
  26539. const std::string reason = "server stopping";
  26540. EXPECT_EQ(std::string("\x88") + static_cast<char>(2 + reason.size()) +
  26541. "\x03\xe9",
  26542. head);
  26543. }
  26544. TEST(WebSocketTest, StopClosesWithGoingAway) {
  26545. check_stop_closes_with_going_away("");
  26546. }
  26547. TEST(WebSocketTest, StopMidMessageClosesWithGoingAway) {
  26548. // A Text frame without FIN: the first fragment of a message
  26549. check_stop_closes_with_going_away(masked_frame(0x01, "half"));
  26550. }
  26551. TEST(WebSocketTest, StopMidBoundedMessageClosesWithGoingAway) {
  26552. check_stop_closes_with_going_away(masked_frame(0x01, "half"),
  26553. /*bounded=*/true);
  26554. }
  26555. // A handler that bounds its reads gets control back within its timeout even
  26556. // while a message arrives in pieces, and the message whole once the last has
  26557. // come: what was read of it is kept across the timeouts. Each of `pieces` is
  26558. // sent once read() has timed out twice since the one before was sent, so the
  26559. // second timeout came from a read() that had that piece to take.
  26560. static void check_bounded_read_resumes(const std::vector<std::string> &pieces,
  26561. const std::string &expected) {
  26562. std::atomic<bool> done{false};
  26563. std::atomic<int> timeouts{0};
  26564. std::string received;
  26565. Server svr;
  26566. svr.set_websocket_ping_interval(0);
  26567. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26568. ws.set_read_timeout(0, 10000);
  26569. std::string msg;
  26570. ws::ReadResult r;
  26571. while ((r = ws.read(msg)) == ws::Timeout) {
  26572. timeouts++;
  26573. }
  26574. if (r == ws::Text) { received = msg; }
  26575. done = true;
  26576. });
  26577. auto port = svr.bind_to_any_port("127.0.0.1");
  26578. std::thread t([&]() { svr.listen_after_bind(); });
  26579. auto se = detail::scope_exit([&] {
  26580. svr.stop();
  26581. t.join();
  26582. });
  26583. svr.wait_until_ready();
  26584. auto sock = connect_raw_websocket(port, "/ws");
  26585. ASSERT_NE(INVALID_SOCKET, sock);
  26586. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  26587. // Each piece goes out at once, not held back by Nagle's algorithm
  26588. ASSERT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  26589. for (size_t i = 0; i < pieces.size(); i++) {
  26590. ASSERT_EQ(static_cast<ssize_t>(pieces[i].size()),
  26591. detail::send_socket(sock, pieces[i].data(), pieces[i].size(), 0));
  26592. if (i + 1 == pieces.size()) { break; }
  26593. auto before = timeouts.load();
  26594. for (int j = 0; j < 5000 && timeouts < before + 2; j++) {
  26595. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26596. }
  26597. ASSERT_GE(timeouts.load(), before + 2) << "piece " << i;
  26598. }
  26599. for (int i = 0; i < 5000 && !done; i++) {
  26600. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  26601. }
  26602. ASSERT_TRUE(done);
  26603. EXPECT_EQ(expected, received);
  26604. }
  26605. TEST(WebSocketTest, BoundedReadResumesAFrameInPieces) {
  26606. // The header's first byte, then its second with half the mask key, then
  26607. // the rest: what a frame written in several writes may look like when
  26608. // Nagle's algorithm holds the later ones back for an ACK.
  26609. auto frame = masked_frame(0x81, "Hello"); // FIN + Text
  26610. check_bounded_read_resumes(
  26611. {frame.substr(0, 1), frame.substr(1, 3), frame.substr(4)}, "Hello");
  26612. }
  26613. TEST(WebSocketTest, BoundedReadResumesBetweenFragments) {
  26614. check_bounded_read_resumes(
  26615. {masked_frame(0x01, "Hel"), masked_frame(0x80, "lo")}, "Hello");
  26616. }
  26617. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  26618. Server svr;
  26619. svr.set_websocket_ping_interval(0);
  26620. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26621. std::string msg;
  26622. while (ws.read(msg)) {}
  26623. });
  26624. auto port = svr.bind_to_any_port("127.0.0.1");
  26625. std::thread t([&]() { svr.listen_after_bind(); });
  26626. auto se = detail::scope_exit([&] {
  26627. svr.stop();
  26628. t.join();
  26629. });
  26630. svr.wait_until_ready();
  26631. // Each Close payload and the reply it should get: an echo when valid, 1002
  26632. // otherwise.
  26633. std::vector<std::pair<std::string, std::string>> cases = {
  26634. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  26635. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  26636. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  26637. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  26638. };
  26639. // Also between the fragments of a message.
  26640. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  26641. for (const auto &c : cases) {
  26642. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  26643. c.second,
  26644. raw_websocket_reply(port, prefix + masked_frame(0x88, c.first),
  26645. 2 + c.second.size()));
  26646. }
  26647. }
  26648. }
  26649. TEST(WebSocketTest, FailsABadFrameWithACloseStatus) {
  26650. Server svr;
  26651. svr.set_websocket_ping_interval(0);
  26652. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26653. std::string msg;
  26654. while (ws.read(msg)) {}
  26655. });
  26656. auto port = svr.bind_to_any_port("127.0.0.1");
  26657. std::thread t([&]() { svr.listen_after_bind(); });
  26658. auto se = detail::scope_exit([&] {
  26659. svr.stop();
  26660. t.join();
  26661. });
  26662. svr.wait_until_ready();
  26663. // A header that announces one byte over the limit, and none of its payload
  26664. std::string too_big = "\x82\xff";
  26665. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1;
  26666. for (int shift = 56; shift >= 0; shift -= 8) {
  26667. too_big += static_cast<char>((len >> shift) & 0xff);
  26668. }
  26669. too_big.append(4, '\0');
  26670. const std::string protocol_error("\x03\xea"); // 1002
  26671. const std::string too_big_error("\x03\xf1"); // 1009
  26672. // What the client sends and the status the server closes with
  26673. std::vector<std::pair<std::string, std::string>> cases = {
  26674. {masked_frame(0xc1, "a"), protocol_error}, // RSV1
  26675. {std::string("\x81\x01") + "a", protocol_error}, // not masked
  26676. {masked_frame(0x09, ""), protocol_error}, // fragmented Ping
  26677. {masked_frame(0x83, ""), protocol_error}, // reserved opcode
  26678. {masked_frame(0x8b, ""), protocol_error}, // reserved control opcode
  26679. {masked_frame(0x80, "a"), protocol_error}, // continuation, no start
  26680. {masked_frame(0x01, "a") + masked_frame(0x81, "b"),
  26681. protocol_error}, // a new message inside a fragmented one
  26682. {std::string("\x81\xff\x80", 3) + std::string(11, '\0'),
  26683. protocol_error}, // 64-bit length with its top bit set
  26684. {too_big, too_big_error},
  26685. };
  26686. for (const auto &c : cases) {
  26687. EXPECT_EQ(std::string("\x88\x02") + c.second,
  26688. raw_websocket_reply(port, c.first, 4));
  26689. }
  26690. }
  26691. TEST(WebSocketTest, ClientFailsAMaskedFrameWithProtocolError) {
  26692. SilentListener listener;
  26693. ASSERT_NE(INVALID_SOCKET, listener.sock);
  26694. // A peer that completes the handshake, then sends a masked frame, which a
  26695. // server must never do, and keeps what the client sends back.
  26696. std::string reply;
  26697. std::thread peer([&]() {
  26698. auto sock = listener.accept();
  26699. if (sock == INVALID_SOCKET) { return; }
  26700. std::string req;
  26701. char c;
  26702. while (req.find("\r\n\r\n") == std::string::npos &&
  26703. ::recv(sock, &c, 1, 0) == 1) {
  26704. req += c;
  26705. }
  26706. const std::string field = "Sec-WebSocket-Key: ";
  26707. auto pos = req.find(field);
  26708. if (pos != std::string::npos) {
  26709. pos += field.size();
  26710. auto key = req.substr(pos, req.find("\r\n", pos) - pos);
  26711. auto res = "HTTP/1.1 101 Switching Protocols\r\n"
  26712. "Upgrade: websocket\r\n"
  26713. "Connection: Upgrade\r\n"
  26714. "Sec-WebSocket-Accept: " +
  26715. detail::websocket_accept_key(key) + "\r\n\r\n" +
  26716. masked_frame(0x81, "a");
  26717. detail::send_socket(sock, res.data(), res.size(), 0);
  26718. // FIN + Close, masked with a length of 2, the mask key, the code
  26719. char buf[256];
  26720. while (reply.size() < 8) {
  26721. auto n = ::recv(sock, buf, sizeof(buf), 0);
  26722. if (n <= 0) { break; }
  26723. reply.append(buf, static_cast<size_t>(n));
  26724. }
  26725. }
  26726. detail::close_socket(sock);
  26727. });
  26728. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(listener.port) +
  26729. "/ws");
  26730. auto connected = static_cast<bool>(client.connect());
  26731. std::string msg;
  26732. auto r = connected ? client.read(msg) : ws::Fail;
  26733. peer.join();
  26734. ASSERT_TRUE(connected);
  26735. EXPECT_EQ(ws::Fail, r);
  26736. detail::BufferStream strm;
  26737. strm.write(reply.data(), reply.size());
  26738. ws::Opcode opcode;
  26739. std::string payload;
  26740. bool fin;
  26741. ASSERT_EQ(
  26742. ws::impl::FrameRead::Ok,
  26743. ws::impl::read_websocket_frame(strm, opcode, payload, fin, true, 125));
  26744. EXPECT_EQ(ws::Opcode::Close, opcode);
  26745. EXPECT_EQ(std::string("\x03\xea"), payload);
  26746. }
  26747. // What a handler sees of the peer's close once read() has failed
  26748. TEST(WebSocketTest, HandlerSeesThePeersClose) {
  26749. std::mutex m;
  26750. std::condition_variable cv;
  26751. size_t handled = 0;
  26752. uint16_t seen_status = 0;
  26753. std::string seen_reason;
  26754. Server svr;
  26755. svr.set_websocket_ping_interval(0);
  26756. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  26757. std::string msg;
  26758. while (ws.read(msg)) {}
  26759. std::lock_guard<std::mutex> lock(m);
  26760. seen_status = static_cast<uint16_t>(ws.close_status());
  26761. seen_reason = ws.close_reason();
  26762. handled++;
  26763. cv.notify_one();
  26764. });
  26765. auto port = svr.bind_to_any_port("127.0.0.1");
  26766. std::thread t([&]() { svr.listen_after_bind(); });
  26767. auto se = detail::scope_exit([&] {
  26768. svr.stop();
  26769. t.join();
  26770. });
  26771. svr.wait_until_ready();
  26772. auto expect_seen = [&](size_t n, uint16_t status, const std::string &reason,
  26773. const char *label) {
  26774. std::unique_lock<std::mutex> lock(m);
  26775. ASSERT_TRUE(cv.wait_for(lock, std::chrono::seconds(5), [&] {
  26776. return handled == n;
  26777. })) << label;
  26778. EXPECT_EQ(status, seen_status) << label;
  26779. EXPECT_EQ(reason, seen_reason) << label;
  26780. };
  26781. // What a raw client sends before it drops the connection
  26782. struct Case {
  26783. const char *label;
  26784. std::string sent;
  26785. uint16_t status;
  26786. std::string reason;
  26787. };
  26788. std::vector<Case> cases = {
  26789. {"application code", masked_frame(0x88, "\x0f\xa1logout"), 4001,
  26790. "logout"},
  26791. {"normal", masked_frame(0x88, "\x03\xe8"), 1000, ""},
  26792. {"no status", masked_frame(0x88, ""), 1005, ""},
  26793. {"malformed", masked_frame(0x88, "\x03"), 1002, ""},
  26794. {"no Close", masked_frame(0x81, "hi"), 1006, ""},
  26795. };
  26796. for (size_t i = 0; i < cases.size(); i++) {
  26797. auto sock = connect_raw_websocket(port, "/ws");
  26798. ASSERT_NE(INVALID_SOCKET, sock);
  26799. detail::send_socket(sock, cases[i].sent.data(), cases[i].sent.size(), 0);
  26800. detail::close_socket(sock);
  26801. expect_seen(i + 1, cases[i].status, cases[i].reason, cases[i].label);
  26802. }
  26803. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws");
  26804. ASSERT_TRUE(client.connect());
  26805. client.close(static_cast<ws::CloseStatus>(4001), "logout");
  26806. expect_seen(cases.size() + 1, 4001, "logout", "WebSocketClient");
  26807. }
  26808. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  26809. class WebSocketSSLIntegrationTest : public ::testing::Test {
  26810. protected:
  26811. void SetUp() override {
  26812. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  26813. SERVER_PRIVATE_KEY_FILE);
  26814. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  26815. std::string msg;
  26816. ws::ReadResult ret;
  26817. while ((ret = ws.read(msg))) {
  26818. if (ret == ws::Binary) {
  26819. ws.send(msg.data(), msg.size());
  26820. } else {
  26821. ws.send(msg);
  26822. }
  26823. }
  26824. });
  26825. port_ = server_->bind_to_any_port(HOST);
  26826. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26827. server_->wait_until_ready();
  26828. }
  26829. void TearDown() override {
  26830. server_->stop();
  26831. if (server_thread_.joinable()) { server_thread_.join(); }
  26832. }
  26833. std::unique_ptr<SSLServer> server_;
  26834. std::thread server_thread_;
  26835. int port_ = 0;
  26836. };
  26837. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  26838. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  26839. {
  26840. ws::WebSocketClient client(url);
  26841. client.enable_server_certificate_verification(false);
  26842. auto calls = 0;
  26843. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  26844. calls++;
  26845. return false;
  26846. });
  26847. EXPECT_FALSE(client.connect());
  26848. EXPECT_GT(calls, 0);
  26849. }
  26850. {
  26851. ws::WebSocketClient client(url);
  26852. client.enable_server_certificate_verification(false);
  26853. client.set_session_verifier([](tls::session_t) {
  26854. return SSLVerifierResponse::CertificateRejected;
  26855. });
  26856. EXPECT_FALSE(client.connect());
  26857. }
  26858. {
  26859. ws::WebSocketClient client(url);
  26860. client.enable_server_certificate_verification(false);
  26861. client.set_session_verifier([](tls::session_t) {
  26862. return SSLVerifierResponse::CertificateAccepted;
  26863. });
  26864. EXPECT_TRUE(client.connect());
  26865. }
  26866. }
  26867. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  26868. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26869. "/ws-echo");
  26870. client.enable_server_certificate_verification(false);
  26871. ASSERT_TRUE(client.connect());
  26872. ASSERT_TRUE(client.is_open());
  26873. ASSERT_TRUE(client.send("Hello WSS"));
  26874. std::string msg;
  26875. EXPECT_EQ(ws::Text, client.read(msg));
  26876. EXPECT_EQ("Hello WSS", msg);
  26877. client.close();
  26878. }
  26879. TEST_F(WebSocketSSLIntegrationTest, UppercaseScheme) {
  26880. ws::WebSocketClient client("WSS://localhost:" + std::to_string(port_) +
  26881. "/ws-echo");
  26882. client.enable_server_certificate_verification(false);
  26883. EXPECT_TRUE(client.connect());
  26884. }
  26885. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  26886. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  26887. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  26888. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  26889. // client (without calling close() first) is the only path that runs
  26890. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  26891. // bug exactly.
  26892. //
  26893. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  26894. // when linked against an instrumented libssl; run under Valgrind to catch it
  26895. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  26896. // suite (the freed session otherwise stalls on the close handshake) — this test
  26897. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  26898. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  26899. {
  26900. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26901. "/ws-echo");
  26902. client.enable_server_certificate_verification(false);
  26903. client.set_read_timeout(2, 0);
  26904. client.set_write_timeout(2, 0);
  26905. ASSERT_TRUE(client.connect());
  26906. ASSERT_TRUE(client.is_open());
  26907. ASSERT_TRUE(client.send("still open"));
  26908. // Intentionally do NOT call client.close(): leaving scope runs
  26909. // shutdown_and_close() with the WebSocket still open, which must send the
  26910. // close frame while the TLS session is still alive.
  26911. }
  26912. }
  26913. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  26914. // shutdown_and_close() at the start of connect(), reproducing the same
  26915. // use-after-free within the test body rather than at scope exit. The second
  26916. // connect must succeed and echo, proving the close handshake ran over a live
  26917. // session. See the note above about memory-tool requirements.
  26918. TEST_F(WebSocketSSLIntegrationTest,
  26919. ReconnectWhileOpenSendsCloseOverLiveSession) {
  26920. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  26921. "/ws-echo");
  26922. client.enable_server_certificate_verification(false);
  26923. client.set_read_timeout(2, 0);
  26924. client.set_write_timeout(2, 0);
  26925. ASSERT_TRUE(client.connect());
  26926. ASSERT_TRUE(client.is_open());
  26927. ASSERT_TRUE(client.send("still open"));
  26928. // Reconnect without closing first: connect() calls shutdown_and_close() on
  26929. // the still-open connection, which must not touch a freed TLS session.
  26930. ASSERT_TRUE(client.connect());
  26931. ASSERT_TRUE(client.is_open());
  26932. ASSERT_TRUE(client.send("after reconnect"));
  26933. std::string msg;
  26934. EXPECT_EQ(ws::Text, client.read(msg));
  26935. EXPECT_EQ("after reconnect", msg);
  26936. client.close();
  26937. }
  26938. #endif
  26939. #ifdef CPPHTTPLIB_SSL_ENABLED
  26940. class WebSocketSSLCATest : public ::testing::Test {
  26941. protected:
  26942. void SetUp() override {
  26943. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  26944. SERVER_PRIVATE_KEY_FILE);
  26945. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  26946. std::string msg;
  26947. while (ws.read(msg)) {
  26948. ws.send(msg);
  26949. }
  26950. });
  26951. port_ = server_->bind_to_any_port("127.0.0.1");
  26952. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  26953. server_->wait_until_ready();
  26954. }
  26955. void TearDown() override {
  26956. server_->stop();
  26957. if (server_thread_.joinable()) { server_thread_.join(); }
  26958. }
  26959. std::string url() const {
  26960. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  26961. }
  26962. std::unique_ptr<SSLServer> server_;
  26963. std::thread server_thread_;
  26964. int port_ = 0;
  26965. };
  26966. // A custom CA loaded as PEM verifies the server with full certificate
  26967. // verification enabled
  26968. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  26969. ws::WebSocketClient client(url());
  26970. std::string cert;
  26971. read_file(SERVER_CERT2_FILE, cert);
  26972. client.load_ca_cert_store(cert.c_str(), cert.size());
  26973. ASSERT_TRUE(client.connect());
  26974. ASSERT_TRUE(client.send("hello"));
  26975. std::string msg;
  26976. EXPECT_EQ(ws::Text, client.read(msg));
  26977. EXPECT_EQ("hello", msg);
  26978. client.close();
  26979. }
  26980. // A custom CA that does not cover the server must fail verification (the
  26981. // custom CA is exclusive; system certs are not loaded alongside it)
  26982. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  26983. ws::WebSocketClient client(url());
  26984. std::string cert;
  26985. read_file(CLIENT_CA_CERT_FILE, cert);
  26986. client.load_ca_cert_store(cert.c_str(), cert.size());
  26987. auto res = client.connect();
  26988. ASSERT_FALSE(res);
  26989. EXPECT_EQ(Error::SSLServerVerification, res.error());
  26990. EXPECT_EQ(-1, res.status());
  26991. EXPECT_NE(0u, res.ssl_backend_error());
  26992. }
  26993. // The same CA as a file path rather than PEM in memory
  26994. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  26995. ws::WebSocketClient client(url());
  26996. client.set_ca_cert_path(SERVER_CERT2_FILE);
  26997. ASSERT_TRUE(client.connect());
  26998. ASSERT_TRUE(client.send("hello"));
  26999. std::string msg;
  27000. EXPECT_EQ(ws::Text, client.read(msg));
  27001. EXPECT_EQ("hello", msg);
  27002. client.close();
  27003. }
  27004. // ...and a CA file that does not cover the server still fails, so it is the
  27005. // path above that decides the outcome
  27006. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  27007. ws::WebSocketClient client(url());
  27008. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27009. ASSERT_FALSE(client.connect());
  27010. }
  27011. // Regression test: reconnecting with a native custom CA store used to reuse
  27012. // a store handle the previous TLS context had already freed (use-after-free
  27013. // under the OpenSSL backend). The context now lives as long as the client.
  27014. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  27015. ws::WebSocketClient client(url());
  27016. std::string cert;
  27017. read_file(SERVER_CERT2_FILE, cert);
  27018. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  27019. ASSERT_TRUE(client.connect());
  27020. client.close();
  27021. ASSERT_TRUE(client.connect());
  27022. ASSERT_TRUE(client.send("again"));
  27023. std::string msg;
  27024. EXPECT_EQ(ws::Text, client.read(msg));
  27025. EXPECT_EQ("again", msg);
  27026. client.close();
  27027. }
  27028. // Regression test: a certificate with a trusted chain but no identity match
  27029. // for the server IP must be rejected. The Mbed TLS backend used to skip
  27030. // verification entirely for IP hosts, so this connection succeeded there.
  27031. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  27032. // chain verification while the identity check must still fail.
  27033. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  27034. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  27035. ASSERT_TRUE(svr.is_valid());
  27036. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27037. std::string msg;
  27038. while (ws.read(msg)) {
  27039. ws.send(msg);
  27040. }
  27041. });
  27042. auto port = svr.bind_to_any_port("127.0.0.1");
  27043. auto t = std::thread([&]() { svr.listen_after_bind(); });
  27044. auto se = detail::scope_exit([&] {
  27045. svr.stop();
  27046. t.join();
  27047. });
  27048. svr.wait_until_ready();
  27049. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  27050. "/echo");
  27051. std::string cert;
  27052. read_file(SERVER_CERT_FILE, cert);
  27053. client.load_ca_cert_store(cert.c_str(), cert.size());
  27054. ASSERT_FALSE(client.connect());
  27055. }
  27056. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  27057. // SNI, so nothing binds the host name to the TLS session. These bind the
  27058. // server to "localhost" instead, the only shape that exercises the SNI and
  27059. // hostname-verification path with certificate verification left enabled.
  27060. class WebSocketSSLDnsHostTest : public ::testing::Test {
  27061. protected:
  27062. void Start(const char *cert_file) {
  27063. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  27064. SERVER_PRIVATE_KEY_FILE);
  27065. ASSERT_TRUE(server_->is_valid());
  27066. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  27067. std::string msg;
  27068. while (ws.read(msg)) {
  27069. ws.send(msg);
  27070. }
  27071. });
  27072. port_ = server_->bind_to_any_port("localhost");
  27073. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27074. server_->wait_until_ready();
  27075. }
  27076. void TearDown() override {
  27077. if (server_) { server_->stop(); }
  27078. if (server_thread_.joinable()) { server_thread_.join(); }
  27079. }
  27080. std::string url() const {
  27081. return "wss://localhost:" + std::to_string(port_) + "/echo";
  27082. }
  27083. std::unique_ptr<SSLServer> server_;
  27084. std::thread server_thread_;
  27085. int port_ = 0;
  27086. };
  27087. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  27088. // out and the connection is usable
  27089. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  27090. Start(SERVER_CERT2_FILE);
  27091. ws::WebSocketClient client(url());
  27092. client.set_ca_cert_path(SERVER_CERT2_FILE);
  27093. ASSERT_TRUE(client.connect());
  27094. ASSERT_TRUE(client.send("hello"));
  27095. std::string msg;
  27096. EXPECT_EQ(ws::Text, client.read(msg));
  27097. EXPECT_EQ("hello", msg);
  27098. client.close();
  27099. }
  27100. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  27101. // while the identity check must still reject "localhost"
  27102. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  27103. Start(SERVER_CERT_FILE);
  27104. ws::WebSocketClient client(url());
  27105. client.set_ca_cert_path(SERVER_CERT_FILE);
  27106. auto res = client.connect();
  27107. ASSERT_FALSE(res);
  27108. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  27109. EXPECT_EQ(-1, res.status());
  27110. }
  27111. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  27112. // disabled: the chain is still checked, only the identity check is skipped
  27113. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  27114. Start(SERVER_CERT_FILE);
  27115. ws::WebSocketClient client(url());
  27116. client.set_ca_cert_path(SERVER_CERT_FILE);
  27117. client.enable_server_hostname_verification(false);
  27118. ASSERT_TRUE(client.connect());
  27119. ASSERT_TRUE(client.send("hello"));
  27120. std::string msg;
  27121. EXPECT_EQ(ws::Text, client.read(msg));
  27122. EXPECT_EQ("hello", msg);
  27123. client.close();
  27124. }
  27125. // A CA that did not sign the server certificate fails the chain, even though
  27126. // the name would match
  27127. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  27128. Start(SERVER_CERT2_FILE);
  27129. ws::WebSocketClient client(url());
  27130. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  27131. ASSERT_FALSE(client.connect());
  27132. }
  27133. // With verification disabled, neither the chain nor the name is checked
  27134. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  27135. Start(SERVER_CERT_FILE);
  27136. ws::WebSocketClient client(url());
  27137. client.enable_server_certificate_verification(false);
  27138. ASSERT_TRUE(client.connect());
  27139. ASSERT_TRUE(client.send("hello"));
  27140. std::string msg;
  27141. EXPECT_EQ(ws::Text, client.read(msg));
  27142. EXPECT_EQ("hello", msg);
  27143. client.close();
  27144. }
  27145. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  27146. protected:
  27147. void SetUp() override {
  27148. server_ = httplib::detail::make_unique<SSLServer>(
  27149. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  27150. ASSERT_TRUE(server_->is_valid());
  27151. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  27152. std::string msg;
  27153. while (ws.read(msg)) {
  27154. ws.send(msg);
  27155. }
  27156. });
  27157. port_ = server_->bind_to_any_port("localhost");
  27158. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  27159. server_->wait_until_ready();
  27160. }
  27161. void TearDown() override {
  27162. server_->stop();
  27163. if (server_thread_.joinable()) { server_thread_.join(); }
  27164. }
  27165. std::string url() const {
  27166. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  27167. }
  27168. void ConnectWithClientCert(const std::string &client_cert_file,
  27169. const std::string &client_private_key_file,
  27170. const char *private_key_password) {
  27171. std::string cert_pem, key_pem;
  27172. read_file(client_cert_file, cert_pem);
  27173. read_file(client_private_key_file, key_pem);
  27174. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  27175. key_pem.c_str(), key_pem.size(),
  27176. private_key_password};
  27177. ConnectWithPem(pem);
  27178. }
  27179. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  27180. ws::WebSocketClient client(url(), pem);
  27181. ASSERT_TRUE(client.is_valid());
  27182. client.enable_server_certificate_verification(false);
  27183. ASSERT_TRUE(client.connect());
  27184. ASSERT_TRUE(client.send("hello"));
  27185. std::string msg;
  27186. EXPECT_EQ(ws::Text, client.read(msg));
  27187. EXPECT_EQ("hello", msg);
  27188. client.close();
  27189. }
  27190. std::unique_ptr<SSLServer> server_;
  27191. std::thread server_thread_;
  27192. int port_ = 0;
  27193. };
  27194. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  27195. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  27196. }
  27197. // Control for the tests above: the fixture's server really does require a
  27198. // client certificate, so it is the PEM the constructor installed that decides
  27199. // the outcome.
  27200. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  27201. ws::WebSocketClient client(url());
  27202. ASSERT_TRUE(client.is_valid());
  27203. client.enable_server_certificate_verification(false);
  27204. EXPECT_FALSE(client.connect());
  27205. }
  27206. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  27207. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  27208. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  27209. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  27210. }
  27211. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  27212. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  27213. std::string cert_pem, key_pem;
  27214. read_file(CLIENT_CERT_FILE, cert_pem);
  27215. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  27216. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  27217. std::vector<char> key(key_pem.begin(), key_pem.end());
  27218. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  27219. key.size(), nullptr};
  27220. ConnectWithPem(pem);
  27221. }
  27222. #endif
  27223. #if !defined(_WIN32)
  27224. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  27225. auto secret_dir = std::string("./symlink_test_secret");
  27226. auto served_dir = std::string("./symlink_test_served");
  27227. auto secret_file = secret_dir + "/secret.txt";
  27228. auto symlink_path = served_dir + "/escape";
  27229. // Setup: create directories and files
  27230. mkdir(secret_dir.c_str(), 0755);
  27231. mkdir(served_dir.c_str(), 0755);
  27232. {
  27233. std::ofstream ofs(secret_file);
  27234. ofs << "SECRET_DATA";
  27235. }
  27236. // Create symlink using absolute path so it resolves correctly
  27237. #ifdef PATH_MAX
  27238. char abs_secret[PATH_MAX];
  27239. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  27240. #else
  27241. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  27242. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  27243. ASSERT_NE(nullptr, abs_secret);
  27244. #endif
  27245. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  27246. auto se = detail::scope_exit([&] {
  27247. unlink(symlink_path.c_str());
  27248. unlink(secret_file.c_str());
  27249. rmdir(served_dir.c_str());
  27250. rmdir(secret_dir.c_str());
  27251. });
  27252. Server svr;
  27253. svr.set_mount_point("/", served_dir);
  27254. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27255. auto se2 = detail::scope_exit([&] {
  27256. svr.stop();
  27257. listen_thread.join();
  27258. });
  27259. svr.wait_until_ready();
  27260. Client cli("localhost", PORT);
  27261. // Symlink pointing outside base dir should be blocked
  27262. auto res = cli.Get("/escape/secret.txt");
  27263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27264. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27265. }
  27266. #else
  27267. TEST(SymlinkTest, JunctionEscapeFromBaseDirectory) {
  27268. auto secret_dir = std::string("junction_test_secret");
  27269. auto served_dir = std::string("junction_test_served");
  27270. auto secret_file = secret_dir + "\\secret.txt";
  27271. auto junction_path = served_dir + "\\escape";
  27272. ::CreateDirectoryA(secret_dir.c_str(), nullptr);
  27273. ::CreateDirectoryA(served_dir.c_str(), nullptr);
  27274. {
  27275. std::ofstream ofs(secret_file);
  27276. ofs << "SECRET_DATA";
  27277. }
  27278. // A junction needs no privilege to create, unlike a symlink
  27279. auto cmd = "mklink /J " + junction_path + " " + secret_dir + " >nul";
  27280. ASSERT_EQ(0, std::system(cmd.c_str()));
  27281. auto se = detail::scope_exit([&] {
  27282. ::RemoveDirectoryA(junction_path.c_str());
  27283. std::remove(secret_file.c_str());
  27284. ::RemoveDirectoryA(served_dir.c_str());
  27285. ::RemoveDirectoryA(secret_dir.c_str());
  27286. });
  27287. Server svr;
  27288. svr.set_mount_point("/", served_dir);
  27289. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  27290. auto se2 = detail::scope_exit([&] {
  27291. svr.stop();
  27292. listen_thread.join();
  27293. });
  27294. svr.wait_until_ready();
  27295. Client cli("localhost", PORT);
  27296. // Junction pointing outside base dir should be blocked
  27297. auto res = cli.Get("/escape/secret.txt");
  27298. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27299. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  27300. }
  27301. #endif
  27302. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  27303. // "GET /smuggled" request), reads the first response, and only then sends the
  27304. // embedded request as the body. Returns how many times /smuggled ran.
  27305. //
  27306. // The body is sent AFTER receiving the first response (as in the original
  27307. // PoC) so that the stream_line_reader cannot buffer it together with the
  27308. // headers of the first request.
  27309. static int count_smuggled_requests(const std::string &outer_head,
  27310. std::string &first_response) {
  27311. Server svr;
  27312. svr.set_mount_point("/", "./www");
  27313. std::atomic<int> smuggled_count(0);
  27314. svr.Get("/smuggled", [&](const Request &, Response &res) {
  27315. smuggled_count++;
  27316. res.set_content("oops", "text/plain");
  27317. });
  27318. svr.Post("/post", [&](const Request &req, Response &res) {
  27319. res.set_content(req.body, "text/plain");
  27320. });
  27321. auto port = svr.bind_to_any_port("localhost");
  27322. thread t = thread([&] { svr.listen_after_bind(); });
  27323. auto se = detail::scope_exit([&] {
  27324. svr.stop();
  27325. t.join();
  27326. });
  27327. svr.wait_until_ready();
  27328. auto error = Error::Success;
  27329. auto sock = detail::create_client_socket(
  27330. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  27331. /*connection_timeout_sec=*/2, 0,
  27332. /*read_timeout_sec=*/2, 0,
  27333. /*write_timeout_sec=*/2, 0, std::string(), error);
  27334. EXPECT_NE(INVALID_SOCKET, sock);
  27335. if (sock == INVALID_SOCKET) { return -1; }
  27336. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27337. // The "smuggled" request will be sent as the body of the outer request
  27338. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  27339. "Host: localhost\r\n"
  27340. "Connection: close\r\n"
  27341. "\r\n";
  27342. auto head = outer_head;
  27343. auto len = std::to_string(smuggled.size());
  27344. for (auto pos = head.find("{len}"); pos != std::string::npos;
  27345. pos = head.find("{len}", pos + len.size())) {
  27346. head.replace(pos, 5, len);
  27347. }
  27348. // Step 1: Send only the outer request headers (no body yet)
  27349. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  27350. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  27351. // Step 2: Read the first response
  27352. char buf[4096];
  27353. for (;;) {
  27354. auto n = recv(sock, buf, sizeof(buf), 0);
  27355. if (n <= 0) break;
  27356. first_response.append(buf, static_cast<size_t>(n));
  27357. // Stop once we have a complete response (headers + body)
  27358. auto hdr_end = first_response.find("\r\n\r\n");
  27359. if (hdr_end != std::string::npos) {
  27360. // Check for Content-Length to know when the body is complete
  27361. auto cl_pos = first_response.find("Content-Length:");
  27362. if (cl_pos != std::string::npos) {
  27363. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  27364. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  27365. auto cl = std::stoul(
  27366. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  27367. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  27368. } else {
  27369. break; // No Content-Length, assume headers-only response
  27370. }
  27371. }
  27372. }
  27373. // Step 3: Now send the body, which looks like a new HTTP request. On a
  27374. // vulnerable server the keep-alive loop reads this as a second request. The
  27375. // server may already have closed the connection, so the result is ignored.
  27376. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  27377. // Half-close so that a server which drained the body sees EOF and closes,
  27378. // instead of the read below waiting for the read timeout.
  27379. #ifdef _WIN32
  27380. ::shutdown(sock, SD_SEND);
  27381. #else
  27382. ::shutdown(sock, SHUT_WR);
  27383. #endif
  27384. // Step 4: Read until the server closes the connection
  27385. for (;;) {
  27386. auto n = recv(sock, buf, sizeof(buf), 0);
  27387. if (n <= 0) break;
  27388. }
  27389. return smuggled_count.load();
  27390. }
  27391. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  27392. // A GET request with Content-Length to a static file handler must have its
  27393. // body drained before the keep-alive connection is reused. Otherwise the
  27394. // unread body bytes are interpreted as the next HTTP request.
  27395. std::string first_response;
  27396. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27397. "Host: localhost\r\n"
  27398. "Content-Length: {len}\r\n"
  27399. "\r\n",
  27400. first_response));
  27401. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  27402. }
  27403. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  27404. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  27405. // be answered with 400 and the connection closed. Treating it as "no body"
  27406. // leaves the body to be parsed as the next request.
  27407. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  27408. const char *targets[] = {
  27409. "GET /file", // handler that never reads the body
  27410. "GET /not-found", // no handler matches (404)
  27411. "POST /post", // handler that reads the body
  27412. };
  27413. for (auto target : targets) {
  27414. for (auto value : values) {
  27415. std::string first_response;
  27416. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  27417. " HTTP/1.1\r\n"
  27418. "Host: localhost\r\n"
  27419. "Content-Length: " +
  27420. value + "\r\n\r\n",
  27421. first_response))
  27422. << target << " with Content-Length: " << value;
  27423. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  27424. << target << " with Content-Length: " << value;
  27425. }
  27426. }
  27427. }
  27428. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  27429. // A 400 for an unparseable request line leaves the rest of the message
  27430. // unread, so the connection must be closed rather than reused.
  27431. std::string first_response;
  27432. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  27433. "Host: localhost\r\n"
  27434. "Content-Length: {len}\r\n"
  27435. "\r\n",
  27436. first_response));
  27437. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27438. }
  27439. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  27440. // Same as above for a header block that fails to parse.
  27441. std::string first_response;
  27442. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  27443. "Host: localhost\r\n"
  27444. "Bad Header\r\n"
  27445. "Content-Length: {len}\r\n"
  27446. "\r\n",
  27447. first_response));
  27448. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  27449. }
  27450. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  27451. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  27452. // server must not read another request on that connection, even when the
  27453. // request had no body to drain.
  27454. std::string first_response;
  27455. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  27456. "Host: localhost\r\n"
  27457. "\r\n",
  27458. first_response));
  27459. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  27460. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  27461. }
  27462. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  27463. // A content reader that stops early leaves the stream inside the body.
  27464. // Draining the whole Content-Length from there, or reading the body again,
  27465. // reads into the next request, and whatever follows is parsed as a request
  27466. // of its own.
  27467. Server svr;
  27468. std::atomic<int> smuggled_count(0);
  27469. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  27470. svr.Post("/upload", [](const Request &req, Response &res,
  27471. const ContentReader &content_reader) {
  27472. // Stop at the last chunk, so the whole body has been read however it
  27473. // arrives.
  27474. auto length = req.get_header_value_u64("Content-Length");
  27475. size_t total = 0;
  27476. auto consumed = content_reader([&](const char *, size_t n) {
  27477. total += n;
  27478. return total < length;
  27479. });
  27480. EXPECT_FALSE(consumed);
  27481. if (req.has_param("retry")) {
  27482. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  27483. }
  27484. // Replace the 400 the aborted read set, which would close the connection.
  27485. res.set_redirect("/done");
  27486. });
  27487. auto port = svr.bind_to_any_port(HOST);
  27488. thread t = thread([&] { svr.listen_after_bind(); });
  27489. auto se = detail::scope_exit([&] {
  27490. svr.stop();
  27491. t.join();
  27492. });
  27493. svr.wait_until_ready();
  27494. // A front end sees the second request as a POST whose body is the GET. The
  27495. // first body is as long as the POST's headers, so draining it again reads
  27496. // exactly those and leaves the GET to be parsed next.
  27497. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  27498. "Host: localhost\r\n"
  27499. "\r\n";
  27500. std::string second_head = "POST /post HTTP/1.1\r\n"
  27501. "Host: localhost\r\n"
  27502. "Content-Length: " +
  27503. std::to_string(inner.size()) +
  27504. "\r\n"
  27505. "\r\n";
  27506. for (auto target : {"/upload", "/upload?retry"}) {
  27507. smuggled_count = 0;
  27508. std::string request = "POST " + std::string(target) +
  27509. " HTTP/1.1\r\n"
  27510. "Host: localhost\r\n"
  27511. "Content-Length: " +
  27512. std::to_string(second_head.size()) +
  27513. "\r\n"
  27514. "\r\n" +
  27515. std::string(second_head.size(), 'A') + second_head +
  27516. inner;
  27517. std::string response;
  27518. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  27519. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  27520. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  27521. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  27522. EXPECT_EQ(0, smuggled_count.load()) << target;
  27523. }
  27524. }
  27525. // An error response closes the connection anyway, so the body is left unread
  27526. // with a redirect, such as one to a login page.
  27527. static void serve_redirects(Server &svr,
  27528. const std::function<void(int)> &client) {
  27529. svr.set_pre_routing_handler([](const Request &, Response &res) {
  27530. res.set_redirect("/login");
  27531. return Server::HandlerResponse::Handled;
  27532. });
  27533. auto port = svr.bind_to_any_port(HOST);
  27534. ASSERT_GT(port, 0);
  27535. thread t = thread([&] { svr.listen_after_bind(); });
  27536. auto se = detail::scope_exit([&] {
  27537. svr.stop();
  27538. t.join();
  27539. ASSERT_FALSE(svr.is_running());
  27540. });
  27541. svr.wait_until_ready();
  27542. client(port);
  27543. }
  27544. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  27545. Server svr;
  27546. serve_redirects(svr, [](int port) {
  27547. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  27548. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  27549. std::to_string(body.size()) + "\r\n\r\n" + body +
  27550. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  27551. std::string resp;
  27552. ASSERT_TRUE(send_request(1, req, &resp, port));
  27553. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  27554. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  27555. });
  27556. }
  27557. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  27558. Server svr;
  27559. svr.set_read_timeout(0, 200000);
  27560. serve_redirects(svr, [](int port) {
  27561. // A byte every 100 ms keeps each read within the read timeout, but not the
  27562. // body as a whole, so the server closes and the bytes sent after that fail.
  27563. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  27564. "Content-Length: 10\r\n\r\n"};
  27565. parts.resize(11, "x");
  27566. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  27567. });
  27568. }
  27569. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  27570. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  27571. // must be rejected with 400 Bad Request.
  27572. Server svr;
  27573. svr.Post("/test", [&](const Request &, Response &res) {
  27574. res.set_content("ok", "text/plain");
  27575. });
  27576. thread t = thread([&] { svr.listen(HOST, PORT); });
  27577. auto se = detail::scope_exit([&] {
  27578. svr.stop();
  27579. t.join();
  27580. ASSERT_FALSE(svr.is_running());
  27581. });
  27582. svr.wait_until_ready();
  27583. // Exact "chunked"
  27584. {
  27585. auto req = "POST /test HTTP/1.1\r\n"
  27586. "Host: localhost\r\n"
  27587. "Content-Length: 5\r\n"
  27588. "Transfer-Encoding: chunked\r\n"
  27589. "Connection: close\r\n"
  27590. "\r\n"
  27591. "hello";
  27592. std::string response;
  27593. ASSERT_TRUE(send_request(1, req, &response));
  27594. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27595. response.substr(0, response.find("\r\n")));
  27596. }
  27597. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  27598. {
  27599. auto req = "POST /test HTTP/1.1\r\n"
  27600. "Host: localhost\r\n"
  27601. "Content-Length: 5\r\n"
  27602. "Transfer-Encoding: gzip, chunked\r\n"
  27603. "Connection: close\r\n"
  27604. "\r\n"
  27605. "hello";
  27606. std::string response;
  27607. ASSERT_TRUE(send_request(1, req, &response));
  27608. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27609. response.substr(0, response.find("\r\n")));
  27610. }
  27611. }
  27612. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  27613. Server svr;
  27614. svr.Post("/test", [&](const Request &, Response &res) {
  27615. res.set_content("ok", "text/plain");
  27616. });
  27617. thread t = thread([&] { svr.listen(HOST, PORT); });
  27618. auto se = detail::scope_exit([&] {
  27619. svr.stop();
  27620. t.join();
  27621. ASSERT_FALSE(svr.is_running());
  27622. });
  27623. svr.wait_until_ready();
  27624. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  27625. // length cannot be determined, so the server must answer 400 and close
  27626. // rather than treat the request as bodyless and leave the body in the
  27627. // socket for the next request to pick up.
  27628. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  27629. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  27630. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  27631. std::string response;
  27632. ASSERT_TRUE(send_request(1, req, &response));
  27633. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27634. response.substr(0, response.find("\r\n")))
  27635. << transfer_encoding;
  27636. }
  27637. // RFC 9110 5.3: the codings may also be split across several
  27638. // Transfer-Encoding lines, which combine in the order they were received.
  27639. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  27640. // just like the single-line "chunked, gzip" above.
  27641. {
  27642. auto req = "POST /test HTTP/1.1\r\n"
  27643. "Host: localhost\r\n"
  27644. "Transfer-Encoding: chunked\r\n"
  27645. "Transfer-Encoding: gzip\r\n"
  27646. "\r\n"
  27647. "0\r\n\r\n";
  27648. std::string response;
  27649. ASSERT_TRUE(send_request(1, req, &response));
  27650. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  27651. response.substr(0, response.find("\r\n")));
  27652. }
  27653. }
  27654. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  27655. Server svr;
  27656. svr.Post("/test", [&](const Request &, Response &res) {
  27657. res.set_content("ok", "text/plain");
  27658. });
  27659. auto port = svr.bind_to_any_port(HOST);
  27660. ASSERT_GT(port, 0);
  27661. thread t = thread([&] { svr.listen_after_bind(); });
  27662. auto se = detail::scope_exit([&] {
  27663. svr.stop();
  27664. t.join();
  27665. ASSERT_FALSE(svr.is_running());
  27666. });
  27667. svr.wait_until_ready();
  27668. for (auto transfer_encoding :
  27669. {"Transfer-Encoding: gzip, chunked\r\n",
  27670. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  27671. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  27672. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  27673. transfer_encoding + "\r\n0\r\n\r\n";
  27674. std::string response;
  27675. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  27676. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  27677. response.substr(0, response.find("\r\n")))
  27678. << transfer_encoding;
  27679. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  27680. << transfer_encoding;
  27681. }
  27682. }
  27683. // Regression for issue #2450: a DELETE without Content-Length on a
  27684. // keep-alive connection must not let the post-response drain consume the
  27685. // next request's bytes.
  27686. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  27687. Server svr;
  27688. std::atomic<int> delete_count(0);
  27689. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  27690. delete_count++;
  27691. res.status = StatusCode::NoContent_204;
  27692. });
  27693. auto port = svr.bind_to_any_port(HOST);
  27694. thread t = thread([&] { svr.listen_after_bind(); });
  27695. auto se = detail::scope_exit([&] {
  27696. svr.stop();
  27697. t.join();
  27698. });
  27699. svr.wait_until_ready();
  27700. auto error = Error::Success;
  27701. auto sock = detail::create_client_socket(
  27702. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27703. /*connection_timeout_sec=*/2, 0,
  27704. /*read_timeout_sec=*/2, 0,
  27705. /*write_timeout_sec=*/2, 0, std::string(), error);
  27706. ASSERT_NE(INVALID_SOCKET, sock);
  27707. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27708. auto send_request_and_read_response = [&](const std::string &req,
  27709. std::string &out) -> bool {
  27710. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  27711. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  27712. char buf[4096];
  27713. for (;;) {
  27714. auto n = recv(sock, buf, sizeof(buf), 0);
  27715. if (n <= 0) { return !out.empty(); }
  27716. out.append(buf, static_cast<size_t>(n));
  27717. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  27718. }
  27719. };
  27720. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  27721. "Host: localhost\r\n"
  27722. "\r\n";
  27723. std::string resp1;
  27724. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  27725. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  27726. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  27727. "Host: localhost\r\n"
  27728. "Connection: close\r\n"
  27729. "\r\n";
  27730. std::string resp2;
  27731. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  27732. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  27733. EXPECT_EQ(2, delete_count.load());
  27734. }
  27735. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  27736. Server svr;
  27737. svr.Post("/ingest", [&](const Request &, Response &res,
  27738. const ContentReader &content_reader) {
  27739. auto consumed = content_reader([](const char *, size_t) { return false; });
  27740. EXPECT_FALSE(consumed);
  27741. res.status = StatusCode::Conflict_409;
  27742. res.set_header("Connection", "close");
  27743. });
  27744. auto port = svr.bind_to_any_port(HOST);
  27745. thread t = thread([&] { svr.listen_after_bind(); });
  27746. auto se = detail::scope_exit([&] {
  27747. svr.stop();
  27748. t.join();
  27749. });
  27750. svr.wait_until_ready();
  27751. auto error = Error::Success;
  27752. auto sock = detail::create_client_socket(
  27753. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  27754. /*connection_timeout_sec=*/2, 0,
  27755. /*read_timeout_sec=*/1, 0,
  27756. /*write_timeout_sec=*/2, 0, std::string(), error);
  27757. ASSERT_NE(INVALID_SOCKET, sock);
  27758. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  27759. std::string request = "POST /ingest HTTP/1.1\r\n"
  27760. "Host: localhost\r\n"
  27761. "Transfer-Encoding: chunked\r\n"
  27762. "\r\n"
  27763. "4\r\n"
  27764. "data\r\n";
  27765. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  27766. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  27767. std::string response;
  27768. ssize_t received = 0;
  27769. do {
  27770. char buf[4096];
  27771. received = recv(sock, buf, sizeof(buf), 0);
  27772. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  27773. } while (received > 0);
  27774. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  27775. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  27776. EXPECT_EQ(0, received);
  27777. }
  27778. namespace no_proxy_test {
  27779. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  27780. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  27781. // calling listen().
  27782. class ScopedServer {
  27783. public:
  27784. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  27785. ~ScopedServer() {
  27786. svr_.stop();
  27787. if (th_.joinable()) { th_.join(); }
  27788. }
  27789. Server &svr() { return svr_; }
  27790. int port() const { return port_; }
  27791. void listen() {
  27792. th_ = std::thread([this] { svr_.listen_after_bind(); });
  27793. svr_.wait_until_ready();
  27794. }
  27795. private:
  27796. Server svr_;
  27797. std::thread th_;
  27798. int port_ = 0;
  27799. };
  27800. class ProxyAndTargetServers {
  27801. public:
  27802. ProxyAndTargetServers() {
  27803. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  27804. proxy_hits_++;
  27805. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27806. res.set_content("via-proxy", "text/plain");
  27807. });
  27808. target_.Get(".*", [this](const Request &req, Response &res) {
  27809. target_hits_++;
  27810. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  27811. res.set_content("direct", "text/plain");
  27812. });
  27813. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  27814. target_port_ = target_.bind_to_any_port("127.0.0.1");
  27815. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  27816. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  27817. proxy_mock_.wait_until_ready();
  27818. target_.wait_until_ready();
  27819. }
  27820. ~ProxyAndTargetServers() {
  27821. proxy_mock_.stop();
  27822. target_.stop();
  27823. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  27824. if (target_thread_.joinable()) { target_thread_.join(); }
  27825. }
  27826. Server &proxy_mock() { return proxy_mock_; }
  27827. Server &target() { return target_; }
  27828. int proxy_port() const { return proxy_port_; }
  27829. int target_port() const { return target_port_; }
  27830. int proxy_hits() const { return proxy_hits_.load(); }
  27831. int target_hits() const { return target_hits_.load(); }
  27832. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  27833. void reset_counters() {
  27834. proxy_hits_ = 0;
  27835. target_hits_ = 0;
  27836. last_had_proxy_authz_ = false;
  27837. }
  27838. private:
  27839. Server proxy_mock_;
  27840. Server target_;
  27841. std::thread proxy_thread_;
  27842. std::thread target_thread_;
  27843. int proxy_port_ = 0;
  27844. int target_port_ = 0;
  27845. std::atomic<int> proxy_hits_{0};
  27846. std::atomic<int> target_hits_{0};
  27847. std::atomic<bool> last_had_proxy_authz_{false};
  27848. };
  27849. inline std::unique_ptr<Client> make_client(const std::string &host,
  27850. ProxyAndTargetServers &s) {
  27851. auto cli = detail::make_unique<Client>(host, s.target_port());
  27852. cli->set_direct_hostname_addr_map({{host, "127.0.0.1"}});
  27853. cli->set_proxy("127.0.0.1", s.proxy_port());
  27854. return cli;
  27855. }
  27856. } // namespace no_proxy_test
  27857. using no_proxy_test::make_client;
  27858. using no_proxy_test::ProxyAndTargetServers;
  27859. // A stream request carries the credentials a buffered request does
  27860. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  27861. no_proxy_test::ScopedServer origin;
  27862. origin.svr().Get("/x", [](const Request &req, Response &res) {
  27863. res.set_content(req.get_header_value("Authorization"), "text/plain");
  27864. });
  27865. origin.listen();
  27866. Client cli("127.0.0.1", origin.port());
  27867. cli.set_basic_auth("user", "pass");
  27868. auto handle = cli.open_stream("GET", "/x");
  27869. ASSERT_TRUE(handle.is_valid());
  27870. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  27871. Client bearer("127.0.0.1", origin.port());
  27872. bearer.set_bearer_token_auth("tok");
  27873. auto handle2 = bearer.open_stream("GET", "/x");
  27874. ASSERT_TRUE(handle2.is_valid());
  27875. EXPECT_EQ("Bearer tok", read_all(handle2));
  27876. }
  27877. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  27878. // takes its own credentials, as for a buffered request
  27879. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  27880. std::string target, authz, proxy_authz;
  27881. no_proxy_test::ScopedServer proxy;
  27882. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27883. target = req.target;
  27884. authz = req.get_header_value("Authorization");
  27885. proxy_authz = req.get_header_value("Proxy-Authorization");
  27886. res.set_content("ok", "text/plain");
  27887. });
  27888. proxy.listen();
  27889. Client cli("origin.example", 8080);
  27890. cli.set_proxy("127.0.0.1", proxy.port());
  27891. cli.set_proxy_basic_auth("puser", "ppass");
  27892. cli.set_basic_auth("user", "pass");
  27893. auto handle = cli.open_stream("GET", "/x");
  27894. ASSERT_TRUE(handle.is_valid());
  27895. EXPECT_EQ("ok", read_all(handle));
  27896. EXPECT_EQ("http://origin.example:8080/x", target);
  27897. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  27898. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  27899. }
  27900. // In absolute-form the path follows the authority, so a path that does not
  27901. // begin with '/' would make the proxy connect to another host
  27902. TEST(ProxyAbsoluteFormTest, PathMustNotExtendTheAuthority) {
  27903. std::vector<std::string> targets;
  27904. no_proxy_test::ScopedServer proxy;
  27905. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  27906. targets.push_back(req.target);
  27907. res.set_content("ok", "text/plain");
  27908. });
  27909. proxy.listen();
  27910. Client cli("origin.example", 8080);
  27911. cli.set_proxy("127.0.0.1", proxy.port());
  27912. cli.set_basic_auth("user", "pass");
  27913. for (const auto &path : {"@evil.example/x", ".evil.example/x", ":81/x"}) {
  27914. auto res = cli.Get(path);
  27915. EXPECT_FALSE(res) << path;
  27916. auto handle = cli.open_stream("GET", path);
  27917. EXPECT_FALSE(handle.is_valid()) << path;
  27918. }
  27919. EXPECT_TRUE(targets.empty());
  27920. auto res = cli.Get("/x");
  27921. ASSERT_TRUE(res);
  27922. ASSERT_EQ(1u, targets.size());
  27923. EXPECT_EQ("http://origin.example:8080/x", targets[0]);
  27924. }
  27925. TEST(NoProxyTest, ExactHostnameBypasses) {
  27926. ProxyAndTargetServers s;
  27927. auto cli = make_client("example.com", s);
  27928. cli->set_no_proxy({"example.com"});
  27929. auto res = cli->Get("/");
  27930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27931. EXPECT_EQ(0, s.proxy_hits());
  27932. EXPECT_EQ(1, s.target_hits());
  27933. }
  27934. TEST(NoProxyTest, SubdomainBypasses) {
  27935. ProxyAndTargetServers s;
  27936. auto cli = make_client("foo.example.com", s);
  27937. cli->set_no_proxy({"example.com"});
  27938. auto res = cli->Get("/");
  27939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27940. EXPECT_EQ(0, s.proxy_hits());
  27941. EXPECT_EQ(1, s.target_hits());
  27942. }
  27943. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  27944. // Regression guard: "evilexample.com" must not be considered a subdomain
  27945. // of "example.com". Without the dot-boundary rule, a naive endsWith
  27946. // check would let traffic bypass the proxy and leak credentials direct
  27947. // to the attacker host.
  27948. ProxyAndTargetServers s;
  27949. auto cli = make_client("evilexample.com", s);
  27950. cli->set_no_proxy({"example.com"});
  27951. auto res = cli->Get("/");
  27952. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27953. EXPECT_GE(s.proxy_hits(), 1);
  27954. EXPECT_EQ(0, s.target_hits());
  27955. }
  27956. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  27957. ProxyAndTargetServers s;
  27958. auto cli = make_client("example.com.evil.com", s);
  27959. cli->set_no_proxy({"example.com"});
  27960. auto res = cli->Get("/");
  27961. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27962. EXPECT_GE(s.proxy_hits(), 1);
  27963. EXPECT_EQ(0, s.target_hits());
  27964. }
  27965. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  27966. ProxyAndTargetServers s;
  27967. auto cli = make_client("example.com", s);
  27968. cli->set_no_proxy({".example.com"});
  27969. auto res = cli->Get("/");
  27970. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27971. EXPECT_EQ(0, s.proxy_hits());
  27972. EXPECT_EQ(1, s.target_hits());
  27973. }
  27974. TEST(NoProxyTest, CaseInsensitiveHostname) {
  27975. ProxyAndTargetServers s;
  27976. auto cli = make_client("Example.COM", s);
  27977. cli->set_no_proxy({"EXAMPLE.com"});
  27978. auto res = cli->Get("/");
  27979. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27980. EXPECT_EQ(0, s.proxy_hits());
  27981. EXPECT_EQ(1, s.target_hits());
  27982. }
  27983. TEST(NoProxyTest, TrailingDotIsNormalized) {
  27984. ProxyAndTargetServers s;
  27985. auto cli = make_client("example.com.", s);
  27986. cli->set_no_proxy({"example.com"});
  27987. auto res = cli->Get("/");
  27988. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  27989. EXPECT_EQ(0, s.proxy_hits());
  27990. EXPECT_EQ(1, s.target_hits());
  27991. }
  27992. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  27993. // Trailing dots must be normalized on BOTH sides — host and entry.
  27994. // An implementation that only strips the host-side trailing dot would
  27995. // fail to match host "example.com" against entry "example.com." because
  27996. // a literal substring search would compare 11 chars against 12.
  27997. ProxyAndTargetServers s;
  27998. auto cli = make_client("example.com", s);
  27999. cli->set_no_proxy({"example.com."});
  28000. auto res = cli->Get("/");
  28001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28002. EXPECT_EQ(0, s.proxy_hits());
  28003. EXPECT_EQ(1, s.target_hits());
  28004. }
  28005. TEST(NoProxyTest, WildcardBypassesEverything) {
  28006. ProxyAndTargetServers s;
  28007. auto cli = make_client("anything.invalid.test", s);
  28008. cli->set_no_proxy({"*"});
  28009. auto res = cli->Get("/");
  28010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28011. EXPECT_EQ(0, s.proxy_hits());
  28012. EXPECT_EQ(1, s.target_hits());
  28013. }
  28014. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  28015. ProxyAndTargetServers s;
  28016. Client cli("127.0.0.1", s.target_port());
  28017. cli.set_proxy("127.0.0.1", s.proxy_port());
  28018. cli.set_no_proxy({"127.0.0.1"});
  28019. auto res = cli.Get("/");
  28020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28021. EXPECT_EQ(0, s.proxy_hits());
  28022. EXPECT_EQ(1, s.target_hits());
  28023. }
  28024. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  28025. ProxyAndTargetServers s;
  28026. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  28027. cli.set_direct_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  28028. cli.set_proxy("127.0.0.1", s.proxy_port());
  28029. cli.set_no_proxy({"::1"});
  28030. auto res = cli.Get("/");
  28031. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28032. EXPECT_EQ(0, s.proxy_hits());
  28033. EXPECT_EQ(1, s.target_hits());
  28034. }
  28035. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  28036. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  28037. // must still be recognized as IPv6 for CIDR matching. Implementations
  28038. // that detect IPv6 only when the host begins with '[' would parse the
  28039. // host as a hostname and miss the match.
  28040. ProxyAndTargetServers s;
  28041. Client cli("fe80::1", s.target_port());
  28042. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28043. cli.set_proxy("127.0.0.1", s.proxy_port());
  28044. cli.set_no_proxy({"fe80::/10"});
  28045. auto res = cli.Get("/");
  28046. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28047. EXPECT_EQ(0, s.proxy_hits());
  28048. EXPECT_EQ(1, s.target_hits());
  28049. }
  28050. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  28051. ProxyAndTargetServers s;
  28052. Client cli("::1", s.target_port());
  28053. cli.set_direct_hostname_addr_map({{"::1", "127.0.0.1"}});
  28054. cli.set_proxy("127.0.0.1", s.proxy_port());
  28055. cli.set_no_proxy({"[::1]"});
  28056. auto res = cli.Get("/");
  28057. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28058. EXPECT_EQ(0, s.proxy_hits());
  28059. EXPECT_EQ(1, s.target_hits());
  28060. }
  28061. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  28062. ProxyAndTargetServers s;
  28063. Client cli("fe80::1", s.target_port());
  28064. cli.set_direct_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  28065. cli.set_proxy("127.0.0.1", s.proxy_port());
  28066. cli.set_no_proxy({"[fe80::]/10"});
  28067. auto res = cli.Get("/");
  28068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28069. EXPECT_EQ(0, s.proxy_hits());
  28070. EXPECT_EQ(1, s.target_hits());
  28071. }
  28072. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  28073. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  28074. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  28075. // tricks via address-family conversion.
  28076. ProxyAndTargetServers s;
  28077. Client cli("::ffff:127.0.0.1", s.target_port());
  28078. cli.set_direct_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  28079. cli.set_proxy("127.0.0.1", s.proxy_port());
  28080. cli.set_no_proxy({"127.0.0.1"});
  28081. auto res = cli.Get("/");
  28082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28083. EXPECT_GE(s.proxy_hits(), 1);
  28084. EXPECT_EQ(0, s.target_hits());
  28085. }
  28086. TEST(NoProxyTest, IPv4CidrMatch) {
  28087. ProxyAndTargetServers s;
  28088. Client cli("127.0.0.1", s.target_port());
  28089. cli.set_proxy("127.0.0.1", s.proxy_port());
  28090. cli.set_no_proxy({"127.0.0.0/8"});
  28091. auto res = cli.Get("/");
  28092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28093. EXPECT_EQ(0, s.proxy_hits());
  28094. EXPECT_EQ(1, s.target_hits());
  28095. }
  28096. TEST(NoProxyTest, IPv4CidrNonMatch) {
  28097. ProxyAndTargetServers s;
  28098. Client cli("127.0.0.1", s.target_port());
  28099. cli.set_proxy("127.0.0.1", s.proxy_port());
  28100. cli.set_no_proxy({"10.0.0.0/8"});
  28101. auto res = cli.Get("/");
  28102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28103. EXPECT_GE(s.proxy_hits(), 1);
  28104. EXPECT_EQ(0, s.target_hits());
  28105. }
  28106. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  28107. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  28108. // IPv4 target matches.
  28109. ProxyAndTargetServers s;
  28110. Client cli("127.0.0.1", s.target_port());
  28111. cli.set_proxy("127.0.0.1", s.proxy_port());
  28112. cli.set_no_proxy({"0.0.0.0/0"});
  28113. auto res = cli.Get("/");
  28114. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28115. EXPECT_EQ(0, s.proxy_hits());
  28116. EXPECT_EQ(1, s.target_hits());
  28117. }
  28118. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  28119. ProxyAndTargetServers s;
  28120. Client cli("127.0.0.1", s.target_port());
  28121. cli.set_proxy("127.0.0.1", s.proxy_port());
  28122. cli.set_no_proxy({"127.0.0.1"});
  28123. auto res = cli.Get("/");
  28124. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28125. EXPECT_EQ(0, s.proxy_hits());
  28126. EXPECT_EQ(1, s.target_hits());
  28127. }
  28128. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  28129. ProxyAndTargetServers s;
  28130. Client cli("127.0.0.1", s.target_port());
  28131. cli.set_proxy("127.0.0.1", s.proxy_port());
  28132. cli.set_no_proxy({"127.0.0.0/33"});
  28133. auto res = cli.Get("/");
  28134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28135. EXPECT_GE(s.proxy_hits(), 1);
  28136. EXPECT_EQ(0, s.target_hits());
  28137. }
  28138. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  28139. // Empty prefix after the slash must be rejected, not silently treated as /32.
  28140. ProxyAndTargetServers s;
  28141. Client cli("127.0.0.1", s.target_port());
  28142. cli.set_proxy("127.0.0.1", s.proxy_port());
  28143. cli.set_no_proxy({"127.0.0.1/"});
  28144. auto res = cli.Get("/");
  28145. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28146. EXPECT_GE(s.proxy_hits(), 1);
  28147. EXPECT_EQ(0, s.target_hits());
  28148. }
  28149. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  28150. ProxyAndTargetServers s;
  28151. auto cli = make_client("internal.corp", s);
  28152. cli->set_proxy_basic_auth("u", "p");
  28153. cli->set_no_proxy({"internal.corp"});
  28154. auto res = cli->Get("/");
  28155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28156. EXPECT_EQ(1, s.target_hits());
  28157. EXPECT_EQ(0, s.proxy_hits());
  28158. EXPECT_FALSE(s.last_had_proxy_authz())
  28159. << "Proxy-Authorization must not be sent direct to the target";
  28160. }
  28161. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  28162. ProxyAndTargetServers s;
  28163. auto cli = make_client("public.example", s);
  28164. cli->set_proxy_basic_auth("u", "p");
  28165. cli->set_no_proxy({"internal.corp"}); // does not match
  28166. auto res = cli->Get("/");
  28167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28168. EXPECT_GE(s.proxy_hits(), 1);
  28169. EXPECT_TRUE(s.last_had_proxy_authz());
  28170. }
  28171. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  28172. std::atomic<int> hits{0};
  28173. std::atomic<int> hits_with_authz{0};
  28174. no_proxy_test::ScopedServer proxy_mock;
  28175. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28176. hits++;
  28177. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  28178. if (req.target.find("/redir") != std::string::npos) {
  28179. res.set_redirect("http://other.example/landed");
  28180. } else {
  28181. res.set_content("via-proxy", "text/plain");
  28182. }
  28183. });
  28184. proxy_mock.listen();
  28185. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  28186. hits = 0;
  28187. hits_with_authz = 0;
  28188. Client cli("public.example", 80);
  28189. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28190. cli.set_proxy_basic_auth(c.first, c.second);
  28191. cli.set_follow_location(true);
  28192. // The redirect to another host goes through the proxy as well
  28193. auto res = cli.Get("/redir");
  28194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28195. EXPECT_EQ(2, hits.load());
  28196. EXPECT_EQ(2, hits_with_authz.load());
  28197. }
  28198. }
  28199. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  28200. ProxyAndTargetServers s;
  28201. auto cli = make_client("anything.test", s);
  28202. auto res = cli->Get("/");
  28203. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28204. EXPECT_GE(s.proxy_hits(), 1);
  28205. EXPECT_EQ(0, s.target_hits());
  28206. }
  28207. TEST(NoProxyTest, PortSpecificEntryRejected) {
  28208. ProxyAndTargetServers s;
  28209. auto cli = make_client("example.com", s);
  28210. cli->set_no_proxy({"example.com:8080"});
  28211. auto res = cli->Get("/");
  28212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28213. EXPECT_GE(s.proxy_hits(), 1);
  28214. EXPECT_EQ(0, s.target_hits());
  28215. }
  28216. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  28217. ProxyAndTargetServers s;
  28218. auto cli = make_client("anything.test", s);
  28219. cli->set_no_proxy({"", " ", "\t"});
  28220. auto res = cli->Get("/");
  28221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28222. EXPECT_GE(s.proxy_hits(), 1);
  28223. EXPECT_EQ(0, s.target_hits());
  28224. }
  28225. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  28226. // An entry with leading/trailing whitespace must still match — env-style
  28227. // values are commonly pasted with stray spaces and an implementation
  28228. // that feeds the raw token directly to inet_pton would fail to match
  28229. // valid CIDRs because of the spaces.
  28230. ProxyAndTargetServers s;
  28231. Client cli("127.0.0.1", s.target_port());
  28232. cli.set_proxy("127.0.0.1", s.proxy_port());
  28233. cli.set_no_proxy({" 127.0.0.0/8 "});
  28234. auto res = cli.Get("/");
  28235. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28236. EXPECT_EQ(0, s.proxy_hits());
  28237. EXPECT_EQ(1, s.target_hits());
  28238. }
  28239. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  28240. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  28241. // go direct and must NOT carry Proxy-Authorization.
  28242. std::atomic<int> proxy_hits{0};
  28243. std::atomic<int> target_hits{0};
  28244. std::atomic<bool> target_saw_authz{false};
  28245. no_proxy_test::ScopedServer proxy_mock, target;
  28246. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28247. proxy_hits++;
  28248. res.status = 302;
  28249. res.set_header("Location", "http://127.0.0.1:" +
  28250. std::to_string(target.port()) + "/landed");
  28251. });
  28252. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28253. target_hits++;
  28254. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  28255. res.set_content("direct", "text/plain");
  28256. });
  28257. proxy_mock.listen();
  28258. target.listen();
  28259. Client cli("public.example", target.port());
  28260. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28261. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28262. cli.set_proxy_basic_auth("u", "p");
  28263. cli.set_no_proxy({"127.0.0.1"});
  28264. cli.set_follow_location(true);
  28265. auto res = cli.Get("/redir");
  28266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28267. EXPECT_GE(proxy_hits.load(), 1);
  28268. EXPECT_GE(target_hits.load(), 1);
  28269. EXPECT_FALSE(target_saw_authz.load());
  28270. }
  28271. #ifdef CPPHTTPLIB_SSL_ENABLED
  28272. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  28273. // Direct origin replying 407 must not trigger the digest retry; otherwise
  28274. // proxy creds would be sent to the (possibly hostile) origin.
  28275. std::atomic<int> target_hits{0};
  28276. std::atomic<bool> target_saw_proxy_authz{false};
  28277. no_proxy_test::ScopedServer target;
  28278. target.svr().Get(".*", [&](const Request &req, Response &res) {
  28279. target_hits++;
  28280. if (req.has_header("Proxy-Authorization")) {
  28281. target_saw_proxy_authz = true;
  28282. }
  28283. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28284. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  28285. "nonce=\"abc\", algorithm=MD5");
  28286. });
  28287. target.listen();
  28288. // The proxy address is set to the target's port: the bypass MUST kick in;
  28289. // if it doesn't, the test still routes "via proxy" to the same server and
  28290. // the Proxy-Authorization assertion below catches the leak.
  28291. Client cli("evil.example", target.port());
  28292. cli.set_direct_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  28293. cli.set_proxy("127.0.0.1", target.port());
  28294. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28295. cli.set_no_proxy({"evil.example"});
  28296. auto res = cli.Get("/x");
  28297. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28298. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28299. EXPECT_EQ(1, target_hits.load());
  28300. EXPECT_FALSE(target_saw_proxy_authz.load());
  28301. }
  28302. #endif
  28303. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  28304. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  28305. std::atomic<int> proxy_hits{0};
  28306. std::atomic<int> bypass_hits{0};
  28307. std::atomic<bool> proxy_saw_c_url{false};
  28308. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  28309. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  28310. proxy_hits++;
  28311. if (req.path.find("/start") != std::string::npos) {
  28312. res.status = 302;
  28313. res.set_header("Location", "http://127.0.0.1:" +
  28314. std::to_string(bypass_server.port()) +
  28315. "/middle");
  28316. return;
  28317. }
  28318. if (req.path.find("/end") != std::string::npos) {
  28319. proxy_saw_c_url = true;
  28320. res.set_content("c-via-proxy", "text/plain");
  28321. return;
  28322. }
  28323. res.set_content("unexpected", "text/plain");
  28324. });
  28325. // public.example's "advertised" port is arbitrary (the request never lands
  28326. // there — it goes through the proxy), but use a dynamic value to stay
  28327. // friendly with sharded parallel runs.
  28328. int public_port = bypass_server.port();
  28329. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  28330. bypass_hits++;
  28331. res.status = 302;
  28332. res.set_header("Location", "http://public.example:" +
  28333. std::to_string(public_port) + "/end");
  28334. });
  28335. proxy_mock.listen();
  28336. bypass_server.listen();
  28337. Client cli("public.example", public_port);
  28338. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28339. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28340. cli.set_no_proxy({"127.0.0.1"});
  28341. cli.set_follow_location(true);
  28342. auto res = cli.Get("/start");
  28343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28344. EXPECT_EQ(StatusCode::OK_200, res->status);
  28345. EXPECT_EQ("c-via-proxy", res->body);
  28346. EXPECT_GE(proxy_hits.load(), 2);
  28347. EXPECT_GE(bypass_hits.load(), 1);
  28348. EXPECT_TRUE(proxy_saw_c_url.load());
  28349. }
  28350. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  28351. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  28352. // request reconnects to the correct endpoint.
  28353. std::atomic<int> proxy_hits{0};
  28354. std::atomic<int> target_hits{0};
  28355. no_proxy_test::ScopedServer proxy_mock, target;
  28356. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  28357. proxy_hits++;
  28358. res.set_content("via-proxy", "text/plain");
  28359. });
  28360. target.svr().Get(".*", [&](const Request &, Response &res) {
  28361. target_hits++;
  28362. res.set_content("direct", "text/plain");
  28363. });
  28364. proxy_mock.listen();
  28365. target.listen();
  28366. Client cli("public.example", target.port());
  28367. cli.set_direct_hostname_addr_map({{"public.example", "127.0.0.1"}});
  28368. cli.set_proxy("127.0.0.1", proxy_mock.port());
  28369. cli.set_keep_alive(true);
  28370. auto res1 = cli.Get("/a");
  28371. ASSERT_TRUE(res1);
  28372. EXPECT_EQ("via-proxy", res1->body);
  28373. EXPECT_EQ(1, proxy_hits.load());
  28374. EXPECT_EQ(0, target_hits.load());
  28375. cli.set_no_proxy({"public.example"});
  28376. auto res2 = cli.Get("/b");
  28377. ASSERT_TRUE(res2);
  28378. EXPECT_EQ("direct", res2->body);
  28379. EXPECT_EQ(1, proxy_hits.load());
  28380. EXPECT_EQ(1, target_hits.load());
  28381. }
  28382. // Forward declarations (see the base64_encode note).
  28383. namespace httplib {
  28384. namespace detail {
  28385. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  28386. int shutdown_socket(socket_t sock) noexcept;
  28387. } // namespace detail
  28388. } // namespace httplib
  28389. namespace proxy_tunnel_test {
  28390. const char *const kTunnelEstablished =
  28391. "HTTP/1.1 200 Connection established\r\n\r\n";
  28392. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  28393. using ConnectReply = std::function<std::string(const std::string &head)>;
  28394. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  28395. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  28396. class ScopedConnectProxy {
  28397. public:
  28398. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  28399. : forward_port_(forward_port), reply_(std::move(reply)) {
  28400. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  28401. if (listen_sock_ == INVALID_SOCKET) { return; }
  28402. auto a = loopback(0);
  28403. auto addr = reinterpret_cast<sockaddr *>(&a);
  28404. socklen_t alen = sizeof(a);
  28405. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  28406. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  28407. ::listen(listen_sock_, 4) != 0) {
  28408. return;
  28409. }
  28410. port_ = ntohs(a.sin_port);
  28411. th_ = std::thread([this] { run(); });
  28412. }
  28413. ~ScopedConnectProxy() {
  28414. if (th_.joinable()) {
  28415. stop_ = true;
  28416. auto wake = connect_to(port_);
  28417. th_.join();
  28418. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  28419. }
  28420. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  28421. }
  28422. int port() const { return port_; }
  28423. int connect_hits() const { return connect_hits_.load(); }
  28424. // Head of the last CONNECT request, as the proxy saw it on the wire.
  28425. std::string connect_request() const {
  28426. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28427. return connect_request_;
  28428. }
  28429. private:
  28430. static sockaddr_in loopback(int port) {
  28431. sockaddr_in a{};
  28432. a.sin_family = AF_INET;
  28433. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  28434. a.sin_port = htons(static_cast<unsigned short>(port));
  28435. return a;
  28436. }
  28437. static socket_t connect_to(int port) {
  28438. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  28439. if (sock == INVALID_SOCKET) { return sock; }
  28440. auto a = loopback(port);
  28441. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  28442. detail::close_socket(sock);
  28443. return INVALID_SOCKET;
  28444. }
  28445. return sock;
  28446. }
  28447. static bool send_all(socket_t sock, const char *data, size_t size) {
  28448. while (size > 0) {
  28449. auto n = detail::send_socket(sock, data, size, 0);
  28450. if (n <= 0) { return false; }
  28451. data += n;
  28452. size -= static_cast<size_t>(n);
  28453. }
  28454. return true;
  28455. }
  28456. void run() {
  28457. for (;;) {
  28458. auto client = ::accept(listen_sock_, nullptr, nullptr);
  28459. if (stop_) {
  28460. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  28461. return;
  28462. }
  28463. if (client == INVALID_SOCKET) { continue; }
  28464. serve(client);
  28465. detail::close_socket(client);
  28466. }
  28467. }
  28468. void serve(socket_t client) {
  28469. std::string head;
  28470. char buf[2048];
  28471. while (head.find("\r\n\r\n") == std::string::npos) {
  28472. if (detail::select_read(client, 5, 0) <= 0) { return; }
  28473. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  28474. if (n <= 0) { return; }
  28475. head.append(buf, static_cast<size_t>(n));
  28476. }
  28477. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  28478. connect_hits_++;
  28479. {
  28480. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  28481. connect_request_ = head;
  28482. }
  28483. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  28484. if (!send_all(client, res.data(), res.size()) ||
  28485. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  28486. return;
  28487. }
  28488. auto origin = connect_to(forward_port_);
  28489. if (origin == INVALID_SOCKET) { return; }
  28490. // When either side stops, shut both down so the other pump returns too.
  28491. auto pump = [&](socket_t from, socket_t to) {
  28492. char b[8192];
  28493. for (;;) {
  28494. auto n = detail::read_socket(from, b, sizeof(b), 0);
  28495. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  28496. }
  28497. detail::shutdown_socket(client);
  28498. detail::shutdown_socket(origin);
  28499. };
  28500. std::thread up([&] { pump(client, origin); });
  28501. pump(origin, client);
  28502. up.join();
  28503. detail::close_socket(origin);
  28504. }
  28505. int forward_port_;
  28506. ConnectReply reply_;
  28507. socket_t listen_sock_ = INVALID_SOCKET;
  28508. int port_ = 0;
  28509. std::thread th_;
  28510. std::atomic<bool> stop_{false};
  28511. std::atomic<int> connect_hits_{0};
  28512. mutable std::mutex connect_request_mutex_;
  28513. std::string connect_request_;
  28514. };
  28515. } // namespace proxy_tunnel_test
  28516. #ifdef CPPHTTPLIB_SSL_ENABLED
  28517. namespace proxy_tunnel_test {
  28518. // SSLServer counterpart to no_proxy_test::ScopedServer.
  28519. class ScopedSSLServer {
  28520. public:
  28521. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  28522. port_ = svr_.bind_to_any_port("127.0.0.1");
  28523. }
  28524. ~ScopedSSLServer() {
  28525. svr_.stop();
  28526. if (th_.joinable()) { th_.join(); }
  28527. }
  28528. SSLServer &svr() { return svr_; }
  28529. int port() const { return port_; }
  28530. void listen() {
  28531. th_ = std::thread([this] { svr_.listen_after_bind(); });
  28532. svr_.wait_until_ready();
  28533. }
  28534. private:
  28535. SSLServer svr_;
  28536. std::thread th_;
  28537. int port_ = 0;
  28538. };
  28539. // Sends one request through the CONNECT proxy to the TLS origin with a
  28540. // credential configured for each hop, and checks that each credential reaches
  28541. // only the hop it was configured for: the proxy's on the CONNECT request, the
  28542. // origin's (every header in origin_headers) on the tunnelled request.
  28543. void CredentialsStayWithTheirHop(
  28544. const std::function<void(SSLClient &)> &set_credentials,
  28545. const std::string &scheme,
  28546. const std::vector<std::string> &origin_headers = {"Authorization"},
  28547. bool stream = false) {
  28548. std::atomic<int> origin_hits{0};
  28549. std::atomic<bool> origin_saw_proxy_authz{false};
  28550. std::atomic<bool> origin_saw_headers{false};
  28551. ScopedSSLServer origin;
  28552. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28553. origin_hits++;
  28554. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  28555. origin_saw_headers =
  28556. std::all_of(origin_headers.begin(), origin_headers.end(),
  28557. [&](const std::string &h) { return req.has_header(h); });
  28558. res.set_content("ok", "text/plain");
  28559. });
  28560. origin.listen();
  28561. ScopedConnectProxy proxy(origin.port());
  28562. ASSERT_NE(0, proxy.port());
  28563. // Pinned to 127.0.0.1 for the same reason as the test below.
  28564. SSLClient cli("127.0.0.1", origin.port());
  28565. cli.enable_server_certificate_verification(false);
  28566. cli.set_proxy("127.0.0.1", proxy.port());
  28567. set_credentials(cli);
  28568. if (stream) {
  28569. auto handle = cli.open_stream("GET", "/x");
  28570. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  28571. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  28572. } else {
  28573. auto res = cli.Get("/x");
  28574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28575. EXPECT_EQ(StatusCode::OK_200, res->status);
  28576. }
  28577. EXPECT_EQ(1, origin_hits.load());
  28578. EXPECT_EQ(1, proxy.connect_hits());
  28579. EXPECT_TRUE(origin_saw_headers.load());
  28580. EXPECT_FALSE(origin_saw_proxy_authz.load())
  28581. << "Proxy-Authorization must not be sent inside the tunnel";
  28582. auto connect_req = proxy.connect_request();
  28583. EXPECT_NE(std::string::npos,
  28584. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  28585. for (const auto &h : origin_headers) {
  28586. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  28587. << h << " must not be sent to the proxy on CONNECT";
  28588. }
  28589. }
  28590. } // namespace proxy_tunnel_test
  28591. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  28592. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28593. [](SSLClient &cli) {
  28594. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28595. cli.set_basic_auth("origin-user", "origin-pass");
  28596. },
  28597. "Basic");
  28598. }
  28599. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  28600. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28601. [](SSLClient &cli) {
  28602. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28603. cli.set_basic_auth("origin-user", "origin-pass");
  28604. },
  28605. "Basic", {"Authorization"}, true);
  28606. }
  28607. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  28608. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28609. [](SSLClient &cli) {
  28610. cli.set_proxy_bearer_token_auth("proxy-token");
  28611. cli.set_bearer_token_auth("origin-token");
  28612. },
  28613. "Bearer");
  28614. }
  28615. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  28616. proxy_tunnel_test::CredentialsStayWithTheirHop(
  28617. [](SSLClient &cli) {
  28618. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28619. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  28620. {"Cookie", "sid=origin-session"},
  28621. {"X-Api-Key", "origin-key"}});
  28622. },
  28623. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  28624. }
  28625. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  28626. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  28627. // retry; otherwise proxy creds would be sent to the origin.
  28628. std::atomic<int> origin_hits{0};
  28629. std::atomic<bool> origin_saw_proxy_authz{false};
  28630. proxy_tunnel_test::ScopedSSLServer origin;
  28631. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28632. origin_hits++;
  28633. if (req.has_header("Proxy-Authorization")) {
  28634. origin_saw_proxy_authz = true;
  28635. }
  28636. res.status = StatusCode::ProxyAuthenticationRequired_407;
  28637. res.set_header("Proxy-Authenticate",
  28638. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  28639. "algorithm=MD5");
  28640. });
  28641. origin.listen();
  28642. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28643. ASSERT_NE(0, proxy.port());
  28644. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  28645. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  28646. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  28647. // and answer with its own status, making this test flaky.
  28648. SSLClient cli("127.0.0.1", origin.port());
  28649. cli.enable_server_certificate_verification(false);
  28650. cli.set_proxy("127.0.0.1", proxy.port());
  28651. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28652. auto res = cli.Get("/x");
  28653. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28654. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  28655. EXPECT_EQ(1, origin_hits.load());
  28656. EXPECT_FALSE(origin_saw_proxy_authz.load());
  28657. EXPECT_EQ(1, proxy.connect_hits());
  28658. }
  28659. TEST(ProxyTunnelTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  28660. std::string origin_sni;
  28661. std::string origin_host;
  28662. proxy_tunnel_test::ScopedSSLServer origin;
  28663. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  28664. origin_sni = req.sni();
  28665. origin_host = req.get_header_value("Host");
  28666. res.set_content("ok", "text/plain");
  28667. });
  28668. origin.listen();
  28669. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28670. ASSERT_NE(0, proxy.port());
  28671. SSLClient cli("origin.example", origin.port());
  28672. cli.enable_server_certificate_verification(false);
  28673. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28674. cli.set_proxy("127.0.0.1", proxy.port());
  28675. auto res = cli.Get("/x");
  28676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28677. EXPECT_EQ(StatusCode::OK_200, res->status);
  28678. auto port = std::to_string(origin.port());
  28679. auto target = "127.0.0.1:" + port;
  28680. auto connect_req = proxy.connect_request();
  28681. EXPECT_EQ(1, proxy.connect_hits());
  28682. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28683. EXPECT_NE(std::string::npos,
  28684. connect_req.find("\r\nHost: " + target + "\r\n"));
  28685. EXPECT_EQ("origin.example", origin_sni);
  28686. EXPECT_EQ("origin.example:" + port, origin_host);
  28687. }
  28688. TEST(ProxyTunnelTest, DigestRetryConnectTargetFollowsTunnelHostnameAddrMap) {
  28689. proxy_tunnel_test::ScopedSSLServer origin;
  28690. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28691. res.set_content("ok", "text/plain");
  28692. });
  28693. origin.listen();
  28694. proxy_tunnel_test::ScopedConnectProxy proxy(
  28695. origin.port(), [](const std::string &head) -> std::string {
  28696. if (head.find(
  28697. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  28698. std::string::npos) {
  28699. return proxy_tunnel_test::kTunnelEstablished;
  28700. }
  28701. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28702. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  28703. "nonce=\"abc\", algorithm=MD5\r\n"
  28704. "Content-Length: 0\r\n\r\n";
  28705. });
  28706. ASSERT_NE(0, proxy.port());
  28707. SSLClient cli("origin.example", origin.port());
  28708. cli.enable_server_certificate_verification(false);
  28709. cli.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28710. cli.set_proxy("127.0.0.1", proxy.port());
  28711. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  28712. auto res = cli.Get("/x");
  28713. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28714. EXPECT_EQ(StatusCode::OK_200, res->status);
  28715. // The retried CONNECT is the one the proxy saw last.
  28716. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28717. auto connect_req = proxy.connect_request();
  28718. EXPECT_EQ(2, proxy.connect_hits());
  28719. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28720. EXPECT_NE(std::string::npos,
  28721. connect_req.find("\r\nHost: " + target + "\r\n"));
  28722. }
  28723. TEST(ProxyTunnelTest, DirectHostnameAddrMapLeavesConnectTarget) {
  28724. proxy_tunnel_test::ScopedSSLServer origin;
  28725. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28726. res.set_content("ok", "text/plain");
  28727. });
  28728. origin.listen();
  28729. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28730. ASSERT_NE(0, proxy.port());
  28731. SSLClient cli("origin.example", origin.port());
  28732. cli.enable_server_certificate_verification(false);
  28733. cli.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  28734. cli.set_proxy("127.0.0.1", proxy.port());
  28735. auto res = cli.Get("/x");
  28736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28737. EXPECT_EQ(StatusCode::OK_200, res->status);
  28738. auto target = "origin.example:" + std::to_string(origin.port());
  28739. auto connect_req = proxy.connect_request();
  28740. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28741. EXPECT_NE(std::string::npos,
  28742. connect_req.find("\r\nHost: " + target + "\r\n"));
  28743. }
  28744. TEST(ProxyTunnelTest, RedirectKeepsTunnelHostnameAddrMap) {
  28745. proxy_tunnel_test::ScopedSSLServer origin;
  28746. auto port = std::to_string(origin.port());
  28747. origin.svr().Get("/x", [&](const Request &, Response &res) {
  28748. res.set_redirect("https://next.example:" + port + "/y");
  28749. });
  28750. origin.svr().Get("/y", [](const Request &, Response &res) {
  28751. res.set_content("ok", "text/plain");
  28752. });
  28753. origin.listen();
  28754. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28755. ASSERT_NE(0, proxy.port());
  28756. SSLClient cli("origin.example", origin.port());
  28757. cli.enable_server_certificate_verification(false);
  28758. cli.set_tunnel_hostname_addr_map(
  28759. {{"origin.example", "127.0.0.1"}, {"next.example", "127.0.0.1"}});
  28760. cli.set_proxy("127.0.0.1", proxy.port());
  28761. cli.set_follow_location(true);
  28762. auto res = cli.Get("/x");
  28763. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28764. EXPECT_EQ("ok", res->body);
  28765. // The last CONNECT is the redirect client's.
  28766. ASSERT_EQ(2, proxy.connect_hits());
  28767. auto target = "127.0.0.1:" + port;
  28768. auto connect_req = proxy.connect_request();
  28769. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28770. EXPECT_NE(std::string::npos,
  28771. connect_req.find("\r\nHost: " + target + "\r\n"));
  28772. }
  28773. // A failed handshake inside the tunnel must not leave the tunnel for reuse
  28774. TEST(ProxyTunnelTest, FailedHandshakeClosesTunnel) {
  28775. std::atomic<int> origin_hits{0};
  28776. proxy_tunnel_test::ScopedSSLServer origin;
  28777. origin.svr().Get(".*", [&](const Request &, Response &res) {
  28778. origin_hits++;
  28779. res.set_content("ok", "text/plain");
  28780. });
  28781. origin.listen();
  28782. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28783. ASSERT_NE(0, proxy.port());
  28784. SSLClient cli("127.0.0.1", origin.port());
  28785. cli.enable_server_certificate_verification(false);
  28786. cli.set_proxy("127.0.0.1", proxy.port());
  28787. cli.set_keep_alive(true);
  28788. cli.set_session_verifier(
  28789. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  28790. auto res = cli.Get("/x");
  28791. EXPECT_FALSE(res);
  28792. ASSERT_FALSE(cli.is_socket_open());
  28793. res = cli.Get("/x");
  28794. EXPECT_FALSE(res);
  28795. EXPECT_EQ(2, proxy.connect_hits());
  28796. auto handle = cli.open_stream("GET", "/x");
  28797. EXPECT_FALSE(handle.is_valid());
  28798. EXPECT_EQ(3, proxy.connect_hits());
  28799. EXPECT_EQ(0, origin_hits.load());
  28800. }
  28801. #endif
  28802. namespace proxy_tunnel_test {
  28803. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  28804. // anything else gets a 407 with `challenge`.
  28805. ConnectReply require_proxy_auth(const std::string &expected,
  28806. const std::string &challenge) {
  28807. return [=](const std::string &head) -> std::string {
  28808. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  28809. std::string::npos) {
  28810. return kTunnelEstablished;
  28811. }
  28812. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  28813. "Proxy-Authenticate: " +
  28814. challenge + "\r\nContent-Length: 0\r\n\r\n";
  28815. };
  28816. }
  28817. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  28818. // request, then echoes.
  28819. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  28820. ws.send(
  28821. "authorization:" + req.get_header_value("Authorization") +
  28822. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  28823. std::string msg;
  28824. while (ws.read(msg)) {
  28825. ws.send(msg);
  28826. }
  28827. }
  28828. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  28829. class ScopedWebSocketOrigin {
  28830. public:
  28831. ScopedWebSocketOrigin() {
  28832. server_.svr().WebSocket("/ws", report_auth_then_echo);
  28833. server_.listen();
  28834. }
  28835. int port() const { return server_.port(); }
  28836. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  28837. std::string url() const {
  28838. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  28839. }
  28840. private:
  28841. no_proxy_test::ScopedServer server_;
  28842. };
  28843. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  28844. // passed as a constructor header, and checks that each reaches only its hop.
  28845. void WebSocketCredentialsStayWithTheirHop(
  28846. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  28847. const std::string &proxy_authz, const std::string &origin_authz) {
  28848. ScopedWebSocketOrigin origin;
  28849. ScopedConnectProxy proxy(
  28850. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28851. ASSERT_NE(0, proxy.port());
  28852. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  28853. client.set_proxy("127.0.0.1", proxy.port());
  28854. set_proxy_credentials(client);
  28855. auto res = client.connect();
  28856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28857. std::string msg;
  28858. ASSERT_TRUE(client.read(msg));
  28859. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28860. client.close();
  28861. EXPECT_EQ(1, proxy.connect_hits());
  28862. EXPECT_EQ(std::string::npos,
  28863. proxy.connect_request().find("\r\nAuthorization: "))
  28864. << "origin credentials must not be sent to the proxy";
  28865. }
  28866. // Like WebSocketCredentialsStayWithTheirHop(), but with the setters.
  28867. void WebSocketSetterCredentialsStayWithTheirHop(
  28868. const std::function<void(ws::WebSocketClient &)> &set_credentials,
  28869. const std::string &proxy_authz, const std::string &origin_authz) {
  28870. ScopedWebSocketOrigin origin;
  28871. ScopedConnectProxy proxy(
  28872. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  28873. ASSERT_NE(0, proxy.port());
  28874. ws::WebSocketClient client(origin.url());
  28875. client.set_proxy("127.0.0.1", proxy.port());
  28876. set_credentials(client);
  28877. auto res = client.connect();
  28878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28879. std::string msg;
  28880. ASSERT_TRUE(client.read(msg));
  28881. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  28882. client.close();
  28883. EXPECT_EQ(1, proxy.connect_hits());
  28884. EXPECT_EQ(std::string::npos,
  28885. proxy.connect_request().find("\r\nAuthorization: "))
  28886. << "origin credentials must not be sent to the proxy";
  28887. }
  28888. } // namespace proxy_tunnel_test
  28889. namespace {
  28890. // Connects `client` and returns the Authorization header its upgrade
  28891. // request carried, or "<failed>" when the connection could not be opened.
  28892. std::string websocket_authorization(ws::WebSocketClient &client) {
  28893. if (!client.connect()) { return "<failed>"; }
  28894. std::string msg;
  28895. if (!client.read(msg)) { return "<failed>"; }
  28896. client.close();
  28897. auto prefix = std::string("authorization:");
  28898. auto end = msg.find("|proxy-authorization:");
  28899. return msg.substr(prefix.size(), end - prefix.size());
  28900. }
  28901. } // namespace
  28902. TEST(WebSocketClientAuthTest, BasicAuth) {
  28903. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28904. ws::WebSocketClient client(origin.url());
  28905. client.set_basic_auth("user", "pass");
  28906. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28907. websocket_authorization(client));
  28908. }
  28909. TEST(WebSocketClientAuthTest, BasicAuthWithEmptyPasswordIsSent) {
  28910. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28911. ws::WebSocketClient client(origin.url());
  28912. client.set_basic_auth("user", "");
  28913. EXPECT_EQ("Basic " + detail::base64_encode("user:"),
  28914. websocket_authorization(client));
  28915. }
  28916. TEST(WebSocketClientAuthTest, BearerTokenAuth) {
  28917. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28918. ws::WebSocketClient client(origin.url());
  28919. client.set_bearer_token_auth("token123");
  28920. EXPECT_EQ("Bearer token123", websocket_authorization(client));
  28921. }
  28922. TEST(WebSocketClientAuthTest, BasicAuthWinsOverBearerToken) {
  28923. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28924. ws::WebSocketClient client(origin.url());
  28925. client.set_bearer_token_auth("token123");
  28926. client.set_basic_auth("user", "pass");
  28927. EXPECT_EQ("Basic " + detail::base64_encode("user:pass"),
  28928. websocket_authorization(client));
  28929. }
  28930. TEST(WebSocketClientAuthTest, ConstructorHeaderWinsOverSetter) {
  28931. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28932. ws::WebSocketClient client(origin.url(),
  28933. {{"Authorization", "Bearer from-header"}});
  28934. client.set_bearer_token_auth("from-setter");
  28935. client.set_basic_auth("user", "pass");
  28936. EXPECT_EQ("Bearer from-header", websocket_authorization(client));
  28937. }
  28938. TEST(WebSocketClientAuthTest, CredentialsApplyOnReconnect) {
  28939. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28940. ws::WebSocketClient client(origin.url());
  28941. EXPECT_EQ("", websocket_authorization(client));
  28942. client.set_bearer_token_auth("first");
  28943. EXPECT_EQ("Bearer first", websocket_authorization(client));
  28944. client.set_bearer_token_auth("second");
  28945. EXPECT_EQ("Bearer second", websocket_authorization(client));
  28946. client.set_bearer_token_auth("");
  28947. EXPECT_EQ("", websocket_authorization(client));
  28948. }
  28949. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  28950. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  28951. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  28952. ASSERT_NE(0, proxy.port());
  28953. ws::WebSocketClient client(origin.url());
  28954. client.set_proxy("127.0.0.1", proxy.port());
  28955. auto res = client.connect();
  28956. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  28957. std::string msg;
  28958. ASSERT_TRUE(client.read(msg));
  28959. ASSERT_TRUE(client.send("hello"));
  28960. ASSERT_TRUE(client.read(msg));
  28961. EXPECT_EQ("hello", msg);
  28962. client.close();
  28963. EXPECT_EQ(1, proxy.connect_hits());
  28964. auto target = "127.0.0.1:" + std::to_string(origin.port());
  28965. auto connect_req = proxy.connect_request();
  28966. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  28967. EXPECT_NE(std::string::npos,
  28968. connect_req.find("\r\nHost: " + target + "\r\n"));
  28969. }
  28970. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  28971. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28972. [](ws::WebSocketClient &cli) {
  28973. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28974. },
  28975. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28976. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28977. }
  28978. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  28979. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  28980. [](ws::WebSocketClient &cli) {
  28981. cli.set_proxy_bearer_token_auth("proxy-token");
  28982. },
  28983. "Bearer proxy-token", "Bearer origin-token");
  28984. }
  28985. TEST(WebSocketProxyTest, BasicAuthSetterStaysWithItsHop) {
  28986. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28987. [](ws::WebSocketClient &cli) {
  28988. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  28989. cli.set_basic_auth("origin-user", "origin-pass");
  28990. },
  28991. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  28992. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  28993. }
  28994. TEST(WebSocketProxyTest, BearerTokenAuthSetterStaysWithItsHop) {
  28995. proxy_tunnel_test::WebSocketSetterCredentialsStayWithTheirHop(
  28996. [](ws::WebSocketClient &cli) {
  28997. cli.set_proxy_bearer_token_auth("proxy-token");
  28998. cli.set_bearer_token_auth("origin-token");
  28999. },
  29000. "Bearer proxy-token", "Bearer origin-token");
  29001. }
  29002. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  29003. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29004. proxy_tunnel_test::ScopedConnectProxy proxy(
  29005. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29006. "Basic " + detail::base64_encode("proxy-user:"),
  29007. "Basic realm=\"proxy\""));
  29008. ASSERT_NE(0, proxy.port());
  29009. ws::WebSocketClient client(origin.url());
  29010. client.set_proxy("127.0.0.1", proxy.port());
  29011. client.set_proxy_basic_auth("proxy-user", "");
  29012. auto res = client.connect();
  29013. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29014. client.close();
  29015. EXPECT_EQ(1, proxy.connect_hits());
  29016. }
  29017. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  29018. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29019. proxy_tunnel_test::ScopedConnectProxy proxy(
  29020. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29021. "Bearer proxy-token", "Basic realm=\"proxy\""));
  29022. ASSERT_NE(0, proxy.port());
  29023. ws::WebSocketClient client(origin.url());
  29024. client.set_proxy("127.0.0.1", proxy.port());
  29025. auto res = client.connect();
  29026. EXPECT_FALSE(res);
  29027. EXPECT_EQ(Error::ProxyConnection, res.error());
  29028. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  29029. EXPECT_EQ("Basic realm=\"proxy\"",
  29030. res.get_header_value("Proxy-Authenticate"));
  29031. EXPECT_FALSE(client.is_open());
  29032. }
  29033. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  29034. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29035. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29036. ASSERT_NE(0, proxy.port());
  29037. ws::WebSocketClient client(origin.url());
  29038. client.set_proxy("127.0.0.1", proxy.port());
  29039. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  29040. client.set_no_proxy({"127.0.0.1"});
  29041. auto res = client.connect();
  29042. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29043. std::string msg;
  29044. ASSERT_TRUE(client.read(msg));
  29045. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29046. << "proxy credentials must not reach a bypassed origin";
  29047. client.close();
  29048. EXPECT_EQ(0, proxy.connect_hits());
  29049. }
  29050. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  29051. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29052. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29053. ASSERT_NE(0, proxy.port());
  29054. ws::WebSocketClient client(origin.url());
  29055. client.set_proxy("127.0.0.1", proxy.port());
  29056. ASSERT_TRUE(client.connect());
  29057. ASSERT_TRUE(client.connect());
  29058. client.close();
  29059. EXPECT_EQ(2, proxy.connect_hits());
  29060. }
  29061. TEST(WebSocketProxyTest, ConnectTargetFollowsTunnelHostnameAddrMap) {
  29062. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29063. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29064. ASSERT_NE(0, proxy.port());
  29065. auto port = std::to_string(origin.port());
  29066. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29067. client.set_tunnel_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29068. client.set_proxy("127.0.0.1", proxy.port());
  29069. auto res = client.connect();
  29070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29071. std::string msg;
  29072. ASSERT_TRUE(client.read(msg));
  29073. client.close();
  29074. EXPECT_EQ(1, proxy.connect_hits());
  29075. auto target = "127.0.0.1:" + port;
  29076. auto connect_req = proxy.connect_request();
  29077. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29078. EXPECT_NE(std::string::npos,
  29079. connect_req.find("\r\nHost: " + target + "\r\n"));
  29080. }
  29081. TEST(WebSocketProxyTest, DirectHostnameAddrMapLeavesConnectTarget) {
  29082. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29083. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  29084. ASSERT_NE(0, proxy.port());
  29085. auto port = std::to_string(origin.port());
  29086. ws::WebSocketClient client("ws://origin.example:" + port + "/ws");
  29087. client.set_direct_hostname_addr_map({{"origin.example", "127.0.0.1"}});
  29088. client.set_proxy("127.0.0.1", proxy.port());
  29089. auto res = client.connect();
  29090. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29091. client.close();
  29092. auto target = "origin.example:" + port;
  29093. auto connect_req = proxy.connect_request();
  29094. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  29095. EXPECT_NE(std::string::npos,
  29096. connect_req.find("\r\nHost: " + target + "\r\n"));
  29097. }
  29098. #ifdef CPPHTTPLIB_SSL_ENABLED
  29099. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  29100. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  29101. proxy_tunnel_test::ScopedConnectProxy proxy(
  29102. origin.port(), [](const std::string &head) -> std::string {
  29103. if (head.find(
  29104. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  29105. std::string::npos) {
  29106. return proxy_tunnel_test::kTunnelEstablished;
  29107. }
  29108. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  29109. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  29110. "nonce=\"abc\", algorithm=MD5\r\n"
  29111. "Content-Length: 0\r\n\r\n";
  29112. });
  29113. ASSERT_NE(0, proxy.port());
  29114. ws::WebSocketClient client(origin.url());
  29115. client.set_proxy("127.0.0.1", proxy.port());
  29116. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  29117. auto res = client.connect();
  29118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29119. std::string msg;
  29120. ASSERT_TRUE(client.read(msg));
  29121. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  29122. client.close();
  29123. EXPECT_EQ(2, proxy.connect_hits());
  29124. }
  29125. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  29126. proxy_tunnel_test::ScopedSSLServer origin;
  29127. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  29128. origin.listen();
  29129. proxy_tunnel_test::ScopedConnectProxy proxy(
  29130. origin.port(), proxy_tunnel_test::require_proxy_auth(
  29131. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  29132. ASSERT_NE(0, proxy.port());
  29133. ws::WebSocketClient client(
  29134. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  29135. client.enable_server_certificate_verification(false);
  29136. client.set_proxy("127.0.0.1", proxy.port());
  29137. client.set_proxy_bearer_token_auth("proxy-token");
  29138. auto res = client.connect();
  29139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  29140. std::string msg;
  29141. ASSERT_TRUE(client.read(msg));
  29142. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  29143. << "Proxy-Authorization must not be sent inside the tunnel";
  29144. client.close();
  29145. EXPECT_EQ(1, proxy.connect_hits());
  29146. }
  29147. #endif
  29148. // ---------------------------------------------------------------------------
  29149. // Poller
  29150. // ---------------------------------------------------------------------------
  29151. namespace poller_test {
  29152. struct PollerBackend {
  29153. const char *name;
  29154. std::unique_ptr<detail::Poller> (*create)();
  29155. };
  29156. void PrintTo(const PollerBackend &backend, std::ostream *os) {
  29157. *os << backend.name;
  29158. }
  29159. // Every backend runs the same contract tests. A new one is added here only.
  29160. std::vector<PollerBackend> poller_backends() {
  29161. return {
  29162. {"poll", &detail::PollPoller::create},
  29163. #ifdef __linux__
  29164. {"epoll", &detail::EpollPoller::create},
  29165. #endif
  29166. #ifdef CPPHTTPLIB_KQUEUE_POLLER
  29167. {"kqueue", &detail::KqueuePoller::create},
  29168. #endif
  29169. };
  29170. }
  29171. // A descriptor whose readability the test controls.
  29172. struct TestSocketPair {
  29173. socket_t fd[2] = {INVALID_SOCKET, INVALID_SOCKET};
  29174. TestSocketPair() { detail::create_socket_pair(fd); }
  29175. ~TestSocketPair() {
  29176. for (auto s : fd) {
  29177. if (s != INVALID_SOCKET) { detail::close_socket(s); }
  29178. }
  29179. }
  29180. bool ok() const { return fd[0] != INVALID_SOCKET; }
  29181. socket_t reader() const { return fd[0]; }
  29182. void make_readable() {
  29183. const char c = 1;
  29184. detail::send_socket(fd[1], &c, 1, 0);
  29185. }
  29186. void close_writer() {
  29187. detail::close_socket(fd[1]);
  29188. fd[1] = INVALID_SOCKET;
  29189. }
  29190. };
  29191. using Tokens = std::vector<detail::Poller::Token>;
  29192. class PollerTest : public ::testing::TestWithParam<PollerBackend> {
  29193. protected:
  29194. void SetUp() override {
  29195. poller_ = GetParam().create();
  29196. ASSERT_TRUE(poller_ != nullptr);
  29197. }
  29198. Tokens wait_for(int timeout_ms) {
  29199. Tokens ready;
  29200. poller_->wait(timeout_ms, ready);
  29201. std::sort(ready.begin(), ready.end());
  29202. return ready;
  29203. }
  29204. std::unique_ptr<detail::Poller> poller_;
  29205. };
  29206. } // namespace poller_test
  29207. using poller_test::PollerTest;
  29208. using poller_test::TestSocketPair;
  29209. using poller_test::Tokens;
  29210. INSTANTIATE_TEST_SUITE_P(
  29211. Backends, PollerTest, ::testing::ValuesIn(poller_test::poller_backends()),
  29212. [](const ::testing::TestParamInfo<poller_test::PollerBackend> &p) {
  29213. return std::string(p.param.name);
  29214. });
  29215. TEST_P(PollerTest, DeliversOnceThenStaysDisarmedUntilRearmed) {
  29216. TestSocketPair sp;
  29217. ASSERT_TRUE(sp.ok());
  29218. ASSERT_TRUE(poller_->arm(sp.reader(), 7));
  29219. EXPECT_EQ(Tokens{}, wait_for(0));
  29220. sp.make_readable();
  29221. EXPECT_EQ(Tokens{7}, wait_for(1000));
  29222. EXPECT_EQ(Tokens{}, wait_for(0)); // still readable, but disarmed
  29223. ASSERT_TRUE(poller_->arm(sp.reader(), 8));
  29224. EXPECT_EQ(Tokens{8}, wait_for(1000));
  29225. }
  29226. TEST_P(PollerTest, DisarmedDescriptorIsNotDelivered) {
  29227. TestSocketPair sp;
  29228. ASSERT_TRUE(sp.ok());
  29229. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29230. poller_->disarm(sp.reader());
  29231. poller_->disarm(sp.reader()); // disarming twice is harmless
  29232. sp.make_readable();
  29233. EXPECT_EQ(Tokens{}, wait_for(0));
  29234. }
  29235. TEST_P(PollerTest, WaitHonoursItsTimeout) {
  29236. TestSocketPair sp;
  29237. ASSERT_TRUE(sp.ok());
  29238. ASSERT_TRUE(poller_->arm(sp.reader(), 1));
  29239. auto start = std::chrono::steady_clock::now();
  29240. EXPECT_EQ(Tokens{}, wait_for(30));
  29241. auto elapsed = std::chrono::steady_clock::now() - start;
  29242. EXPECT_GE(elapsed, std::chrono::milliseconds(25));
  29243. EXPECT_LT(elapsed, std::chrono::seconds(1));
  29244. }
  29245. TEST_P(PollerTest, OnlyTheReadyDescriptorsAreDelivered) {
  29246. std::vector<std::unique_ptr<TestSocketPair>> sps;
  29247. for (detail::Poller::Token i = 0; i < 8; i++) {
  29248. sps.emplace_back(new TestSocketPair());
  29249. ASSERT_TRUE(sps.back()->ok());
  29250. ASSERT_TRUE(poller_->arm(sps.back()->reader(), i));
  29251. }
  29252. sps[0]->make_readable();
  29253. sps[3]->make_readable();
  29254. sps[7]->make_readable();
  29255. EXPECT_EQ((Tokens{0, 3, 7}), wait_for(1000));
  29256. // The others are still armed, the delivered ones are not.
  29257. sps[1]->make_readable();
  29258. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29259. EXPECT_EQ(Tokens{}, wait_for(0));
  29260. }
  29261. TEST_P(PollerTest, StaysConsistentAfterOtherDescriptorsWereDelivered) {
  29262. TestSocketPair s0, s1, s2;
  29263. ASSERT_TRUE(s0.ok() && s1.ok() && s2.ok());
  29264. ASSERT_TRUE(poller_->arm(s0.reader(), 0));
  29265. ASSERT_TRUE(poller_->arm(s1.reader(), 1));
  29266. ASSERT_TRUE(poller_->arm(s2.reader(), 2));
  29267. // A delivery may move another entry inside the poller.
  29268. s0.make_readable();
  29269. EXPECT_EQ(Tokens{0}, wait_for(1000));
  29270. // The entries left must still be found by descriptor.
  29271. poller_->disarm(s2.reader());
  29272. s1.make_readable();
  29273. s2.make_readable();
  29274. EXPECT_EQ(Tokens{1}, wait_for(1000));
  29275. }
  29276. TEST_P(PollerTest, PeerHangUpCountsAsReadable) {
  29277. TestSocketPair sp;
  29278. ASSERT_TRUE(sp.ok());
  29279. ASSERT_TRUE(poller_->arm(sp.reader(), 5));
  29280. sp.close_writer();
  29281. EXPECT_EQ(Tokens{5}, wait_for(1000));
  29282. char c;
  29283. EXPECT_EQ(0, detail::read_socket(sp.reader(), &c, 1, 0)); // EOF
  29284. }
  29285. TEST_P(PollerTest, WakeEndsABlockedWait) {
  29286. std::thread waker([&] {
  29287. std::this_thread::sleep_for(std::chrono::milliseconds(20));
  29288. poller_->wake();
  29289. });
  29290. Tokens ready;
  29291. auto start = std::chrono::steady_clock::now();
  29292. EXPECT_TRUE(poller_->wait(5000, ready)); // only the waker ends this early
  29293. waker.join();
  29294. EXPECT_TRUE(ready.empty());
  29295. EXPECT_LT(std::chrono::steady_clock::now() - start, std::chrono::seconds(1));
  29296. }
  29297. TEST_P(PollerTest, WakeBeforeWaitIsNotLost) {
  29298. poller_->wake(); // e.g. stop() running before the reactor reaches wait()
  29299. Tokens ready;
  29300. EXPECT_TRUE(poller_->wait(1000, ready));
  29301. }
  29302. TEST_P(PollerTest, WakesCoalesceAndAreConsumed) {
  29303. for (int i = 0; i < 1000; i++) {
  29304. poller_->wake();
  29305. }
  29306. Tokens ready;
  29307. EXPECT_TRUE(poller_->wait(0, ready));
  29308. EXPECT_FALSE(poller_->wait(0, ready));
  29309. poller_->wake();
  29310. EXPECT_TRUE(poller_->wait(0, ready));
  29311. }
  29312. TEST_P(PollerTest, ConcurrentWakesAreNeverLost) {
  29313. // Two threads publish changes and wake() after each, as a reactor's workers
  29314. // do. Every change must be seen without a wait() timing out. A lost wake()
  29315. // needs an unlucky interleaving, hence the rounds.
  29316. for (int round = 0; round < 5; round++) {
  29317. SCOPED_TRACE(round);
  29318. const int per_thread = 20000;
  29319. std::atomic<int> posted{0};
  29320. auto post = [&] {
  29321. for (int i = 0; i < per_thread; i++) {
  29322. posted++;
  29323. poller_->wake();
  29324. }
  29325. };
  29326. std::thread t1(post), t2(post);
  29327. auto lost = false;
  29328. Tokens ready;
  29329. for (auto seen = 0; seen < 2 * per_thread; seen = posted) {
  29330. if (!poller_->wait(1000, ready)) {
  29331. lost = true;
  29332. break;
  29333. }
  29334. }
  29335. t1.join();
  29336. t2.join();
  29337. ASSERT_FALSE(lost);
  29338. }
  29339. }
  29340. TEST(PollerFactoryTest, MakePollerWorks) {
  29341. auto poller = detail::make_poller();
  29342. ASSERT_TRUE(poller != nullptr);
  29343. poller->wake();
  29344. std::vector<detail::Poller::Token> ready;
  29345. EXPECT_TRUE(poller->wait(1000, ready));
  29346. }
  29347. // ---------------------------------------------------------------------------
  29348. // Keep-alive parking
  29349. // ---------------------------------------------------------------------------
  29350. namespace parking_test {
  29351. // Runs `svr` on a free port and stops it when it goes away. `before_listen`
  29352. // runs once the port is bound and listening, before the server accepts.
  29353. struct RunningServer {
  29354. explicit RunningServer(
  29355. Server &svr, const std::function<void(int)> &before_listen = nullptr)
  29356. : svr_(svr) {
  29357. port = svr_.bind_to_any_port("127.0.0.1");
  29358. if (before_listen) { before_listen(port); }
  29359. thread = std::thread([this] { svr_.listen_after_bind(); });
  29360. svr_.wait_until_ready();
  29361. }
  29362. ~RunningServer() {
  29363. svr_.stop();
  29364. if (thread.joinable()) { thread.join(); }
  29365. }
  29366. Server &svr_;
  29367. int port = 0;
  29368. std::thread thread;
  29369. };
  29370. struct Sockets {
  29371. std::vector<socket_t> socks;
  29372. ~Sockets() {
  29373. for (auto s : socks) {
  29374. detail::close_socket(s);
  29375. }
  29376. }
  29377. socket_t connect(int port) {
  29378. auto error = Error::Success;
  29379. auto s = detail::create_client_socket("127.0.0.1", "", port, AF_UNSPEC,
  29380. false, false, nullptr, 2, 0, 2, 0, 2,
  29381. 0, std::string(), error);
  29382. if (s != INVALID_SOCKET) { socks.push_back(s); }
  29383. return s;
  29384. }
  29385. };
  29386. std::chrono::steady_clock::time_point in_ms(int ms) {
  29387. return std::chrono::steady_clock::now() + std::chrono::milliseconds(ms);
  29388. }
  29389. bool readable_by(socket_t sock,
  29390. std::chrono::steady_clock::time_point deadline) {
  29391. auto left = std::chrono::duration_cast<std::chrono::microseconds>(
  29392. deadline - std::chrono::steady_clock::now())
  29393. .count();
  29394. return left > 0 && detail::select_read(sock, 0, left) > 0;
  29395. }
  29396. bool send_get(socket_t sock, const std::string &path = "/") {
  29397. auto req = "GET " + path + " HTTP/1.1\r\nHost: localhost\r\n\r\n";
  29398. return detail::send_socket(sock, req.data(), req.size(), 0) ==
  29399. static_cast<ssize_t>(req.size());
  29400. }
  29401. // Reads one response whose body is "ok".
  29402. bool receives_ok(socket_t sock, int timeout_ms) {
  29403. auto deadline = in_ms(timeout_ms);
  29404. std::string buf;
  29405. while (readable_by(sock, deadline)) {
  29406. char tmp[1024];
  29407. auto n = detail::read_socket(sock, tmp, sizeof(tmp), 0);
  29408. if (n <= 0) { return false; }
  29409. buf.append(tmp, static_cast<size_t>(n));
  29410. auto end = buf.find("\r\n\r\n");
  29411. if (end != std::string::npos && buf.size() >= end + 4 + 2) {
  29412. return buf.compare(0, 12, "HTTP/1.1 200") == 0 &&
  29413. buf.compare(end + 4, 2, "ok") == 0;
  29414. }
  29415. }
  29416. return false;
  29417. }
  29418. bool get_ok(socket_t sock, int timeout_ms) {
  29419. return send_get(sock) && receives_ok(sock, timeout_ms);
  29420. }
  29421. // Whether the server closes `sock` by `deadline`.
  29422. bool sees_eof(socket_t sock, std::chrono::steady_clock::time_point deadline) {
  29423. char c;
  29424. return readable_by(sock, deadline) &&
  29425. detail::read_socket(sock, &c, 1, 0) <= 0;
  29426. }
  29427. // Whether the server closes `sock` without answering a request.
  29428. bool get_refused(socket_t sock, int timeout_ms) {
  29429. return send_get(sock) && sees_eof(sock, in_ms(timeout_ms));
  29430. }
  29431. bool wait_until(const std::function<bool()> &cond, int timeout_ms) {
  29432. auto deadline = in_ms(timeout_ms);
  29433. while (!cond()) {
  29434. if (std::chrono::steady_clock::now() > deadline) { return false; }
  29435. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  29436. }
  29437. return true;
  29438. }
  29439. void serve_ok(Server &svr, std::function<TaskQueue *(void)> new_task_queue) {
  29440. svr.new_task_queue = std::move(new_task_queue);
  29441. svr.set_keep_alive_parking(true);
  29442. svr.Get("/", [](const Request &, Response &res) {
  29443. res.set_content("ok", "text/plain");
  29444. });
  29445. }
  29446. std::function<TaskQueue *(void)> threads(size_t n) {
  29447. return [n] { return new ThreadPool(n); };
  29448. }
  29449. // Counts what the event loop managed to queue, so that a test can wait for it.
  29450. class CountingTaskQueue final : public TaskQueue {
  29451. public:
  29452. CountingTaskQueue(size_t threads, size_t max_queued, std::atomic<int> &ok,
  29453. std::atomic<int> &full)
  29454. : pool_(threads, threads, max_queued), ok_(ok), full_(full) {}
  29455. bool enqueue(std::function<void()> fn) override {
  29456. auto queued = pool_.enqueue([this, fn]() {
  29457. fn();
  29458. // Holds the worker back from taking the next job.
  29459. std::this_thread::sleep_for(std::chrono::milliseconds(pause_after_ms));
  29460. });
  29461. (queued ? ok_ : full_)++;
  29462. return queued;
  29463. }
  29464. void shutdown() override { pool_.shutdown(); }
  29465. std::atomic<int> pause_after_ms{0};
  29466. private:
  29467. ThreadPool pool_;
  29468. std::atomic<int> &ok_;
  29469. std::atomic<int> &full_;
  29470. };
  29471. // Holds handlers until it opens, or for 3 seconds at most.
  29472. class Gate {
  29473. public:
  29474. void wait() {
  29475. std::unique_lock<std::mutex> lock(m_);
  29476. entered_++;
  29477. cv_.notify_all();
  29478. cv_.wait_for(lock, std::chrono::seconds(3), [&] { return open_; });
  29479. }
  29480. void open() {
  29481. std::lock_guard<std::mutex> guard(m_);
  29482. open_ = true;
  29483. cv_.notify_all();
  29484. }
  29485. int entered() {
  29486. std::lock_guard<std::mutex> guard(m_);
  29487. return entered_;
  29488. }
  29489. private:
  29490. std::mutex m_;
  29491. std::condition_variable cv_;
  29492. bool open_ = false;
  29493. int entered_ = 0;
  29494. };
  29495. } // namespace parking_test
  29496. TEST(KeepAliveParkingTest, IdleConnectionsDoNotHoldTheWorkers) {
  29497. using namespace parking_test;
  29498. Server svr;
  29499. serve_ok(svr, threads(1));
  29500. RunningServer running(svr);
  29501. Sockets socks;
  29502. // One kept-alive connection that has been served, and many that have not
  29503. // sent anything yet. None of them may keep the only worker.
  29504. auto served = socks.connect(running.port);
  29505. ASSERT_TRUE(get_ok(served, 2000));
  29506. for (int i = 0; i < 49; i++) {
  29507. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29508. }
  29509. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29510. EXPECT_TRUE(get_ok(served, 1000));
  29511. }
  29512. TEST(KeepAliveParkingTest, IdleConnectionsTimeOutTogether) {
  29513. using namespace parking_test;
  29514. Server svr;
  29515. serve_ok(svr, threads(1));
  29516. svr.set_keep_alive_timeout(1);
  29517. RunningServer running(svr);
  29518. Sockets socks;
  29519. for (int i = 0; i < 3; i++) {
  29520. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29521. }
  29522. // One worker waiting on each in turn would take about 3 seconds.
  29523. auto deadline = in_ms(2000);
  29524. for (auto s : socks.socks) {
  29525. EXPECT_TRUE(sees_eof(s, deadline));
  29526. }
  29527. }
  29528. TEST(KeepAliveParkingTest, EstablishedConnectionWaitsForAFullQueue) {
  29529. using namespace parking_test;
  29530. std::atomic<int> queued{0}, full{0};
  29531. Server svr;
  29532. // One worker and room for one queued task.
  29533. serve_ok(svr, [&] { return new CountingTaskQueue(1, 1, queued, full); });
  29534. Gate gate;
  29535. svr.Get("/block", [&](const Request &, Response &res) {
  29536. gate.wait();
  29537. res.set_content("ok", "text/plain");
  29538. });
  29539. RunningServer running(svr);
  29540. // Before the server stops, so that a failed run does not wait for the
  29541. // handler's timeout.
  29542. auto open_gate = detail::scope_exit([&] { gate.open(); });
  29543. Sockets socks;
  29544. auto a = socks.connect(running.port);
  29545. ASSERT_TRUE(get_ok(a, 2000));
  29546. // B keeps the only worker busy.
  29547. auto b = socks.connect(running.port);
  29548. ASSERT_TRUE(send_get(b, "/block"));
  29549. ASSERT_TRUE(wait_until([&] { return gate.entered() == 1; }, 2000));
  29550. // A new connection C fills the queue.
  29551. auto c = socks.connect(running.port);
  29552. ASSERT_TRUE(send_get(c));
  29553. ASSERT_TRUE(wait_until([&] { return queued == 3; }, 2000));
  29554. // A's next request finds the queue full, but A has been served before, so it
  29555. // waits instead of being cut off.
  29556. ASSERT_TRUE(send_get(a));
  29557. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29558. gate.open();
  29559. EXPECT_TRUE(receives_ok(b, 2000));
  29560. EXPECT_TRUE(receives_ok(c, 2000));
  29561. EXPECT_TRUE(receives_ok(a, 2000));
  29562. }
  29563. TEST(KeepAliveParkingTest, BacklogIsRetriedOnceTheQueueHasRoom) {
  29564. using namespace parking_test;
  29565. std::atomic<int> queued{0}, full{0};
  29566. CountingTaskQueue *queue = nullptr;
  29567. Server svr;
  29568. // Two workers and room for one queued task.
  29569. serve_ok(svr,
  29570. [&] { return queue = new CountingTaskQueue(2, 1, queued, full); });
  29571. Gate first, second;
  29572. svr.Get("/first", [&](const Request &, Response &res) {
  29573. first.wait();
  29574. res.set_content("ok", "text/plain");
  29575. });
  29576. svr.Get("/second", [&](const Request &, Response &res) {
  29577. second.wait();
  29578. res.set_content("ok", "text/plain");
  29579. });
  29580. RunningServer running(svr);
  29581. auto open_gates = detail::scope_exit([&] {
  29582. first.open();
  29583. second.open();
  29584. });
  29585. Sockets socks;
  29586. auto a = socks.connect(running.port);
  29587. ASSERT_TRUE(get_ok(a, 2000));
  29588. // B and D take both workers, and C fills the queue. One at a time: the
  29589. // queue has room for one job only until a worker takes it.
  29590. ASSERT_TRUE(send_get(socks.connect(running.port), "/first"));
  29591. ASSERT_TRUE(wait_until([&] { return first.entered() == 1; }, 2000));
  29592. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29593. ASSERT_TRUE(wait_until([&] { return second.entered() == 1; }, 2000));
  29594. ASSERT_TRUE(send_get(socks.connect(running.port), "/second"));
  29595. ASSERT_TRUE(wait_until([&] { return queued == 4; }, 2000));
  29596. // A's next request waits in the backlog.
  29597. ASSERT_TRUE(send_get(a));
  29598. ASSERT_TRUE(wait_until([&] { return full >= 1; }, 2000));
  29599. // B's worker finishes, then takes C off the queue only later, which makes
  29600. // room for A.
  29601. queue->pause_after_ms = 200;
  29602. first.open();
  29603. EXPECT_TRUE(wait_until([&] { return queued == 5; }, 1000));
  29604. queue->pause_after_ms = 0;
  29605. second.open();
  29606. EXPECT_TRUE(receives_ok(a, 2000));
  29607. }
  29608. TEST(KeepAliveParkingTest, ZeroKeepAliveTimeoutServesTheFirstRequest) {
  29609. using namespace parking_test;
  29610. Server svr;
  29611. serve_ok(svr, threads(1));
  29612. svr.set_keep_alive_timeout(0);
  29613. // The request is on the socket before the server accepts the connection,
  29614. // so it does not race the 10 ms floor. Without the floor the connection is
  29615. // closed unread.
  29616. Sockets socks;
  29617. auto sock = INVALID_SOCKET;
  29618. RunningServer running(svr, [&](int port) {
  29619. sock = socks.connect(port);
  29620. send_get(sock);
  29621. });
  29622. EXPECT_TRUE(receives_ok(sock, 1000));
  29623. }
  29624. TEST(KeepAliveParkingTest, StopClosesParkedConnectionsPromptly) {
  29625. using namespace parking_test;
  29626. for (int round = 0; round < 5; round++) {
  29627. SCOPED_TRACE(round);
  29628. Server svr;
  29629. serve_ok(svr, threads(2));
  29630. RunningServer running(svr);
  29631. Sockets socks;
  29632. for (int i = 0; i < 20; i++) {
  29633. ASSERT_TRUE(get_ok(socks.connect(running.port), 1000));
  29634. }
  29635. auto start = std::chrono::steady_clock::now();
  29636. svr.stop();
  29637. running.thread.join();
  29638. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29639. std::chrono::milliseconds(500));
  29640. auto deadline = in_ms(1000);
  29641. for (auto s : socks.socks) {
  29642. EXPECT_TRUE(sees_eof(s, deadline));
  29643. }
  29644. }
  29645. }
  29646. #ifdef CPPHTTPLIB_SSL_ENABLED
  29647. namespace parking_test {
  29648. // Completes a TLS handshake on `sock` and sends nothing more, like a browser
  29649. // that has opened a connection ahead of time. Freeing the session sends no
  29650. // close_notify, so the connection stays quiet.
  29651. bool handshake_only(socket_t sock) {
  29652. auto ctx = tls::create_client_context();
  29653. tls::set_verify_client(ctx, false);
  29654. auto session = tls::create_session(ctx, sock);
  29655. auto se = detail::scope_exit([&] {
  29656. tls::free_session(session);
  29657. tls::free_context(ctx);
  29658. });
  29659. tls::TlsError err;
  29660. return session &&
  29661. tls::connect_nonblocking(session, sock, 2, 0, &err, nullptr);
  29662. }
  29663. Client tls_client(int port) {
  29664. Client cli("https://127.0.0.1:" + std::to_string(port));
  29665. cli.enable_server_certificate_verification(false);
  29666. cli.set_keep_alive(true);
  29667. cli.set_connection_timeout(1);
  29668. cli.set_read_timeout(1);
  29669. return cli;
  29670. }
  29671. bool tls_get_ok(Client &cli) {
  29672. auto res = cli.Get("/");
  29673. return res && res->body == "ok";
  29674. }
  29675. } // namespace parking_test
  29676. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  29677. TEST(KeepAliveParkingTest, SslFreeBuffersOnlyWhereTheCveIsFixed) {
  29678. struct {
  29679. unsigned long version;
  29680. bool safe;
  29681. } cases[] = {
  29682. {0x30000020UL, false}, {0x300000d0UL, false}, {0x300000e0UL, true},
  29683. {0x300000f0UL, true}, {0x30100050UL, false}, {0x30100060UL, true},
  29684. {0x30200010UL, false}, {0x30200020UL, true}, {0x30300000UL, false},
  29685. {0x30300010UL, true}, {0x30400000UL, true}, {0x40000000UL, true},
  29686. };
  29687. for (const auto &c : cases) {
  29688. EXPECT_EQ(c.safe, detail::ssl_free_buffers_is_safe(c.version))
  29689. << std::hex << c.version;
  29690. }
  29691. }
  29692. #endif
  29693. TEST(KeepAliveParkingTest, IdleTlsConnectionsDoNotHoldTheWorkers) {
  29694. using namespace parking_test;
  29695. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29696. ASSERT_TRUE(svr.is_valid());
  29697. serve_ok(svr, threads(1));
  29698. svr.set_read_timeout(1); // so that a failing run does not take long
  29699. RunningServer running(svr);
  29700. Sockets socks;
  29701. // One served connection, some that have not started their handshake, and
  29702. // one that has finished it and gone quiet. None may keep the only worker.
  29703. auto served = tls_client(running.port);
  29704. ASSERT_TRUE(tls_get_ok(served));
  29705. for (int i = 0; i < 10; i++) {
  29706. ASSERT_NE(INVALID_SOCKET, socks.connect(running.port));
  29707. }
  29708. EXPECT_TRUE(handshake_only(socks.connect(running.port)));
  29709. auto other = tls_client(running.port);
  29710. EXPECT_TRUE(tls_get_ok(other));
  29711. EXPECT_TRUE(tls_get_ok(served));
  29712. }
  29713. TEST(KeepAliveParkingTest, FailedTlsHandshakeClosesTheConnection) {
  29714. using namespace parking_test;
  29715. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29716. ASSERT_TRUE(svr.is_valid());
  29717. serve_ok(svr, threads(1));
  29718. RunningServer running(svr);
  29719. Sockets socks;
  29720. auto plain = socks.connect(running.port);
  29721. ASSERT_TRUE(send_get(plain));
  29722. EXPECT_TRUE(sees_eof(plain, in_ms(1000)));
  29723. EXPECT_NE(0, svr.ssl_last_error());
  29724. }
  29725. TEST(KeepAliveParkingTest, StopClosesParkedTlsConnections) {
  29726. using namespace parking_test;
  29727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29728. ASSERT_TRUE(svr.is_valid());
  29729. serve_ok(svr, threads(2));
  29730. RunningServer running(svr);
  29731. std::vector<Client> clients;
  29732. for (int i = 0; i < 5; i++) {
  29733. clients.push_back(tls_client(running.port));
  29734. ASSERT_TRUE(tls_get_ok(clients.back()));
  29735. }
  29736. auto start = std::chrono::steady_clock::now();
  29737. svr.stop();
  29738. running.thread.join();
  29739. EXPECT_LT(std::chrono::steady_clock::now() - start,
  29740. std::chrono::milliseconds(500));
  29741. }
  29742. #endif
  29743. TEST(AcceptHandlerTest, RefusedConnectionIsClosedUnread) {
  29744. using namespace parking_test;
  29745. for (auto parking : {false, true}) {
  29746. SCOPED_TRACE(parking);
  29747. Server svr;
  29748. serve_ok(svr, threads(2));
  29749. svr.set_keep_alive_parking(parking);
  29750. std::atomic<int> served{0};
  29751. svr.set_pre_routing_handler([&](const Request &, Response &) {
  29752. served++;
  29753. return Server::HandlerResponse::Unhandled;
  29754. });
  29755. std::atomic<bool> allow{false};
  29756. std::atomic<bool> peer_seen{false};
  29757. svr.set_accept_handler([&](socket_t sock) {
  29758. sockaddr_in addr{};
  29759. socklen_t len = sizeof(addr);
  29760. peer_seen =
  29761. getpeername(sock, reinterpret_cast<sockaddr *>(&addr), &len) == 0 &&
  29762. addr.sin_family == AF_INET &&
  29763. ntohl(addr.sin_addr.s_addr) == INADDR_LOOPBACK;
  29764. return allow.load();
  29765. });
  29766. RunningServer running(svr);
  29767. Sockets socks;
  29768. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29769. EXPECT_TRUE(peer_seen);
  29770. EXPECT_EQ(0, served);
  29771. allow = true;
  29772. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29773. EXPECT_EQ(1, served);
  29774. }
  29775. }
  29776. TEST(AcceptHandlerTest, HandlerSeesTheReadTimeout) {
  29777. using namespace parking_test;
  29778. Server svr;
  29779. serve_ok(svr, threads(1));
  29780. svr.set_read_timeout(std::chrono::milliseconds(50));
  29781. std::atomic<bool> timed_out{false};
  29782. svr.set_accept_handler([&](socket_t sock) {
  29783. char c;
  29784. timed_out = detail::read_socket(sock, &c, 1, 0) < 0;
  29785. return true;
  29786. });
  29787. RunningServer running(svr);
  29788. Sockets socks;
  29789. auto sock = socks.connect(running.port);
  29790. EXPECT_TRUE(wait_until([&] { return timed_out.load(); }, 1000));
  29791. EXPECT_TRUE(get_ok(sock, 1000));
  29792. }
  29793. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  29794. TEST(AcceptHandlerTest, ThrowingHandlerRefusesTheConnection) {
  29795. using namespace parking_test;
  29796. Server svr;
  29797. serve_ok(svr, threads(1));
  29798. std::atomic<bool> throws{true};
  29799. svr.set_accept_handler([&](socket_t) -> bool {
  29800. if (throws) { throw std::runtime_error("refused"); }
  29801. return true;
  29802. });
  29803. std::atomic<int> logged{0};
  29804. svr.set_error_logger([&](const Error &err, const Request *) {
  29805. if (err == Error::UserCallbackException) { logged++; }
  29806. });
  29807. RunningServer running(svr);
  29808. Sockets socks;
  29809. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29810. EXPECT_EQ(1, logged);
  29811. throws = false;
  29812. EXPECT_TRUE(get_ok(socks.connect(running.port), 1000));
  29813. }
  29814. #endif
  29815. #ifdef CPPHTTPLIB_SSL_ENABLED
  29816. TEST(AcceptHandlerTest, RefusedTlsConnectionSkipsTheHandshake) {
  29817. using namespace parking_test;
  29818. for (auto parking : {false, true}) {
  29819. SCOPED_TRACE(parking);
  29820. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  29821. ASSERT_TRUE(svr.is_valid());
  29822. serve_ok(svr, threads(1));
  29823. svr.set_keep_alive_parking(parking);
  29824. svr.set_accept_handler([](socket_t) { return false; });
  29825. RunningServer running(svr);
  29826. Sockets socks;
  29827. // A handshake on a plain request would fail and set ssl_last_error().
  29828. EXPECT_TRUE(get_refused(socks.connect(running.port), 1000));
  29829. EXPECT_EQ(0, svr.ssl_last_error());
  29830. }
  29831. }
  29832. #endif