test.cc 1.0 MB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389263902639126392263932639426395263962639726398263992640026401264022640326404264052640626407264082640926410264112641226413264142641526416264172641826419264202642126422264232642426425264262642726428264292643026431264322643326434264352643626437264382643926440264412644226443264442644526446264472644826449264502645126452264532645426455264562645726458264592646026461264622646326464264652646626467264682646926470264712647226473264742647526476264772647826479264802648126482264832648426485264862648726488264892649026491264922649326494264952649626497264982649926500265012650226503265042650526506265072650826509265102651126512265132651426515265162651726518265192652026521265222652326524265252652626527265282652926530265312653226533265342653526536265372653826539265402654126542265432654426545265462654726548265492655026551265522655326554265552655626557265582655926560265612656226563265642656526566265672656826569265702657126572265732657426575265762657726578265792658026581265822658326584265852658626587265882658926590265912659226593265942659526596265972659826599266002660126602266032660426605266062660726608266092661026611266122661326614266152661626617266182661926620266212662226623266242662526626266272662826629266302663126632266332663426635266362663726638266392664026641266422664326644266452664626647266482664926650266512665226653266542665526656266572665826659266602666126662266632666426665266662666726668266692667026671266722667326674266752667626677266782667926680266812668226683266842668526686266872668826689266902669126692266932669426695266962669726698266992670026701267022670326704267052670626707267082670926710267112671226713267142671526716267172671826719267202672126722267232672426725267262672726728267292673026731267322673326734267352673626737267382673926740267412674226743267442674526746267472674826749267502675126752267532675426755267562675726758267592676026761267622676326764267652676626767267682676926770267712677226773267742677526776267772677826779267802678126782267832678426785267862678726788267892679026791267922679326794267952679626797267982679926800268012680226803268042680526806268072680826809268102681126812268132681426815268162681726818268192682026821268222682326824268252682626827268282682926830268312683226833268342683526836268372683826839268402684126842268432684426845268462684726848268492685026851268522685326854268552685626857268582685926860268612686226863268642686526866268672686826869268702687126872268732687426875268762687726878268792688026881268822688326884268852688626887268882688926890268912689226893268942689526896268972689826899269002690126902269032690426905269062690726908269092691026911269122691326914269152691626917269182691926920269212692226923269242692526926269272692826929269302693126932269332693426935269362693726938269392694026941269422694326944269452694626947269482694926950269512695226953269542695526956269572695826959269602696126962269632696426965269662696726968269692697026971269722697326974269752697626977269782697926980269812698226983269842698526986269872698826989269902699126992269932699426995269962699726998269992700027001270022700327004270052700627007270082700927010270112701227013270142701527016270172701827019270202702127022270232702427025270262702727028270292703027031270322703327034270352703627037270382703927040270412704227043270442704527046270472704827049270502705127052270532705427055270562705727058270592706027061270622706327064270652706627067270682706927070270712707227073270742707527076270772707827079270802708127082270832708427085270862708727088270892709027091270922709327094270952709627097270982709927100271012710227103271042710527106271072710827109271102711127112271132711427115271162711727118271192712027121271222712327124271252712627127271282712927130271312713227133271342713527136271372713827139271402714127142271432714427145271462714727148271492715027151271522715327154271552715627157271582715927160271612716227163271642716527166271672716827169271702717127172271732717427175271762717727178271792718027181271822718327184271852718627187271882718927190271912719227193271942719527196271972719827199272002720127202272032720427205272062720727208272092721027211272122721327214272152721627217272182721927220272212722227223272242722527226272272722827229272302723127232272332723427235272362723727238272392724027241272422724327244272452724627247272482724927250272512725227253272542725527256272572725827259272602726127262272632726427265272662726727268272692727027271272722727327274272752727627277272782727927280272812728227283272842728527286272872728827289272902729127292272932729427295272962729727298272992730027301273022730327304273052730627307273082730927310273112731227313273142731527316273172731827319273202732127322273232732427325273262732727328273292733027331273322733327334273352733627337273382733927340273412734227343273442734527346273472734827349273502735127352273532735427355273562735727358273592736027361273622736327364273652736627367273682736927370273712737227373273742737527376273772737827379273802738127382273832738427385273862738727388273892739027391273922739327394273952739627397273982739927400274012740227403274042740527406274072740827409274102741127412274132741427415274162741727418274192742027421274222742327424274252742627427274282742927430274312743227433274342743527436274372743827439274402744127442274432744427445274462744727448274492745027451274522745327454274552745627457274582745927460274612746227463274642746527466274672746827469274702747127472274732747427475274762747727478274792748027481274822748327484274852748627487274882748927490274912749227493274942749527496274972749827499275002750127502275032750427505275062750727508275092751027511275122751327514275152751627517275182751927520275212752227523275242752527526275272752827529275302753127532275332753427535275362753727538275392754027541275422754327544275452754627547275482754927550275512755227553275542755527556275572755827559275602756127562275632756427565275662756727568275692757027571275722757327574275752757627577275782757927580275812758227583275842758527586275872758827589275902759127592275932759427595275962759727598275992760027601276022760327604276052760627607276082760927610276112761227613276142761527616276172761827619276202762127622276232762427625276262762727628276292763027631276322763327634276352763627637276382763927640276412764227643276442764527646276472764827649276502765127652276532765427655276562765727658276592766027661276622766327664276652766627667276682766927670276712767227673276742767527676276772767827679276802768127682276832768427685276862768727688276892769027691276922769327694276952769627697276982769927700277012770227703277042770527706277072770827709277102771127712277132771427715277162771727718277192772027721277222772327724277252772627727277282772927730277312773227733277342773527736277372773827739277402774127742277432774427745277462774727748277492775027751277522775327754277552775627757277582775927760277612776227763277642776527766277672776827769277702777127772277732777427775277762777727778277792778027781277822778327784277852778627787277882778927790277912779227793277942779527796277972779827799278002780127802278032780427805278062780727808278092781027811278122781327814278152781627817278182781927820278212782227823278242782527826278272782827829278302783127832278332783427835278362783727838278392784027841278422784327844278452784627847278482784927850278512785227853278542785527856278572785827859278602786127862278632786427865278662786727868278692787027871278722787327874278752787627877278782787927880278812788227883278842788527886278872788827889278902789127892278932789427895278962789727898278992790027901279022790327904279052790627907279082790927910279112791227913279142791527916279172791827919279202792127922279232792427925279262792727928279292793027931279322793327934279352793627937279382793927940279412794227943279442794527946279472794827949279502795127952279532795427955279562795727958279592796027961279622796327964279652796627967279682796927970279712797227973279742797527976279772797827979279802798127982279832798427985279862798727988279892799027991279922799327994279952799627997279982799928000280012800228003280042800528006280072800828009280102801128012280132801428015280162801728018280192802028021280222802328024280252802628027280282802928030280312803228033280342803528036280372803828039280402804128042280432804428045280462804728048280492805028051280522805328054280552805628057280582805928060280612806228063280642806528066280672806828069280702807128072280732807428075280762807728078280792808028081280822808328084280852808628087280882808928090280912809228093280942809528096280972809828099281002810128102281032810428105281062810728108281092811028111281122811328114281152811628117281182811928120281212812228123281242812528126281272812828129281302813128132281332813428135281362813728138281392814028141281422814328144281452814628147281482814928150281512815228153281542815528156281572815828159281602816128162281632816428165281662816728168281692817028171281722817328174281752817628177281782817928180281812818228183281842818528186281872818828189281902819128192281932819428195281962819728198281992820028201282022820328204282052820628207282082820928210282112821228213282142821528216282172821828219282202822128222282232822428225282262822728228282292823028231282322823328234282352823628237282382823928240282412824228243282442824528246282472824828249282502825128252282532825428255282562825728258282592826028261282622826328264282652826628267282682826928270282712827228273282742827528276282772827828279282802828128282282832828428285282862828728288282892829028291282922829328294282952829628297282982829928300283012830228303283042830528306283072830828309283102831128312283132831428315283162831728318283192832028321283222832328324283252832628327283282832928330283312833228333283342833528336283372833828339283402834128342283432834428345283462834728348283492835028351283522835328354283552835628357283582835928360283612836228363283642836528366283672836828369283702837128372283732837428375283762837728378283792838028381283822838328384283852838628387283882838928390283912839228393283942839528396283972839828399284002840128402284032840428405284062840728408284092841028411284122841328414284152841628417284182841928420284212842228423284242842528426284272842828429284302843128432284332843428435284362843728438284392844028441284422844328444284452844628447284482844928450284512845228453284542845528456284572845828459284602846128462284632846428465284662846728468284692847028471284722847328474284752847628477284782847928480284812848228483284842848528486284872848828489284902849128492284932849428495284962849728498284992850028501285022850328504285052850628507285082850928510285112851228513285142851528516285172851828519285202852128522285232852428525285262852728528285292853028531285322853328534285352853628537285382853928540285412854228543285442854528546285472854828549285502855128552285532855428555285562855728558285592856028561285622856328564285652856628567285682856928570285712857228573285742857528576285772857828579285802858128582285832858428585285862858728588285892859028591285922859328594285952859628597285982859928600286012860228603286042860528606286072860828609286102861128612286132861428615286162861728618286192862028621286222862328624286252862628627286282862928630286312863228633286342863528636286372863828639286402864128642286432864428645286462864728648286492865028651286522865328654286552865628657286582865928660286612866228663286642866528666286672866828669286702867128672286732867428675286762867728678286792868028681286822868328684286852868628687286882868928690286912869228693286942869528696286972869828699287002870128702287032870428705287062870728708287092871028711287122871328714287152871628717287182871928720287212872228723287242872528726287272872828729287302873128732287332873428735287362873728738287392874028741287422874328744287452874628747287482874928750287512875228753287542875528756287572875828759287602876128762287632876428765287662876728768287692877028771287722877328774287752877628777287782877928780287812878228783287842878528786287872878828789287902879128792287932879428795287962879728798287992880028801288022880328804288052880628807288082880928810288112881228813288142881528816288172881828819288202882128822288232882428825288262882728828288292883028831288322883328834288352883628837288382883928840288412884228843288442884528846288472884828849288502885128852288532885428855288562885728858288592886028861288622886328864288652886628867288682886928870288712887228873288742887528876288772887828879288802888128882288832888428885288862888728888288892889028891288922889328894288952889628897288982889928900289012890228903289042890528906289072890828909289102891128912289132891428915289162891728918289192892028921289222892328924289252892628927289282892928930289312893228933289342893528936289372893828939289402894128942289432894428945289462894728948289492895028951289522895328954289552895628957289582895928960289612896228963289642896528966289672896828969289702897128972289732897428975289762897728978289792898028981289822898328984289852898628987289882898928990289912899228993289942899528996289972899828999290002900129002290032900429005290062900729008290092901029011290122901329014290152901629017290182901929020290212902229023290242902529026290272902829029290302903129032290332903429035290362903729038290392904029041290422904329044290452904629047290482904929050290512905229053290542905529056290572905829059290602906129062290632906429065290662906729068290692907029071290722907329074290752907629077290782907929080290812908229083290842908529086290872908829089290902909129092290932909429095290962909729098290992910029101291022910329104291052910629107291082910929110291112911229113291142911529116291172911829119291202912129122291232912429125291262912729128291292913029131291322913329134291352913629137291382913929140291412914229143291442914529146291472914829149291502915129152291532915429155291562915729158291592916029161291622916329164291652916629167291682916929170291712917229173291742917529176291772917829179291802918129182291832918429185291862918729188291892919029191291922919329194291952919629197291982919929200292012920229203292042920529206292072920829209292102921129212292132921429215292162921729218292192922029221292222922329224292252922629227292282922929230292312923229233292342923529236292372923829239292402924129242292432924429245292462924729248292492925029251292522925329254292552925629257292582925929260292612926229263292642926529266292672926829269292702927129272292732927429275292762927729278292792928029281292822928329284292852928629287292882928929290292912929229293292942929529296292972929829299293002930129302293032930429305293062930729308293092931029311293122931329314293152931629317293182931929320293212932229323293242932529326293272932829329293302933129332293332933429335293362933729338293392934029341293422934329344293452934629347293482934929350293512935229353293542935529356293572935829359293602936129362293632936429365293662936729368293692937029371293722937329374293752937629377293782937929380293812938229383293842938529386293872938829389293902939129392293932939429395293962939729398293992940029401294022940329404294052940629407294082940929410294112941229413294142941529416294172941829419294202942129422294232942429425294262942729428294292943029431294322943329434294352943629437294382943929440294412944229443294442944529446294472944829449294502945129452294532945429455294562945729458294592946029461294622946329464294652946629467294682946929470294712947229473294742947529476294772947829479294802948129482294832948429485294862948729488294892949029491294922949329494294952949629497294982949929500295012950229503295042950529506295072950829509295102951129512295132951429515295162951729518295192952029521295222952329524295252952629527295282952929530295312953229533295342953529536295372953829539295402954129542295432954429545295462954729548295492955029551295522955329554295552955629557295582955929560295612956229563295642956529566295672956829569295702957129572295732957429575295762957729578295792958029581295822958329584295852958629587295882958929590295912959229593295942959529596295972959829599296002960129602296032960429605296062960729608296092961029611296122961329614296152961629617296182961929620296212962229623296242962529626296272962829629296302963129632296332963429635296362963729638296392964029641296422964329644296452964629647296482964929650296512965229653296542965529656296572965829659296602966129662296632966429665296662966729668296692967029671296722967329674296752967629677296782967929680296812968229683296842968529686296872968829689296902969129692296932969429695296962969729698296992970029701297022970329704297052970629707297082970929710297112971229713297142971529716297172971829719297202972129722297232972429725297262972729728297292973029731297322973329734297352973629737297382973929740297412974229743297442974529746297472974829749297502975129752297532975429755297562975729758297592976029761297622976329764297652976629767297682976929770297712977229773297742977529776297772977829779297802978129782297832978429785297862978729788297892979029791297922979329794297952979629797297982979929800298012980229803298042980529806298072980829809298102981129812298132981429815298162981729818298192982029821298222982329824298252982629827298282982929830298312983229833298342983529836298372983829839298402984129842298432984429845298462984729848298492985029851298522985329854298552985629857298582985929860298612986229863298642986529866298672986829869298702987129872298732987429875298762987729878298792988029881298822988329884298852988629887298882988929890298912989229893298942989529896298972989829899299002990129902299032990429905299062990729908299092991029911299122991329914299152991629917299182991929920299212992229923299242992529926299272992829929299302993129932299332993429935299362993729938299392994029941299422994329944299452994629947299482994929950299512995229953299542995529956299572995829959299602996129962299632996429965299662996729968299692997029971299722997329974299752997629977299782997929980299812998229983299842998529986299872998829989299902999129992299932999429995299962999729998299993000030001300023000330004300053000630007300083000930010300113001230013300143001530016300173001830019300203002130022300233002430025300263002730028300293003030031300323003330034300353003630037300383003930040300413004230043300443004530046300473004830049300503005130052300533005430055300563005730058300593006030061300623006330064300653006630067300683006930070300713007230073300743007530076300773007830079300803008130082300833008430085300863008730088300893009030091300923009330094300953009630097300983009930100301013010230103301043010530106301073010830109301103011130112301133011430115301163011730118301193012030121301223012330124301253012630127301283012930130301313013230133301343013530136301373013830139301403014130142301433014430145301463014730148301493015030151301523015330154301553015630157301583015930160301613016230163301643016530166301673016830169301703017130172301733017430175301763017730178301793018030181301823018330184301853018630187301883018930190301913019230193301943019530196301973019830199302003020130202302033020430205302063020730208302093021030211302123021330214302153021630217302183021930220302213022230223302243022530226302273022830229302303023130232302333023430235302363023730238302393024030241302423024330244302453024630247302483024930250302513025230253302543025530256302573025830259302603026130262302633026430265302663026730268302693027030271302723027330274302753027630277302783027930280302813028230283302843028530286302873028830289302903029130292302933029430295302963029730298302993030030301303023030330304303053030630307303083030930310303113031230313303143031530316303173031830319303203032130322303233032430325303263032730328303293033030331303323033330334303353033630337303383033930340303413034230343303443034530346303473034830349303503035130352303533035430355303563035730358303593036030361303623036330364303653036630367303683036930370303713037230373303743037530376303773037830379303803038130382303833038430385303863038730388303893039030391303923039330394303953039630397303983039930400304013040230403304043040530406304073040830409304103041130412304133041430415304163041730418304193042030421304223042330424304253042630427304283042930430304313043230433304343043530436304373043830439304403044130442304433044430445304463044730448304493045030451304523045330454304553045630457304583045930460304613046230463304643046530466304673046830469304703047130472304733047430475304763047730478304793048030481304823048330484304853048630487304883048930490304913049230493304943049530496304973049830499305003050130502305033050430505305063050730508305093051030511305123051330514305153051630517305183051930520305213052230523305243052530526305273052830529305303053130532305333053430535305363053730538305393054030541305423054330544305453054630547305483054930550305513055230553305543055530556305573055830559305603056130562305633056430565305663056730568305693057030571305723057330574305753057630577305783057930580305813058230583305843058530586305873058830589305903059130592305933059430595305963059730598305993060030601306023060330604306053060630607306083060930610306113061230613306143061530616306173061830619306203062130622306233062430625306263062730628306293063030631306323063330634306353063630637306383063930640306413064230643306443064530646306473064830649306503065130652306533065430655306563065730658306593066030661306623066330664306653066630667306683066930670306713067230673306743067530676306773067830679306803068130682306833068430685306863068730688306893069030691306923069330694306953069630697306983069930700307013070230703307043070530706307073070830709307103071130712307133071430715307163071730718307193072030721307223072330724307253072630727307283072930730307313073230733307343073530736307373073830739307403074130742307433074430745307463074730748307493075030751307523075330754307553075630757307583075930760307613076230763307643076530766307673076830769307703077130772307733077430775307763077730778307793078030781307823078330784307853078630787307883078930790307913079230793307943079530796307973079830799308003080130802308033080430805308063080730808308093081030811308123081330814308153081630817308183081930820308213082230823308243082530826308273082830829308303083130832308333083430835308363083730838308393084030841308423084330844308453084630847308483084930850308513085230853308543085530856308573085830859308603086130862308633086430865308663086730868308693087030871308723087330874308753087630877308783087930880308813088230883308843088530886308873088830889308903089130892308933089430895308963089730898308993090030901309023090330904309053090630907309083090930910309113091230913309143091530916309173091830919309203092130922309233092430925309263092730928309293093030931309323093330934309353093630937309383093930940309413094230943309443094530946309473094830949309503095130952309533095430955309563095730958309593096030961309623096330964309653096630967309683096930970309713097230973309743097530976309773097830979309803098130982309833098430985309863098730988309893099030991309923099330994309953099630997309983099931000310013100231003310043100531006310073100831009310103101131012310133101431015310163101731018310193102031021310223102331024310253102631027310283102931030310313103231033310343103531036310373103831039310403104131042310433104431045310463104731048310493105031051310523105331054310553105631057310583105931060310613106231063310643106531066310673106831069310703107131072310733107431075310763107731078310793108031081310823108331084310853108631087310883108931090310913109231093310943109531096310973109831099311003110131102311033110431105311063110731108311093111031111311123111331114311153111631117311183111931120311213112231123311243112531126311273112831129311303113131132311333113431135311363113731138311393114031141311423114331144311453114631147311483114931150311513115231153311543115531156311573115831159311603116131162311633116431165311663116731168311693117031171311723117331174311753117631177311783117931180311813118231183311843118531186311873118831189311903119131192311933119431195311963119731198311993120031201312023120331204312053120631207312083120931210312113121231213312143121531216312173121831219312203122131222312233122431225312263122731228312293123031231312323123331234312353123631237312383123931240312413124231243312443124531246312473124831249312503125131252312533125431255312563125731258312593126031261312623126331264312653126631267312683126931270312713127231273312743127531276312773127831279312803128131282312833128431285312863128731288312893129031291312923129331294312953129631297312983129931300313013130231303313043130531306313073130831309313103131131312313133131431315313163131731318313193132031321313223132331324313253132631327313283132931330313313133231333313343133531336313373133831339313403134131342313433134431345313463134731348313493135031351313523135331354313553135631357313583135931360313613136231363313643136531366313673136831369313703137131372313733137431375313763137731378313793138031381313823138331384313853138631387313883138931390313913139231393313943139531396313973139831399314003140131402314033140431405314063140731408314093141031411314123141331414314153141631417314183141931420314213142231423314243142531426314273142831429314303143131432314333143431435314363143731438314393144031441314423144331444314453144631447314483144931450314513145231453314543145531456314573145831459314603146131462314633146431465314663146731468314693147031471314723147331474314753147631477314783147931480314813148231483314843148531486314873148831489314903149131492314933149431495314963149731498314993150031501315023150331504315053150631507315083150931510315113151231513315143151531516
  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_IPV6_FILE "./cert_ipv6.pem"
  41. #define SERVER_CERT_SAN_TYPES_FILE "./cert_san_types.pem"
  42. #define SERVER_CERT_WILDCARD_SAN_FILE "./cert_wildcard_san.pem"
  43. #define SERVER_PRIVATE_KEY_FILE "./key.pem"
  44. #define CA_CERT_FILE "./ca-bundle.crt"
  45. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  46. #define CLIENT_CA_CERT_DIR "."
  47. #define CLIENT_CERT_FILE "./client.cert.pem"
  48. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  49. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  50. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  51. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  52. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  54. #else
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  56. #endif
  57. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  58. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  59. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  60. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  61. #ifdef CPPHTTPLIB_SSL_ENABLED
  62. namespace httplib {
  63. namespace tls {
  64. // Declared here for the split build, where the TLS abstraction declarations
  65. // live below the split border; the definitions are linked from httplib.cc.
  66. ca_store_t create_ca_store(const char *pem, size_t len);
  67. bool set_verify_callback(ctx_t ctx, VerifyCallback callback);
  68. std::vector<std::string> get_ca_names(ctx_t ctx);
  69. } // namespace tls
  70. } // namespace httplib
  71. #endif
  72. using namespace std;
  73. using namespace httplib;
  74. const char *HOST = "localhost";
  75. static int get_base_port() {
  76. const char *shard = getenv("GTEST_SHARD_INDEX");
  77. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  78. }
  79. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  80. // New standalone tests MUST use svr.bind_to_any_port() instead.
  81. const int PORT = get_base_port();
  82. const string LONG_QUERY_VALUE = string(25000, '@');
  83. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  84. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  85. const string TOO_LONG_QUERY_URL =
  86. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  87. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  88. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  89. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  90. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  91. return file.name == key;
  92. });
  93. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  94. return *it;
  95. #else
  96. if (it != items.end()) { return *it; }
  97. throw std::runtime_error("invalid multipart form data name error");
  98. #endif
  99. }
  100. static void read_file(const std::string &path, std::string &out) {
  101. std::ifstream fs(path, std::ios_base::binary);
  102. if (!fs) {
  103. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  104. return;
  105. #else
  106. throw std::runtime_error("File not found: " + path);
  107. #endif
  108. }
  109. fs.seekg(0, std::ios_base::end);
  110. auto size = fs.tellg();
  111. fs.seekg(0);
  112. out.resize(static_cast<size_t>(size));
  113. fs.read(&out[0], static_cast<std::streamsize>(size));
  114. }
  115. class UnixSocketTest : public ::testing::Test {
  116. protected:
  117. void TearDown() override { std::remove(pathname_.c_str()); }
  118. void client_GET(const std::string &addr) {
  119. httplib::Client cli{addr};
  120. cli.set_address_family(AF_UNIX);
  121. ASSERT_TRUE(cli.is_valid());
  122. const auto &result = cli.Get(pattern_);
  123. ASSERT_TRUE(result) << "error: " << result.error();
  124. const auto &resp = result.value();
  125. EXPECT_EQ(resp.status, StatusCode::OK_200);
  126. EXPECT_EQ(resp.body, content_);
  127. }
  128. static std::string make_sock_path() {
  129. const char *shard = getenv("GTEST_SHARD_INDEX");
  130. return shard ? std::string("./httplib-server-") + shard + ".sock"
  131. : "./httplib-server.sock";
  132. }
  133. const std::string pathname_{make_sock_path()};
  134. const std::string pattern_{"/hi"};
  135. const std::string content_{"Hello World!"};
  136. };
  137. TEST_F(UnixSocketTest, pathname) {
  138. httplib::Server svr;
  139. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  140. res.set_content(content_, "text/plain");
  141. });
  142. std::thread t{[&] {
  143. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  144. }};
  145. auto se = detail::scope_exit([&] {
  146. svr.stop();
  147. t.join();
  148. ASSERT_FALSE(svr.is_running());
  149. });
  150. svr.wait_until_ready();
  151. ASSERT_TRUE(svr.is_running());
  152. client_GET(pathname_);
  153. // ".//x.sock", which is not taken for a URL
  154. client_GET("./" + pathname_.substr(1));
  155. }
  156. #if defined(__linux__) || \
  157. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  158. TEST_F(UnixSocketTest, PeerPid) {
  159. httplib::Server svr;
  160. std::string remote_port_val;
  161. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  162. res.set_content(content_, "text/plain");
  163. remote_port_val = std::to_string(req.remote_port);
  164. });
  165. std::thread t{[&] {
  166. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  167. }};
  168. auto se = detail::scope_exit([&] {
  169. svr.stop();
  170. t.join();
  171. ASSERT_FALSE(svr.is_running());
  172. });
  173. svr.wait_until_ready();
  174. ASSERT_TRUE(svr.is_running());
  175. client_GET(pathname_);
  176. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  177. }
  178. #endif
  179. #ifdef __linux__
  180. TEST_F(UnixSocketTest, abstract) {
  181. constexpr char svr_path[]{"\x00httplib-server.sock"};
  182. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  183. httplib::Server svr;
  184. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  185. res.set_content(content_, "text/plain");
  186. });
  187. std::thread t{[&] {
  188. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  189. }};
  190. auto se = detail::scope_exit([&] {
  191. svr.stop();
  192. t.join();
  193. ASSERT_FALSE(svr.is_running());
  194. });
  195. svr.wait_until_ready();
  196. ASSERT_TRUE(svr.is_running());
  197. client_GET(abstract_addr);
  198. }
  199. #endif
  200. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  201. httplib::Server svr;
  202. std::string received_host_header;
  203. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  204. // Capture the Host header sent by the client
  205. auto host_iter = req.headers.find("Host");
  206. if (host_iter != req.headers.end()) {
  207. received_host_header = host_iter->second;
  208. }
  209. res.set_content(content_, "text/plain");
  210. });
  211. std::thread t{[&] {
  212. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  213. }};
  214. auto se = detail::scope_exit([&] {
  215. svr.stop();
  216. t.join();
  217. ASSERT_FALSE(svr.is_running());
  218. });
  219. svr.wait_until_ready();
  220. ASSERT_TRUE(svr.is_running());
  221. // Test that Host header is automatically set to "localhost" for Unix socket
  222. // connections
  223. httplib::Client cli{pathname_};
  224. cli.set_address_family(AF_UNIX);
  225. ASSERT_TRUE(cli.is_valid());
  226. const auto &result = cli.Get(pattern_);
  227. ASSERT_TRUE(result) << "error: " << result.error();
  228. const auto &resp = result.value();
  229. EXPECT_EQ(resp.status, StatusCode::OK_200);
  230. EXPECT_EQ(resp.body, content_);
  231. // Verify that Host header was automatically set to "localhost"
  232. EXPECT_EQ(received_host_header, "localhost");
  233. }
  234. #ifndef _WIN32
  235. TEST(SocketStream, wait_writable_UNIX) {
  236. int fds[2];
  237. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  238. const auto asSocketStream = [&](socket_t fd,
  239. std::function<bool(Stream &)> func) {
  240. return detail::process_client_socket(
  241. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  242. };
  243. asSocketStream(fds[0], [&](Stream &s0) {
  244. EXPECT_EQ(s0.socket(), fds[0]);
  245. EXPECT_TRUE(s0.wait_writable());
  246. EXPECT_TRUE(s0.is_peer_alive());
  247. EXPECT_EQ(0, close(fds[1]));
  248. EXPECT_FALSE(s0.is_peer_alive());
  249. return true;
  250. });
  251. EXPECT_EQ(0, close(fds[0]));
  252. }
  253. TEST(SocketStream, wait_writable_INET) {
  254. sockaddr_in addr;
  255. memset(&addr, 0, sizeof(addr));
  256. addr.sin_family = AF_INET;
  257. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  258. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  259. int disconnected_svr_sock = -1;
  260. std::thread svr{[&] {
  261. const int s = socket(AF_INET, SOCK_STREAM, 0);
  262. ASSERT_LE(0, s);
  263. // PORT + 1 is shared with the SSL redirect tests and with
  264. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  265. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  266. // because that happens on a worker thread the ASSERT does not stop the
  267. // test: it runs on and fails at the disconnected_svr_sock check instead.
  268. default_socket_options(s);
  269. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  270. ASSERT_EQ(0, listen(s, 1));
  271. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  272. ASSERT_EQ(0, close(s));
  273. }};
  274. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  275. std::thread cli{[&] {
  276. const int s = socket(AF_INET, SOCK_STREAM, 0);
  277. ASSERT_LE(0, s);
  278. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  279. ASSERT_EQ(0, close(s));
  280. }};
  281. cli.join();
  282. svr.join();
  283. ASSERT_NE(disconnected_svr_sock, -1);
  284. const auto asSocketStream = [&](socket_t fd,
  285. std::function<bool(Stream &)> func) {
  286. return detail::process_client_socket(
  287. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  288. };
  289. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  290. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  291. // wait_writable() returns true because select_write() only checks if the
  292. // send buffer has space. Peer disconnection is detected later by send().
  293. EXPECT_TRUE(ss.wait_writable());
  294. return true;
  295. });
  296. ASSERT_EQ(0, close(disconnected_svr_sock));
  297. }
  298. #endif // #ifndef _WIN32
  299. TEST(SetSocketOptTest, TcpNoDelay) {
  300. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  301. ASSERT_NE(sock, INVALID_SOCKET);
  302. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  303. int val = 0;
  304. socklen_t len = sizeof(val);
  305. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  306. reinterpret_cast<char *>(&val), &len));
  307. EXPECT_NE(val, 0);
  308. detail::close_socket(sock);
  309. }
  310. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  311. // accept() reports failures through WSAGetLastError() on Windows and through
  312. // errno everywhere else. Asking the wrong one is what made the accept loop
  313. // treat every recoverable failure as fatal on Windows.
  314. struct Classification {
  315. bool resource;
  316. bool transient;
  317. };
  318. auto classify = [](int err) {
  319. #ifdef _WIN32
  320. WSASetLastError(err);
  321. #else
  322. errno = err;
  323. #endif
  324. // Read both before asserting: an assertion may clobber the error slot.
  325. Classification c;
  326. c.resource = detail::is_accept_resource_error();
  327. c.transient = detail::is_accept_transient_error();
  328. return c;
  329. };
  330. #ifdef _WIN32
  331. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  332. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  333. WSAECONNRESET, WSAECONNABORTED};
  334. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  335. #else
  336. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  337. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  338. ECONNABORTED};
  339. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  340. #endif
  341. for (auto err : resource_errors) {
  342. const auto c = classify(err);
  343. EXPECT_TRUE(c.resource) << "error " << err;
  344. EXPECT_FALSE(c.transient) << "error " << err;
  345. }
  346. for (auto err : transient_errors) {
  347. const auto c = classify(err);
  348. EXPECT_TRUE(c.transient) << "error " << err;
  349. EXPECT_FALSE(c.resource) << "error " << err;
  350. }
  351. for (auto err : fatal_errors) {
  352. const auto c = classify(err);
  353. EXPECT_FALSE(c.resource) << "error " << err;
  354. EXPECT_FALSE(c.transient) << "error " << err;
  355. }
  356. #ifdef _WIN32
  357. WSASetLastError(0);
  358. #else
  359. errno = 0;
  360. #endif
  361. }
  362. TEST(ClientTest, MoveConstructible) {
  363. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  364. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  365. }
  366. TEST(ClientTest, MoveAssignable) {
  367. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  368. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  369. }
  370. #ifdef _WIN32
  371. TEST(StartupTest, WSAStartup) {
  372. WSADATA wsaData;
  373. int ret = WSAStartup(0x0002, &wsaData);
  374. ASSERT_EQ(0, ret);
  375. }
  376. #endif
  377. TEST(DecodePathTest, PercentCharacter) {
  378. EXPECT_EQ(
  379. decode_path_component(
  380. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  381. U8("descrip=Gastos áéíóúñÑ 6"));
  382. }
  383. TEST(DecodePathTest, PercentCharacterNUL) {
  384. string expected;
  385. expected.push_back('x');
  386. expected.push_back('\0');
  387. expected.push_back('x');
  388. EXPECT_EQ(decode_path_component("x%00x"), expected);
  389. }
  390. TEST(DecodePathTest, UnicodeEncoding) {
  391. // %u0041 = 'A' (1-byte UTF-8)
  392. EXPECT_EQ("A", decode_path_component("%u0041"));
  393. // %u00E9 = 'é' (2-byte UTF-8)
  394. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  395. // %u3042 = 'あ' (3-byte UTF-8)
  396. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  397. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  398. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  399. // %uD800 = surrogate (invalid, kept as it is rather than joining its
  400. // neighbours)
  401. EXPECT_EQ("%uD800", decode_path_component("%uD800"));
  402. EXPECT_EQ("/ad%uD800min", decode_path_component("/ad%uD800min"));
  403. }
  404. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  405. // A sign or whitespace inside the two-character escape window must not be
  406. // accepted as a valid percent-encoding; the sequence is passed through
  407. // literally, matching decode_uri_component / decode_path_component.
  408. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  409. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  410. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  411. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  412. // Well-formed escapes still decode.
  413. EXPECT_EQ("-", decode_query_component("%2D", false));
  414. EXPECT_EQ("A", decode_query_component("%41", false));
  415. }
  416. TEST(SanitizeFilenameTest, VariousPatterns) {
  417. // Path traversal
  418. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  419. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  420. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  421. // Normal and edge cases
  422. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  423. EXPECT_EQ("filename.txt",
  424. httplib::sanitize_filename("/path/to/filename.txt"));
  425. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  426. EXPECT_EQ("", httplib::sanitize_filename(".."));
  427. EXPECT_EQ("", httplib::sanitize_filename(""));
  428. // Null bytes stripped
  429. EXPECT_EQ("safe.txt",
  430. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  431. // Whitespace-only rejected
  432. EXPECT_EQ("", httplib::sanitize_filename(" "));
  433. }
  434. // Forward declaration (see the base64_encode note below): split builds move the
  435. // definition into httplib.cc, so re-declaring it here lets the test link.
  436. namespace httplib {
  437. namespace detail {
  438. bool is_chunked_transfer_encoding(const Headers &headers);
  439. } // namespace detail
  440. } // namespace httplib
  441. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  442. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  443. auto make = [](std::initializer_list<const char *> lines) {
  444. Headers h;
  445. for (auto te : lines) {
  446. if (te) { h.emplace("Transfer-Encoding", te); }
  447. }
  448. return h;
  449. };
  450. // Sole coding, matched case-insensitively.
  451. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  452. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  453. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  454. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  455. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  456. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  457. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  458. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  459. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  462. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  463. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  464. // were received, into one list. Headers preserves that order, so the answer
  465. // is decided by the last coding of the last line and the order the lines
  466. // arrived in is significant.
  467. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  468. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  470. // The split can fall anywhere in the list.
  471. EXPECT_TRUE(
  472. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  473. EXPECT_FALSE(
  474. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  475. // A trailing line naming no coding leaves the list ending in nothing, so it
  476. // must not inherit the chunked from the line before it.
  477. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  478. }
  479. // Forward declarations (see the base64_encode note below).
  480. namespace httplib {
  481. namespace detail {
  482. bool parse_status_line(const char *line, std::string &version, int &status,
  483. std::string &reason);
  484. std::string file_extension(const std::string &path);
  485. std::string
  486. find_content_type(const std::string &path,
  487. const std::map<std::string, std::string> &user_data,
  488. const std::string &default_content_type);
  489. bool can_compress_content_type(const std::string &content_type);
  490. bool is_prohibited_header_name(const std::string &name);
  491. bool is_valid_path(const std::string &path);
  492. #ifdef CPPHTTPLIB_SSL_ENABLED
  493. bool match_hostname(const std::string &pattern, const std::string &hostname);
  494. #endif
  495. } // namespace detail
  496. } // namespace httplib
  497. TEST(ParseStatusLineTest, ParsesVersionStatusAndReason) {
  498. struct {
  499. const char *line;
  500. const char *version;
  501. int status;
  502. const char *reason;
  503. } cases[] = {
  504. {"HTTP/1.1 200 OK\r\n", "HTTP/1.1", 200, "OK"},
  505. {"HTTP/1.0 404 Not Found\r\n", "HTTP/1.0", 404, "Not Found"},
  506. // The reason phrase may be empty, or left out along with its space.
  507. {"HTTP/1.1 204 \r\n", "HTTP/1.1", 204, ""},
  508. {"HTTP/1.1 304\r\n", "HTTP/1.1", 304, ""},
  509. };
  510. for (const auto &c : cases) {
  511. std::string version;
  512. int status = 0;
  513. std::string reason = "unset";
  514. EXPECT_TRUE(detail::parse_status_line(c.line, version, status, reason))
  515. << c.line;
  516. EXPECT_EQ(c.version, version);
  517. EXPECT_EQ(c.status, status);
  518. EXPECT_EQ(c.reason, reason);
  519. }
  520. }
  521. TEST(ParseStatusLineTest, RejectsMalformedLines) {
  522. const char *lines[] = {
  523. "HTTP/2 200 OK\r\n",
  524. "HTTP/1.2 200 OK\r\n",
  525. "HTTP/1.1 20 OK\r\n",
  526. "HTTP/1.1 2000 OK\r\n",
  527. "HTTP/1.1 2x0 OK\r\n",
  528. "HTTP/1.1 200 OK\r\n",
  529. "HTTP/1.1 200OK\r\n",
  530. "HTTP/1.1 200 O\rK\r\n",
  531. "HTTP/1.1 200 OK",
  532. "HTTP/1.1 200 OK\r\nX",
  533. "",
  534. #ifndef CPPHTTPLIB_ALLOW_LF_AS_LINE_TERMINATOR
  535. "HTTP/1.1 200 OK\n",
  536. #endif
  537. };
  538. for (auto line : lines) {
  539. std::string version;
  540. int status = 0;
  541. std::string reason;
  542. EXPECT_FALSE(detail::parse_status_line(line, version, status, reason))
  543. << line;
  544. }
  545. }
  546. TEST(ParseStatusLineTest, AcceptsAReasonPhraseAsLongAsALine) {
  547. // Long enough to overflow the stack when matched with std::regex.
  548. auto long_reason = std::string(CPPHTTPLIB_MAX_LINE_LENGTH - 15, 'A');
  549. auto line = "HTTP/1.1 200 " + long_reason + "\r\n";
  550. std::string version;
  551. int status = 0;
  552. std::string reason;
  553. EXPECT_TRUE(detail::parse_status_line(line.c_str(), version, status, reason));
  554. EXPECT_EQ(200, status);
  555. EXPECT_EQ(long_reason, reason);
  556. }
  557. TEST(FileExtensionTest, TakesTheAlphanumericSuffix) {
  558. EXPECT_EQ("txt", detail::file_extension("a.txt"));
  559. EXPECT_EQ("gz", detail::file_extension("/dir/a.tar.gz"));
  560. EXPECT_EQ("htaccess", detail::file_extension(".htaccess"));
  561. EXPECT_EQ("", detail::file_extension("noext"));
  562. EXPECT_EQ("", detail::file_extension("a."));
  563. EXPECT_EQ("", detail::file_extension("dir.d/file"));
  564. EXPECT_EQ("", detail::file_extension("a.b-c"));
  565. // Long enough to overflow the stack when matched with std::regex.
  566. auto long_ext = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'a');
  567. EXPECT_EQ(long_ext, detail::file_extension("a." + long_ext));
  568. }
  569. #ifdef CPPHTTPLIB_SSL_ENABLED
  570. TEST(MatchHostnameTest, FollowsX509CheckHost) {
  571. EXPECT_TRUE(detail::match_hostname("*.example.com", "www.example.com"));
  572. EXPECT_TRUE(detail::match_hostname("www*.example.com", "www1.example.com"));
  573. EXPECT_TRUE(detail::match_hostname("www.example.com", "WWW.example.com."));
  574. // A wildcard needs two labels after it, in the leftmost label only
  575. EXPECT_FALSE(detail::match_hostname("*.com", "example.com"));
  576. EXPECT_FALSE(detail::match_hostname("*", "localhost"));
  577. EXPECT_FALSE(detail::match_hostname("vic*.test", "victim.test"));
  578. EXPECT_FALSE(detail::match_hostname("www.*.com", "www.a.com"));
  579. EXPECT_FALSE(
  580. detail::match_hostname("xn--*.example.com", "xn--a.example.com"));
  581. // No name may have an empty label
  582. EXPECT_FALSE(detail::match_hostname("*.example.com", "a..example.com"));
  583. EXPECT_FALSE(detail::match_hostname("a..example.com", "a.example.com"));
  584. }
  585. #endif
  586. TEST(CaseIgnoreHashTest, IgnoresCaseAndTakesLongKeys) {
  587. detail::case_ignore::hash hash;
  588. EXPECT_EQ(hash("Content-Type"), hash("content-TYPE"));
  589. EXPECT_NE(hash("Content-Type"), hash("Content-Length"));
  590. // Long enough to overflow the stack if hashed one call per character.
  591. EXPECT_EQ(hash(std::string(1 << 20, 'A')), hash(std::string(1 << 20, 'a')));
  592. }
  593. TEST(FindContentTypeTest, ComparesWholeExtensions) {
  594. EXPECT_EQ("text/html", detail::find_content_type("/a.html", {}, ""));
  595. EXPECT_EQ("image/svg+xml", detail::find_content_type("/a.svg", {}, ""));
  596. EXPECT_EQ("text/javascript", detail::find_content_type("/a.js", {}, ""));
  597. EXPECT_EQ("text/html", detail::find_content_type("/INDEX.HTML", {}, ""));
  598. // Same 26-bit hash as html, svg and js.
  599. EXPECT_EQ("", detail::find_content_type("/a.qo2yh", {}, ""));
  600. EXPECT_EQ("", detail::find_content_type("/a.q4g", {}, ""));
  601. EXPECT_EQ("", detail::find_content_type("/a.l5", {}, ""));
  602. }
  603. TEST(IsValidPathTest, RejectsSegmentsEndingInDotOrSpace) {
  604. for (auto path : {"/a.", "/a ", "/dir./a", "/dir /a", "/..."}) {
  605. EXPECT_FALSE(detail::is_valid_path(path)) << path;
  606. }
  607. }
  608. TEST(CanCompressContentTypeTest, ComparesWholeTypes) {
  609. EXPECT_TRUE(detail::can_compress_content_type("application/json"));
  610. EXPECT_TRUE(detail::can_compress_content_type("text/plain; charset=utf-8"));
  611. EXPECT_FALSE(detail::can_compress_content_type("text/event-stream"));
  612. EXPECT_FALSE(detail::can_compress_content_type("image/png"));
  613. EXPECT_TRUE(detail::can_compress_content_type("Application/JSON"));
  614. EXPECT_FALSE(detail::can_compress_content_type("Text/Event-Stream"));
  615. // Same 26-bit hash as application/json.
  616. EXPECT_FALSE(detail::can_compress_content_type("VY_LQ"));
  617. }
  618. TEST(MultipartFormDataTest, MediaTypeIgnoresCase) {
  619. Request req;
  620. req.set_header("Content-Type", "Multipart/Form-Data; Boundary=x");
  621. EXPECT_TRUE(req.is_multipart_form_data());
  622. std::string boundary;
  623. EXPECT_TRUE(detail::parse_multipart_boundary(
  624. req.get_header_value("Content-Type"), boundary));
  625. EXPECT_EQ("x", boundary);
  626. }
  627. TEST(ProhibitedHeaderNameTest, ComparesWholeNames) {
  628. EXPECT_TRUE(detail::is_prohibited_header_name("REMOTE_ADDR"));
  629. EXPECT_TRUE(detail::is_prohibited_header_name("LOCAL_PORT"));
  630. EXPECT_FALSE(detail::is_prohibited_header_name("Host"));
  631. EXPECT_TRUE(detail::is_prohibited_header_name("remote_addr"));
  632. // Same 26-bit hash as REMOTE_ADDR.
  633. EXPECT_FALSE(detail::is_prohibited_header_name("IIJRp"));
  634. }
  635. // Forward declaration: in split builds split.py strips `inline` and moves the
  636. // definition into httplib.cc, so detail::base64_encode is not visible from the
  637. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  638. // in both header-only and split builds.
  639. namespace httplib {
  640. namespace detail {
  641. std::string base64_encode(const std::string &in);
  642. } // namespace detail
  643. } // namespace httplib
  644. TEST(Base64EncodeTest, KnownAnswers) {
  645. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  646. // where the accumulator's top bit is already set before the next shift.
  647. EXPECT_EQ("", detail::base64_encode(""));
  648. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  649. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  650. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  651. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  652. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  653. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  654. // High bytes keep the top bit set across several rounds.
  655. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  656. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  657. }
  658. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  659. string unescapedCharacters = "-_.!~*'()";
  660. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  661. }
  662. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  663. string reservedCharacters = ";,/?:@&=+$";
  664. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  665. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  666. }
  667. TEST(ClientQueryOrder, PreserveOrder) {
  668. // This test reproduces Issue #2259: client may reorder query parameters
  669. // when sending a GET request. The expected behavior is that the client
  670. // preserves the original query string order when the caller supplied it
  671. // as part of the path.
  672. Server svr;
  673. svr.Get("/", [&](const Request &req, Response &res) {
  674. // Echo back the raw target so the test can assert ordering
  675. res.set_content(req.target, "text/plain");
  676. });
  677. std::thread t{[&] { svr.listen(HOST, PORT); }};
  678. auto se = detail::scope_exit([&] {
  679. svr.stop();
  680. t.join();
  681. ASSERT_FALSE(svr.is_running());
  682. });
  683. svr.wait_until_ready();
  684. Client cli(HOST, PORT);
  685. ASSERT_TRUE(cli.is_valid());
  686. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  687. auto res = cli.Get(original);
  688. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  689. // Expect the echoed target to exactly match the original path (order
  690. // preserved)
  691. EXPECT_EQ(res->body, original);
  692. }
  693. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  694. string chineseCharacters = U8("中国語");
  695. string russianCharacters = U8("дом");
  696. string brazilianCharacters = U8("óculos");
  697. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  698. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  699. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  700. "%D0%B4%D0%BE%D0%BC");
  701. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  702. }
  703. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  704. string unescapedCharacters = "-_.!~*'()";
  705. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  706. }
  707. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  708. string reservedCharacters = ";,/?:@&=+$";
  709. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  710. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  711. }
  712. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  713. string chineseCharacters = U8("中国語");
  714. string russianCharacters = U8("дом");
  715. string brazilianCharacters = U8("óculos");
  716. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  717. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  718. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  719. "%D0%B4%D0%BE%D0%BC");
  720. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  721. }
  722. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  723. // Issue #2082 use case: encoding path component with ampersand
  724. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  725. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  726. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  727. }
  728. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  729. string unescapedCharacters = "-_.!~*'()";
  730. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  731. }
  732. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  733. string reservedCharacters = ";,/?:@&=+$#";
  734. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  735. }
  736. TEST(EncodeUriTest, TestUTF8Characters) {
  737. string chineseCharacters = U8("中国語");
  738. string russianCharacters = U8("дом");
  739. string brazilianCharacters = U8("óculos");
  740. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  741. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  742. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  743. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  744. }
  745. TEST(EncodeUriTest, TestCompleteUri) {
  746. string uri =
  747. "https://example.com/path/to/resource?query=value&param=test#fragment";
  748. EXPECT_EQ(
  749. httplib::encode_uri(uri),
  750. "https://example.com/path/to/resource?query=value&param=test#fragment");
  751. }
  752. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  753. string uri =
  754. "https://example.com/path with spaces/file name.html?q=hello world";
  755. EXPECT_EQ(httplib::encode_uri(uri),
  756. "https://example.com/path%20with%20spaces/"
  757. "file%20name.html?q=hello%20world");
  758. }
  759. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  760. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  761. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  762. }
  763. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  764. string unescapedCharacters = "-_.!~*'()";
  765. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  766. }
  767. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  768. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  769. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  770. string encodedBrazilian = "%C3%B3culos";
  771. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  772. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  773. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  774. }
  775. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  776. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  777. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  778. "Piri Tommy Villiers - on & on");
  779. }
  780. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  781. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  782. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  783. }
  784. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  785. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  786. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  787. }
  788. TEST(DecodeUriTest, TestUTF8Characters) {
  789. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  790. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  791. string encodedBrazilian = "%C3%B3culos";
  792. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  793. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  794. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  795. }
  796. TEST(DecodeUriTest, TestCompleteUri) {
  797. string encodedUri = "https://example.com/path%20with%20spaces/"
  798. "file%20name.html?q=hello%20world";
  799. EXPECT_EQ(
  800. httplib::decode_uri(encodedUri),
  801. "https://example.com/path with spaces/file name.html?q=hello world");
  802. }
  803. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  804. string original =
  805. "https://example.com/path with spaces/file name.html?q=hello world";
  806. string encoded = httplib::encode_uri(original);
  807. string decoded = httplib::decode_uri(encoded);
  808. EXPECT_EQ(decoded, original);
  809. }
  810. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  811. // decode_uri is the inverse of encode_uri: an escaped reserved character
  812. // stays encoded so it is not promoted into a real delimiter, while
  813. // non-reserved escapes still decode (like JS decodeURI).
  814. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  815. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  816. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  817. "%3F%3A%40%26%3D%2B%24%2C%3B");
  818. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  819. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  820. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  821. "http://example.com/a%2Fb");
  822. // decode_uri_component still decodes the reserved character.
  823. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  824. }
  825. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  826. string original = "Piri Tommy Villiers - on & on";
  827. string encoded = httplib::encode_uri_component(original);
  828. string decoded = httplib::decode_uri_component(encoded);
  829. EXPECT_EQ(decoded, original);
  830. }
  831. TEST(TrimTests, TrimStringTests) {
  832. EXPECT_EQ("abc", detail::trim_copy("abc"));
  833. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  834. EXPECT_TRUE(detail::trim_copy("").empty());
  835. }
  836. TEST(AsciiTest, LocaleIndependentClassification) {
  837. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  838. // which consult the global C locale: std::isalnum(0xC5) can return true
  839. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  840. // helpers must classify every byte by the ASCII grammar alone.
  841. for (int i = 0; i < 256; i++) {
  842. auto c = static_cast<char>(i);
  843. auto is_digit = i >= '0' && i <= '9';
  844. auto is_upper = i >= 'A' && i <= 'Z';
  845. auto is_lower = i >= 'a' && i <= 'z';
  846. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  847. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  848. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  849. << "byte " << i;
  850. }
  851. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  852. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  853. // Non-ASCII bytes must be percent-encoded, never passed through as
  854. // alphanumeric.
  855. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  856. }
  857. TEST(FromCharsTest, Double) {
  858. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  859. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  860. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  861. auto parse = [](const std::string &s, double &v) {
  862. return detail::from_chars(s.data(), s.data() + s.size(), v);
  863. };
  864. double v = -1.0;
  865. // Representative quality values.
  866. EXPECT_EQ(parse("0", v).ec, std::errc{});
  867. EXPECT_DOUBLE_EQ(v, 0.0);
  868. EXPECT_EQ(parse("1", v).ec, std::errc{});
  869. EXPECT_DOUBLE_EQ(v, 1.0);
  870. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  871. EXPECT_DOUBLE_EQ(v, 0.8);
  872. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  873. EXPECT_DOUBLE_EQ(v, 0.001);
  874. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  875. EXPECT_DOUBLE_EQ(v, 1.0);
  876. // A missing integer or fractional part is tolerated.
  877. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  878. EXPECT_DOUBLE_EQ(v, 0.5);
  879. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  880. EXPECT_DOUBLE_EQ(v, 5.0);
  881. // Values outside [0, 1] still parse; the caller range-checks them.
  882. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  883. EXPECT_DOUBLE_EQ(v, 123.456);
  884. // Stops at the first byte that is not part of the number and reports where.
  885. std::string trailing = "0.9, text/html";
  886. auto r = parse(trailing, v);
  887. EXPECT_EQ(r.ec, std::errc{});
  888. EXPECT_DOUBLE_EQ(v, 0.9);
  889. EXPECT_EQ(*r.ptr, ',');
  890. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  891. // outright, and an 'e'/'E' simply ends the number.
  892. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  893. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  894. std::string exp_input = "1.5e3";
  895. r = parse(exp_input, v);
  896. EXPECT_EQ(r.ec, std::errc{});
  897. EXPECT_DOUBLE_EQ(v, 1.5);
  898. EXPECT_EQ(*r.ptr, 'e');
  899. // Invalid inputs.
  900. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  901. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  902. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  903. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  904. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  905. // Pathological but well-formed inputs must stay bounded (no overflow, no
  906. // out-of-bounds table access) and stay within [0, 1] for the caller.
  907. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  908. std::errc{});
  909. EXPECT_DOUBLE_EQ(v, 0.0);
  910. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  911. std::errc{});
  912. EXPECT_GE(v, 0.0);
  913. EXPECT_LE(v, 1.0);
  914. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  915. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  916. }
  917. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  918. // Simple case without quality values
  919. std::vector<std::string> result1;
  920. EXPECT_TRUE(detail::parse_accept_header(
  921. "text/html,application/json,text/plain", result1));
  922. EXPECT_EQ(result1.size(), 3U);
  923. EXPECT_EQ(result1[0], "text/html");
  924. EXPECT_EQ(result1[1], "application/json");
  925. EXPECT_EQ(result1[2], "text/plain");
  926. // With quality values
  927. std::vector<std::string> result2;
  928. EXPECT_TRUE(detail::parse_accept_header(
  929. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  930. EXPECT_EQ(result2.size(), 3U);
  931. EXPECT_EQ(result2[0], "application/json"); // highest q value
  932. EXPECT_EQ(result2[1], "text/html");
  933. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  934. }
  935. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  936. // Mixed with and without quality values
  937. std::vector<std::string> result;
  938. EXPECT_TRUE(detail::parse_accept_header(
  939. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  940. EXPECT_EQ(result.size(), 3U);
  941. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  942. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  943. EXPECT_EQ(result[2], "application/json"); // q=0.5
  944. }
  945. TEST(ParseAcceptHeaderTest, EdgeCases) {
  946. // Empty header
  947. std::vector<std::string> empty_result;
  948. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  949. EXPECT_TRUE(empty_result.empty());
  950. // Single type
  951. std::vector<std::string> single_result;
  952. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  953. EXPECT_EQ(single_result.size(), 1U);
  954. EXPECT_EQ(single_result[0], "application/json");
  955. // Wildcard types
  956. std::vector<std::string> wildcard_result;
  957. EXPECT_TRUE(detail::parse_accept_header(
  958. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  959. EXPECT_EQ(wildcard_result.size(), 3U);
  960. EXPECT_EQ(wildcard_result[0], "application/json");
  961. EXPECT_EQ(wildcard_result[1], "text/*");
  962. EXPECT_EQ(wildcard_result[2], "*/*");
  963. }
  964. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  965. // Common browser Accept header
  966. std::vector<std::string> browser_result;
  967. EXPECT_TRUE(
  968. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  969. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  970. browser_result));
  971. EXPECT_EQ(browser_result.size(), 6U);
  972. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  973. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  974. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  975. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  976. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  977. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  978. // API client header
  979. std::vector<std::string> api_result;
  980. EXPECT_TRUE(detail::parse_accept_header(
  981. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  982. api_result));
  983. EXPECT_EQ(api_result.size(), 3U);
  984. EXPECT_EQ(api_result[0], "application/json");
  985. EXPECT_EQ(api_result[1], "application/xml");
  986. EXPECT_EQ(api_result[2], "text/plain");
  987. }
  988. TEST(ParseAcceptHeaderTest, SpecialCases) {
  989. // Quality value with 3 decimal places
  990. std::vector<std::string> decimal_result;
  991. EXPECT_TRUE(detail::parse_accept_header(
  992. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  993. EXPECT_EQ(decimal_result.size(), 2U);
  994. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  995. EXPECT_EQ(decimal_result[1], "text/html");
  996. // Zero quality (should still be included but with lowest priority)
  997. std::vector<std::string> zero_q_result;
  998. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  999. zero_q_result));
  1000. EXPECT_EQ(zero_q_result.size(), 2U);
  1001. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  1002. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  1003. // No spaces around commas
  1004. std::vector<std::string> no_space_result;
  1005. EXPECT_TRUE(detail::parse_accept_header(
  1006. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  1007. no_space_result));
  1008. EXPECT_EQ(no_space_result.size(), 3U);
  1009. EXPECT_EQ(no_space_result[0], "text/html");
  1010. EXPECT_EQ(no_space_result[1], "application/json");
  1011. EXPECT_EQ(no_space_result[2], "text/plain");
  1012. }
  1013. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  1014. // Quality values always use '.' as the decimal separator, so parsing must
  1015. // not depend on the process locale. An embedding application may have
  1016. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  1017. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  1018. std::string saved = cur ? cur : "C";
  1019. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  1020. "fr_FR.UTF-8"};
  1021. bool switched = false;
  1022. for (const auto loc : comma_locales) {
  1023. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  1024. std::localeconv()->decimal_point[0] == ',') {
  1025. switched = true;
  1026. break;
  1027. }
  1028. }
  1029. if (!switched) {
  1030. std::setlocale(LC_NUMERIC, saved.c_str());
  1031. GTEST_SKIP() << "no comma-decimal locale available on this host";
  1032. }
  1033. // The higher-weighted type appears later in the list, so a correct parse
  1034. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  1035. // sensitive parse reads both weights as 0 and leaves the original order.
  1036. std::vector<std::string> result;
  1037. EXPECT_TRUE(detail::parse_accept_header(
  1038. "application/json;q=0.1,text/html;q=0.9", result));
  1039. ASSERT_EQ(result.size(), 2U);
  1040. EXPECT_EQ(result[0], "text/html");
  1041. EXPECT_EQ(result[1], "application/json");
  1042. std::setlocale(LC_NUMERIC, saved.c_str());
  1043. }
  1044. TEST(ParseAcceptHeaderTest, InvalidCases) {
  1045. std::vector<std::string> result;
  1046. // Invalid quality value (> 1.0)
  1047. EXPECT_FALSE(
  1048. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  1049. // Invalid quality value (< 0.0)
  1050. EXPECT_FALSE(
  1051. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  1052. // Invalid quality value (not a number)
  1053. EXPECT_FALSE(detail::parse_accept_header(
  1054. "text/html;q=invalid,application/json", result));
  1055. // A valid numeric prefix does not make the entire quality value valid.
  1056. EXPECT_FALSE(detail::parse_accept_header(
  1057. "text/html;q=0.5junk,application/json", result));
  1058. // Empty quality value
  1059. EXPECT_FALSE(
  1060. detail::parse_accept_header("text/html;q=,application/json", result));
  1061. // Invalid media type format (no slash and not wildcard)
  1062. EXPECT_FALSE(
  1063. detail::parse_accept_header("invalidtype,application/json", result));
  1064. // Valid cases should still work
  1065. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  1066. EXPECT_EQ(result.size(), 1U);
  1067. EXPECT_EQ(result[0], "*/*");
  1068. EXPECT_TRUE(detail::parse_accept_header("*", result));
  1069. EXPECT_EQ(result.size(), 1U);
  1070. EXPECT_EQ(result[0], "*");
  1071. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  1072. EXPECT_EQ(result.size(), 1U);
  1073. EXPECT_EQ(result[0], "text/*");
  1074. }
  1075. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  1076. // elements, so a leading, trailing or doubled comma is a legal Accept value
  1077. // and must not be answered with 400 Bad Request.
  1078. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  1079. struct {
  1080. const char *value;
  1081. std::vector<std::string> expected;
  1082. } cases[] = {
  1083. {",application/json", {"application/json"}},
  1084. {"text/html,", {"text/html"}},
  1085. {"text/html,,*/*", {"text/html", "*/*"}},
  1086. // An empty element may be spelled with whitespace in it
  1087. {"text/html, , application/json", {"text/html", "application/json"}},
  1088. // Nothing but empty elements is an empty list, which means the same
  1089. // thing as no Accept header at all
  1090. {",,,", {}},
  1091. // Quality values still apply across ignored empty elements
  1092. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  1093. };
  1094. for (const auto &c : cases) {
  1095. std::vector<std::string> result;
  1096. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1097. << "value: " << c.value;
  1098. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1099. }
  1100. // An invalid entry is still rejected when empty elements surround it
  1101. std::vector<std::string> result;
  1102. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  1103. }
  1104. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and a ','
  1105. // or ';' inside one does not end the list element or the parameter. Section
  1106. // 5.6.4: nor does a '"' that a backslash escapes end the quoted-string.
  1107. TEST(ParseAcceptHeaderTest, DelimitersInQuotedParameterValues) {
  1108. struct {
  1109. const char *value;
  1110. std::vector<std::string> expected;
  1111. } cases[] = {
  1112. {"text/html;profile=\"a,b\",application/json",
  1113. {"text/html", "application/json"}},
  1114. // A "q=" inside a quoted value is not the weight
  1115. {"text/html;profile=\"a;q=0.1\",application/json;q=0.5",
  1116. {"text/html", "application/json"}},
  1117. // The weight after a quoted value still applies
  1118. {"text/html;profile=\"a,b;q=0.1\";q=0.8,application/json;q=0.9",
  1119. {"application/json", "text/html"}},
  1120. {"text/html;profile=\"a\\\",b\";q=0.8,application/json;q=0.9",
  1121. {"application/json", "text/html"}},
  1122. {"text/html;profile=\"a\\\"b\",application/json",
  1123. {"text/html", "application/json"}},
  1124. // An escaped backslash does not escape the '"' after it
  1125. {"text/html;profile=\"a\\\\\",application/json",
  1126. {"text/html", "application/json"}},
  1127. };
  1128. for (const auto &c : cases) {
  1129. std::vector<std::string> result;
  1130. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  1131. << "value: " << c.value;
  1132. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  1133. }
  1134. }
  1135. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  1136. Server svr;
  1137. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  1138. EXPECT_EQ(req.accept_content_types.size(), 3U);
  1139. EXPECT_EQ(req.accept_content_types[0], "application/json");
  1140. EXPECT_EQ(req.accept_content_types[1], "text/html");
  1141. EXPECT_EQ(req.accept_content_types[2], "*/*");
  1142. res.set_content("ok", "text/plain");
  1143. });
  1144. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  1145. EXPECT_TRUE(false);
  1146. res.set_content("bad request", "text/plain");
  1147. });
  1148. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  1149. auto se = detail::scope_exit([&] {
  1150. svr.stop();
  1151. listen_thread.join();
  1152. ASSERT_FALSE(svr.is_running());
  1153. });
  1154. svr.wait_until_ready();
  1155. Client cli("localhost", PORT);
  1156. {
  1157. auto res = cli.Get(
  1158. "/accept_ok",
  1159. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  1160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1161. EXPECT_EQ(StatusCode::OK_200, res->status);
  1162. }
  1163. {
  1164. auto res = cli.Get("/accept_bad_request",
  1165. Headers{{"Accept", "text/html;q=abc,application/json"}});
  1166. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1167. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  1168. }
  1169. }
  1170. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  1171. Server svr;
  1172. svr.Get("/", [](const Request & /*req*/, Response &res) {
  1173. res.set_content("ok", "text/plain");
  1174. });
  1175. std::atomic<int> start_count{0};
  1176. std::atomic<bool> running_when_called{false};
  1177. svr.set_start_handler([&]() {
  1178. running_when_called = svr.is_running();
  1179. start_count++;
  1180. });
  1181. auto port = svr.bind_to_any_port(HOST);
  1182. std::thread t([&]() { svr.listen_after_bind(); });
  1183. auto se = detail::scope_exit([&] {
  1184. svr.stop();
  1185. t.join();
  1186. ASSERT_FALSE(svr.is_running());
  1187. });
  1188. svr.wait_until_ready();
  1189. // A successful request proves the accept loop is running, which the start
  1190. // handler precedes; so by now the handler must have run exactly once.
  1191. Client cli(HOST, port);
  1192. cli.set_connection_timeout(std::chrono::seconds(5));
  1193. auto res = cli.Get("/");
  1194. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1195. EXPECT_EQ(StatusCode::OK_200, res->status);
  1196. EXPECT_EQ(1, start_count.load());
  1197. EXPECT_TRUE(running_when_called.load());
  1198. }
  1199. TEST(DivideTest, DivideStringTests) {
  1200. auto divide = [](const std::string &str, char d) {
  1201. std::string lhs;
  1202. std::string rhs;
  1203. detail::divide(str, d,
  1204. [&](const char *lhs_data, std::size_t lhs_size,
  1205. const char *rhs_data, std::size_t rhs_size) {
  1206. lhs.assign(lhs_data, lhs_size);
  1207. rhs.assign(rhs_data, rhs_size);
  1208. });
  1209. return std::make_pair(std::move(lhs), std::move(rhs));
  1210. };
  1211. {
  1212. const auto res = divide("", '=');
  1213. EXPECT_EQ(res.first, "");
  1214. EXPECT_EQ(res.second, "");
  1215. }
  1216. {
  1217. const auto res = divide("=", '=');
  1218. EXPECT_EQ(res.first, "");
  1219. EXPECT_EQ(res.second, "");
  1220. }
  1221. {
  1222. const auto res = divide(" ", '=');
  1223. EXPECT_EQ(res.first, " ");
  1224. EXPECT_EQ(res.second, "");
  1225. }
  1226. {
  1227. const auto res = divide("a", '=');
  1228. EXPECT_EQ(res.first, "a");
  1229. EXPECT_EQ(res.second, "");
  1230. }
  1231. {
  1232. const auto res = divide("a=", '=');
  1233. EXPECT_EQ(res.first, "a");
  1234. EXPECT_EQ(res.second, "");
  1235. }
  1236. {
  1237. const auto res = divide("=b", '=');
  1238. EXPECT_EQ(res.first, "");
  1239. EXPECT_EQ(res.second, "b");
  1240. }
  1241. {
  1242. const auto res = divide("a=b", '=');
  1243. EXPECT_EQ(res.first, "a");
  1244. EXPECT_EQ(res.second, "b");
  1245. }
  1246. {
  1247. const auto res = divide("a=b=", '=');
  1248. EXPECT_EQ(res.first, "a");
  1249. EXPECT_EQ(res.second, "b=");
  1250. }
  1251. {
  1252. const auto res = divide("a=b=c", '=');
  1253. EXPECT_EQ(res.first, "a");
  1254. EXPECT_EQ(res.second, "b=c");
  1255. }
  1256. }
  1257. TEST(SplitTest, ParseQueryString) {
  1258. string s = "key1=val1&key2=val2&key3=val3";
  1259. Params dic;
  1260. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1261. [&](const char *b, const char *e) {
  1262. string key, val;
  1263. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1264. if (key.empty()) {
  1265. key.assign(b2, e2);
  1266. } else {
  1267. val.assign(b2, e2);
  1268. }
  1269. });
  1270. dic.emplace(key, val);
  1271. });
  1272. EXPECT_EQ("val1", dic.find("key1")->second);
  1273. EXPECT_EQ("val2", dic.find("key2")->second);
  1274. EXPECT_EQ("val3", dic.find("key3")->second);
  1275. }
  1276. TEST(SplitTest, ParseInvalidQueryTests) {
  1277. {
  1278. string s = " ";
  1279. Params dict;
  1280. detail::parse_query_text(s, dict);
  1281. EXPECT_TRUE(dict.empty());
  1282. }
  1283. {
  1284. string s = " = =";
  1285. Params dict;
  1286. detail::parse_query_text(s, dict);
  1287. EXPECT_TRUE(dict.empty());
  1288. }
  1289. }
  1290. TEST(ParseQueryTest, ParseQueryString) {
  1291. {
  1292. std::string s = "key1=val1&key2=val2&key3=val3";
  1293. Params dic;
  1294. detail::parse_query_text(s, dic);
  1295. EXPECT_EQ("val1", dic.find("key1")->second);
  1296. EXPECT_EQ("val2", dic.find("key2")->second);
  1297. EXPECT_EQ("val3", dic.find("key3")->second);
  1298. }
  1299. {
  1300. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1301. Params dic;
  1302. detail::parse_query_text(s, dic);
  1303. EXPECT_EQ("", dic.find("key1")->second);
  1304. EXPECT_EQ("val1", dic.find("key2")->second);
  1305. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1306. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1307. }
  1308. }
  1309. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1310. Params dic;
  1311. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1312. dic.emplace("key1", "val1");
  1313. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1314. dic.emplace("key2", "val2");
  1315. dic.emplace("key3", "val3");
  1316. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1317. }
  1318. TEST(AppendQueryParamsTest, JoinsAnExistingQuery) {
  1319. Params params;
  1320. params.emplace("a", "1");
  1321. EXPECT_EQ("/p?a=1", append_query_params("/p", params));
  1322. EXPECT_EQ("/p?x=0&a=1", append_query_params("/p?x=0", params));
  1323. EXPECT_EQ("/p?&a=1", append_query_params("/p?", params));
  1324. EXPECT_EQ("?x=0&a=1", append_query_params("?x=0", params));
  1325. // Long enough to overflow the stack when matched with std::regex.
  1326. auto long_query = std::string(CPPHTTPLIB_MAX_LINE_LENGTH, 'x');
  1327. EXPECT_EQ("/p?" + long_query + "&a=1",
  1328. append_query_params("/p?" + long_query, params));
  1329. }
  1330. // Joins every entry of a Headers or Params into "key=value " so a whole
  1331. // traversal can be compared in one assertion. Both are instantiations of the
  1332. // same insertion-ordered container, so one helper serves both.
  1333. template <typename Map> static std::string entries_to_string(const Map &m) {
  1334. std::string s;
  1335. for (const auto &entry : m) {
  1336. s += entry.first + "=" + entry.second + " ";
  1337. }
  1338. return s;
  1339. }
  1340. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1341. // Params used to be a std::multimap, which sorted by name and handed the
  1342. // caller's query back alphabetised. A client signing its query string could
  1343. // not reproduce the order it asked for.
  1344. Params dic;
  1345. dic.emplace("zulu", "1");
  1346. dic.emplace("alpha", "2");
  1347. dic.emplace("mike", "3");
  1348. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1349. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1350. }
  1351. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1352. Params dic;
  1353. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1354. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1355. }
  1356. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1357. Request req;
  1358. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1359. req.params);
  1360. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1361. EXPECT_EQ("first", req.get_param_value("tag"));
  1362. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1363. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1364. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1365. EXPECT_EQ("", req.get_param_value("tag", 3));
  1366. }
  1367. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1368. // Params shares its container with Headers, which matches field names
  1369. // case-insensitively. Parameter names must not pick that up.
  1370. Params dic;
  1371. dic.emplace("Key", "upper");
  1372. dic.emplace("key", "lower");
  1373. EXPECT_EQ(2U, dic.size());
  1374. EXPECT_EQ(1U, dic.count("Key"));
  1375. EXPECT_EQ(1U, dic.count("key"));
  1376. EXPECT_EQ("upper", dic.find("Key")->second);
  1377. EXPECT_EQ("lower", dic.find("key")->second);
  1378. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1379. }
  1380. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1381. Server svr;
  1382. std::string order;
  1383. svr.Get("/order", [&](const Request &req, Response &res) {
  1384. order = entries_to_string(req.params);
  1385. res.set_content("ok", "text/plain");
  1386. });
  1387. auto port = svr.bind_to_any_port(HOST);
  1388. thread t = thread([&] { svr.listen_after_bind(); });
  1389. auto se = detail::scope_exit([&] {
  1390. svr.stop();
  1391. t.join();
  1392. ASSERT_FALSE(svr.is_running());
  1393. });
  1394. svr.wait_until_ready();
  1395. Client cli(HOST, port);
  1396. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1397. ASSERT_TRUE(res);
  1398. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1399. }
  1400. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1401. Server svr;
  1402. std::string field_order, file_order;
  1403. svr.Post("/order", [&](const Request &req, Response &res) {
  1404. for (const auto &field : req.form.fields) {
  1405. field_order += field.first + "=" + field.second.content + " ";
  1406. }
  1407. for (const auto &file : req.form.files) {
  1408. file_order += file.first + "=" + file.second.filename + " ";
  1409. }
  1410. res.set_content("ok", "text/plain");
  1411. });
  1412. auto port = svr.bind_to_any_port(HOST);
  1413. thread t = thread([&] { svr.listen_after_bind(); });
  1414. auto se = detail::scope_exit([&] {
  1415. svr.stop();
  1416. t.join();
  1417. ASSERT_FALSE(svr.is_running());
  1418. });
  1419. svr.wait_until_ready();
  1420. UploadFormDataItems items = {
  1421. {"zulu", "1", "", ""},
  1422. {"alpha", "2", "", ""},
  1423. {"mike", "3", "", ""},
  1424. {"zebra", "z", "z.txt", "text/plain"},
  1425. {"apple", "a", "a.txt", "text/plain"},
  1426. };
  1427. Client cli(HOST, port);
  1428. auto res = cli.Post("/order", items);
  1429. ASSERT_TRUE(res);
  1430. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1431. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1432. }
  1433. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1434. Server svr;
  1435. std::vector<std::string> values;
  1436. std::string first, second, out_of_range, order;
  1437. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1438. values = req.form.get_fields("tag");
  1439. first = req.form.get_field("tag", 0);
  1440. second = req.form.get_field("tag", 1);
  1441. out_of_range = req.form.get_field("tag", 2);
  1442. for (const auto &field : req.form.fields) {
  1443. order += field.first + "=" + field.second.content + " ";
  1444. }
  1445. res.set_content("ok", "text/plain");
  1446. });
  1447. auto port = svr.bind_to_any_port(HOST);
  1448. thread t = thread([&] { svr.listen_after_bind(); });
  1449. auto se = detail::scope_exit([&] {
  1450. svr.stop();
  1451. t.join();
  1452. ASSERT_FALSE(svr.is_running());
  1453. });
  1454. svr.wait_until_ready();
  1455. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1456. // not adjacent in the container.
  1457. UploadFormDataItems items = {
  1458. {"tag", "first", "", ""},
  1459. {"other", "x", "", ""},
  1460. {"tag", "second", "", ""},
  1461. };
  1462. Client cli(HOST, port);
  1463. auto res = cli.Post("/repeated", items);
  1464. ASSERT_TRUE(res);
  1465. ASSERT_EQ(2U, values.size());
  1466. EXPECT_EQ("first", values[0]);
  1467. EXPECT_EQ("second", values[1]);
  1468. EXPECT_EQ("first", first);
  1469. EXPECT_EQ("second", second);
  1470. // std::multimap already kept entries sharing a name in insertion order, so
  1471. // everything above passes without this change too. The whole traversal is
  1472. // what tells the two apart: sorting by name would hoist "other" to the front
  1473. // and the two "tag" parts would end up adjacent.
  1474. EXPECT_EQ("tag=first other=x tag=second ", order);
  1475. // Advancing past the last entry of a name used to run off the container;
  1476. // the container's saturating increment makes it return the default instead.
  1477. EXPECT_EQ("", out_of_range);
  1478. }
  1479. TEST(MultipartFormDataTest, BackslashesInNamesSurvive) {
  1480. Server svr;
  1481. std::string file_names;
  1482. svr.Post("/upload", [&](const Request &req, Response &res) {
  1483. for (const auto &file : req.form.files) {
  1484. file_names += file.first + "|" + file.second.filename + " ";
  1485. }
  1486. res.set_content("ok", "text/plain");
  1487. });
  1488. auto port = svr.bind_to_any_port(HOST);
  1489. thread t = thread([&] { svr.listen_after_bind(); });
  1490. auto se = detail::scope_exit([&] {
  1491. svr.stop();
  1492. t.join();
  1493. ASSERT_FALSE(svr.is_running());
  1494. });
  1495. svr.wait_until_ready();
  1496. // A trailing backslash would otherwise escape the closing quote.
  1497. UploadFormDataItems items = {
  1498. {"dir\\", "x", "a.txt", "text/plain"},
  1499. {"b", "y", "a\\\\b.txt", "text/plain"},
  1500. };
  1501. Client cli(HOST, port);
  1502. auto res = cli.Post("/upload", items);
  1503. ASSERT_TRUE(res);
  1504. EXPECT_EQ("dir\\|a.txt b|a\\\\b.txt ", file_names);
  1505. }
  1506. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1507. // Server::read_content() keeps a FormFields::iterator alive across the
  1508. // content callbacks that fill the part it points at. The container is
  1509. // vector-backed, so a later emplace can reallocate and invalidate an older
  1510. // iterator; 64 parts grow the vector through seven reallocations, which
  1511. // checks that every part's content still lands in its own entry.
  1512. const size_t part_count = 64;
  1513. // One formula for both the parts sent and the values expected back, so the
  1514. // two cannot drift apart.
  1515. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1516. auto content_of = [](size_t i) {
  1517. return std::string(64, static_cast<char>('a' + (i % 26)));
  1518. };
  1519. Server svr;
  1520. std::vector<std::pair<std::string, std::string>> received;
  1521. svr.Post("/many", [&](const Request &req, Response &res) {
  1522. for (const auto &field : req.form.fields) {
  1523. received.emplace_back(field.first, field.second.content);
  1524. }
  1525. res.set_content("ok", "text/plain");
  1526. });
  1527. auto port = svr.bind_to_any_port(HOST);
  1528. thread t = thread([&] { svr.listen_after_bind(); });
  1529. auto se = detail::scope_exit([&] {
  1530. svr.stop();
  1531. t.join();
  1532. ASSERT_FALSE(svr.is_running());
  1533. });
  1534. svr.wait_until_ready();
  1535. UploadFormDataItems items;
  1536. for (size_t i = 0; i < part_count; i++) {
  1537. items.push_back({name_of(i), content_of(i), "", ""});
  1538. }
  1539. Client cli(HOST, port);
  1540. auto res = cli.Post("/many", items);
  1541. ASSERT_TRUE(res);
  1542. ASSERT_EQ(part_count, received.size());
  1543. for (size_t i = 0; i < part_count; i++) {
  1544. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1545. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1546. }
  1547. }
  1548. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1549. string content_type = "multipart/form-data; boundary=something";
  1550. string boundary;
  1551. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1552. EXPECT_TRUE(ret);
  1553. EXPECT_EQ(boundary, "something");
  1554. }
  1555. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1556. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1557. string boundary;
  1558. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1559. EXPECT_TRUE(ret);
  1560. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1561. }
  1562. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1563. string content_type =
  1564. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1565. string boundary;
  1566. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1567. EXPECT_TRUE(ret);
  1568. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1569. }
  1570. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1571. string content_type =
  1572. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1573. string boundary;
  1574. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1575. EXPECT_TRUE(ret);
  1576. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1577. }
  1578. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1579. const string boundary(70, 'a');
  1580. string content_type = "multipart/form-data; boundary=" + boundary;
  1581. string parsed;
  1582. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1583. EXPECT_TRUE(ret);
  1584. EXPECT_EQ(parsed, boundary);
  1585. }
  1586. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1587. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1588. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1589. string parsed;
  1590. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1591. EXPECT_FALSE(ret);
  1592. }
  1593. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1594. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1595. // is 72 characters on the wire and still valid.
  1596. const string boundary(70, 'a');
  1597. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1598. string parsed;
  1599. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1600. EXPECT_EQ(parsed, boundary);
  1601. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1602. parsed.clear();
  1603. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1604. }
  1605. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1606. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1607. // The parameter parser must not treat that '=' as the key/value separator.
  1608. string content_type =
  1609. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1610. "charset=UTF-8";
  1611. string parsed;
  1612. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1613. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1614. }
  1615. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1616. // A ';' inside the quoted-string is part of the value, not a parameter
  1617. // separator, so it must not truncate the boundary.
  1618. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1619. string parsed;
  1620. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1621. EXPECT_EQ(parsed, "a;b");
  1622. }
  1623. TEST(ParseMultipartBoundaryTest, QuotedPairsAreUnescaped) {
  1624. string parsed;
  1625. EXPECT_TRUE(detail::parse_multipart_boundary(
  1626. "multipart/form-data; boundary=\"a\\\\b\"", parsed));
  1627. EXPECT_EQ("a\\b", parsed);
  1628. EXPECT_TRUE(detail::parse_multipart_boundary(
  1629. "multipart/form-data; boundary=\"a\\\"b\"", parsed));
  1630. EXPECT_EQ("a\"b", parsed);
  1631. }
  1632. TEST(ParseDispositionParamsTest, QuotedValues) {
  1633. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1634. // ';' and '=' are ordinary characters inside one.
  1635. struct {
  1636. const char *value;
  1637. std::vector<std::pair<const char *, const char *>> expected;
  1638. } cases[] = {
  1639. {"name=\"file1\"; filename=\"a.txt\"",
  1640. {{"name", "file1"}, {"filename", "a.txt"}}},
  1641. // Whitespace around '=' and ';' is still trimmed
  1642. {"name=\"file2\" ;filename = \"a.html\"",
  1643. {{"name", "file2"}, {"filename", "a.html"}}},
  1644. // '=' inside the value used to leave only the text after the last one
  1645. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1646. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1647. {"name=\"x=y\"", {{"name", "x=y"}}},
  1648. // ';' inside the value used to truncate the pair and leave a bogus one
  1649. {"name=\"file3\"; filename=\"a;b.txt\"",
  1650. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1651. // An unquoted value keeps working, and so does filename*
  1652. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1653. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1654. // A parameter with no key is dropped rather than turned into one whose
  1655. // key is the value
  1656. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1657. // An escaped quote does not end the value
  1658. {"name=\"a\\\"; filename=evil.php\"",
  1659. {{"name", "a\"; filename=evil.php"}}},
  1660. // Other backslashes, as in a Windows path, are kept
  1661. {"name=\"f\"; filename=\"C:\\dir\\a.txt\"",
  1662. {{"name", "f"}, {"filename", "C:\\dir\\a.txt"}}},
  1663. };
  1664. for (const auto &c : cases) {
  1665. Params params;
  1666. detail::parse_disposition_params(c.value, params);
  1667. for (const auto &kv : c.expected) {
  1668. auto it = params.find(kv.first);
  1669. ASSERT_NE(it, params.end())
  1670. << "value: " << c.value << ", key: " << kv.first;
  1671. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1672. }
  1673. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1674. }
  1675. }
  1676. TEST(MultipartFormDataTest, PartArrivingAByteAtATime) {
  1677. Server svr;
  1678. std::string filename;
  1679. std::string content;
  1680. svr.Post("/upload", [&](const Request &req, Response &) {
  1681. const auto &file = req.form.get_file("file");
  1682. filename = file.filename;
  1683. content = file.content;
  1684. });
  1685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  1686. auto se = detail::scope_exit([&] {
  1687. svr.stop();
  1688. thread.join();
  1689. ASSERT_FALSE(svr.is_running());
  1690. });
  1691. svr.wait_until_ready();
  1692. std::string body = "--B\r\n"
  1693. "Content-Disposition: form-data; name=\"file\"; "
  1694. "filename=\"a.txt\"\r\n"
  1695. "Content-Type: text/plain\r\n"
  1696. "\r\n"
  1697. "hello\r\n"
  1698. "--B--\r\n";
  1699. Client cli(HOST, PORT);
  1700. auto res = cli.Post(
  1701. "/upload",
  1702. [&](size_t offset, DataSink &sink) {
  1703. if (offset < body.size()) {
  1704. sink.write(&body[offset], 1);
  1705. } else {
  1706. sink.done();
  1707. }
  1708. return true;
  1709. },
  1710. "multipart/form-data; boundary=B");
  1711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1712. EXPECT_EQ(StatusCode::OK_200, res->status);
  1713. EXPECT_EQ("a.txt", filename);
  1714. EXPECT_EQ("hello", content);
  1715. }
  1716. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1717. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1718. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1719. Server svr;
  1720. std::string field_value, file_name, file_filename;
  1721. bool has_field = false, has_file = false;
  1722. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1723. has_field = req.form.has_field("x=y");
  1724. field_value = req.form.get_field("x=y");
  1725. has_file = req.form.has_file("file1");
  1726. const auto &file = req.form.get_file("file1");
  1727. file_name = file.name;
  1728. file_filename = file.filename;
  1729. res.set_content("ok", "text/plain");
  1730. });
  1731. auto port = svr.bind_to_any_port(HOST);
  1732. thread t = thread([&] { svr.listen_after_bind(); });
  1733. auto se = detail::scope_exit([&] {
  1734. svr.stop();
  1735. t.join();
  1736. ASSERT_FALSE(svr.is_running());
  1737. });
  1738. svr.wait_until_ready();
  1739. UploadFormDataItems items = {
  1740. {"x=y", "field-value", "", ""},
  1741. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1742. };
  1743. Client cli(HOST, port);
  1744. auto res = cli.Post("/quoted", items);
  1745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1746. ASSERT_EQ(StatusCode::OK_200, res->status);
  1747. EXPECT_TRUE(has_field);
  1748. EXPECT_EQ("field-value", field_value);
  1749. EXPECT_TRUE(has_file);
  1750. EXPECT_EQ("file1", file_name);
  1751. EXPECT_EQ("a;b=report.pdf", file_filename);
  1752. }
  1753. TEST(GetHeaderValueTest, DefaultValue) {
  1754. Headers headers = {{"Dummy", "Dummy"}};
  1755. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1756. EXPECT_STREQ("text/plain", val);
  1757. }
  1758. TEST(GetHeaderValueTest, DefaultValueInt) {
  1759. Headers headers = {{"Dummy", "Dummy"}};
  1760. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1761. EXPECT_EQ(100ull, val);
  1762. }
  1763. TEST(GetHeaderValueTest, RegularValue) {
  1764. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1765. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1766. EXPECT_STREQ("text/html", val);
  1767. }
  1768. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1769. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1770. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1771. EXPECT_STREQ("text/html", val);
  1772. }
  1773. TEST(GetHeaderValueTest, SetContent) {
  1774. Response res;
  1775. res.set_content("html", "text/html");
  1776. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1777. res.set_content("text", "text/plain");
  1778. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1779. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1780. }
  1781. TEST(GetHeaderValueTest, RegularValueInt) {
  1782. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1783. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1784. EXPECT_EQ(100ull, val);
  1785. }
  1786. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1787. Headers headers = {{"Content-Length", "x"}};
  1788. auto is_invalid_value = false;
  1789. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1790. is_invalid_value);
  1791. EXPECT_EQ(0ull, val);
  1792. EXPECT_TRUE(is_invalid_value);
  1793. }
  1794. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1795. // An all-digit value that overflows size_t must be reported as invalid, not
  1796. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1797. // a large length to a small one on 32-bit builds, leaving the framing length
  1798. // wrong while is_invalid_value stayed false.
  1799. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1800. auto is_invalid_value = false;
  1801. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1802. is_invalid_value);
  1803. EXPECT_TRUE(is_invalid_value);
  1804. // A well-formed length is unaffected.
  1805. Headers ok = {{"Content-Length", "1234"}};
  1806. is_invalid_value = false;
  1807. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1808. is_invalid_value);
  1809. EXPECT_EQ(1234ull, val);
  1810. EXPECT_FALSE(is_invalid_value);
  1811. }
  1812. TEST(GetHeaderValueTest, Range) {
  1813. {
  1814. Headers headers = {make_range_header({{1, -1}})};
  1815. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1816. EXPECT_STREQ("bytes=1-", val);
  1817. }
  1818. {
  1819. Headers headers = {make_range_header({{-1, 1}})};
  1820. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1821. EXPECT_STREQ("bytes=-1", val);
  1822. }
  1823. {
  1824. Headers headers = {make_range_header({{1, 10}})};
  1825. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1826. EXPECT_STREQ("bytes=1-10", val);
  1827. }
  1828. {
  1829. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1830. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1831. EXPECT_STREQ("bytes=1-10, 100-", val);
  1832. }
  1833. {
  1834. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1835. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1836. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1837. }
  1838. {
  1839. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1840. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1841. EXPECT_STREQ("bytes=0-0, -1", val);
  1842. }
  1843. }
  1844. TEST(BearerTokenAuthTest, SchemeValidation) {
  1845. // A value shorter than "Bearer " must not throw from the fixed-length
  1846. // substr, and a non-Bearer scheme must not be reported as a token.
  1847. struct {
  1848. const char *value;
  1849. const char *expected;
  1850. } cases[] = {
  1851. {"x", ""},
  1852. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1853. {"Bearer abc123", "abc123"},
  1854. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1855. };
  1856. for (const auto &c : cases) {
  1857. Request req;
  1858. req.set_header("Authorization", c.value);
  1859. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1860. }
  1861. }
  1862. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1863. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1864. // to depend on the standard library (libstdc++ handed back duplicates in
  1865. // reverse insertion order, libc++ in insertion order).
  1866. Request req;
  1867. req.set_header("Accept-Encoding", "gzip");
  1868. req.set_header("Accept-Encoding", "deflate");
  1869. req.set_header("Accept-Encoding", "br");
  1870. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1871. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1872. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1873. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1874. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1875. }
  1876. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1877. Request req;
  1878. req.set_header("X-Test", "only");
  1879. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1880. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1881. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1882. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1883. }
  1884. TEST(HeadersOrderTest, HugeIdYieldsDefault) {
  1885. Request req;
  1886. req.set_header("X-First", "1");
  1887. req.set_header("X-Test", "2");
  1888. req.params.emplace("first", "1");
  1889. req.params.emplace("test", "2");
  1890. req.form.fields.emplace("first", FormField{"first", "1", {}});
  1891. req.form.fields.emplace("test", FormField{"test", "2", {}});
  1892. req.form.files.emplace("first", FormData{"first", "1", "", "", {}});
  1893. req.form.files.emplace("test", FormData{"test", "2", "", "", {}});
  1894. // The second one is negative when read as a signed value
  1895. const auto max_id = (std::numeric_limits<size_t>::max)();
  1896. for (auto id : {max_id / 2, max_id}) {
  1897. EXPECT_EQ("def", req.get_header_value("X-Test", "def", id));
  1898. EXPECT_EQ(7U, req.get_header_value_u64("X-Test", 7, id));
  1899. EXPECT_EQ("", req.get_param_value("test", id));
  1900. EXPECT_EQ("", req.form.get_field("test", id));
  1901. EXPECT_EQ("", req.form.get_file("test", id).content);
  1902. }
  1903. }
  1904. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1905. Headers headers;
  1906. headers.emplace("Host", "example.com");
  1907. headers.emplace("Accept-Encoding", "gzip");
  1908. headers.emplace("User-Agent", "test");
  1909. headers.emplace("Accept-Encoding", "deflate");
  1910. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1911. "Accept-Encoding=deflate ",
  1912. entries_to_string(headers));
  1913. }
  1914. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1915. Headers headers = {{"Content-Type", "text/html"},
  1916. {"CONTENT-TYPE", "text/xml"}};
  1917. EXPECT_EQ(2U, headers.count("content-type"));
  1918. auto it = headers.find("content-type");
  1919. ASSERT_TRUE(it != headers.end());
  1920. EXPECT_EQ("text/html", it->second);
  1921. }
  1922. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1923. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1924. // drop only those fields and leave everything positioned between them.
  1925. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1926. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1927. auto rng = headers.equal_range("a");
  1928. headers.erase(rng.first, rng.second);
  1929. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1930. }
  1931. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1932. Headers headers = {
  1933. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1934. EXPECT_EQ(3U, headers.erase("A"));
  1935. EXPECT_EQ(0U, headers.count("A"));
  1936. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1937. }
  1938. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1939. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1940. headers.emplace_front("Host", "example.com");
  1941. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1942. entries_to_string(headers));
  1943. }
  1944. TEST(ParseHeaderValueTest, Range) {
  1945. {
  1946. Ranges ranges;
  1947. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1948. EXPECT_TRUE(ret);
  1949. EXPECT_EQ((Ranges{{1, -1}}), ranges);
  1950. }
  1951. {
  1952. Ranges ranges;
  1953. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1954. EXPECT_TRUE(ret);
  1955. EXPECT_EQ((Ranges{{-1, 1}}), ranges);
  1956. }
  1957. {
  1958. Ranges ranges;
  1959. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1960. EXPECT_TRUE(ret);
  1961. EXPECT_EQ((Ranges{{1, 10}}), ranges);
  1962. }
  1963. {
  1964. Ranges ranges;
  1965. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1966. EXPECT_FALSE(ret);
  1967. }
  1968. {
  1969. Ranges ranges;
  1970. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1971. EXPECT_TRUE(ret);
  1972. EXPECT_EQ((Ranges{{1, 10}, {100, -1}}), ranges);
  1973. }
  1974. {
  1975. Ranges ranges;
  1976. auto ret =
  1977. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1978. EXPECT_TRUE(ret);
  1979. EXPECT_EQ((Ranges{{1, 10}, {100, 200}, {300, 400}}), ranges);
  1980. }
  1981. {
  1982. Ranges ranges;
  1983. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1984. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1985. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1986. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1987. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1988. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1989. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1990. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1991. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1992. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1993. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1994. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1995. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1996. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1997. EXPECT_FALSE(
  1998. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1999. EXPECT_TRUE(ranges.empty());
  2000. }
  2001. {
  2002. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  2003. // remainder of the representation, so it stays accepted.
  2004. Ranges ranges;
  2005. auto ret =
  2006. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  2007. EXPECT_TRUE(ret);
  2008. ASSERT_EQ(1u, ranges.size());
  2009. EXPECT_EQ(0, ranges[0].first);
  2010. EXPECT_EQ(-1, ranges[0].second);
  2011. }
  2012. // RFC 9110 14.1: range unit names are case-insensitive.
  2013. for (const auto &s : {"Bytes=1-10", "BYTES=1-10", "bYtEs=1-10"}) {
  2014. Ranges ranges;
  2015. EXPECT_TRUE(detail::parse_range_header(s, ranges)) << s;
  2016. EXPECT_EQ((Ranges{{1, 10}}), ranges) << s;
  2017. }
  2018. }
  2019. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  2020. Request req;
  2021. req.set_header("Accept-Encoding", "gzip");
  2022. Response res;
  2023. res.set_header("Content-Type", "text/plain");
  2024. auto ret = detail::encoding_type(req, res);
  2025. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2026. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2027. #else
  2028. EXPECT_TRUE(ret == detail::EncodingType::None);
  2029. #endif
  2030. }
  2031. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  2032. Request req;
  2033. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  2034. Response res;
  2035. res.set_header("Content-Type", "text/plain");
  2036. auto ret = detail::encoding_type(req, res);
  2037. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2038. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2039. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2040. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2041. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2042. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2043. #else
  2044. EXPECT_TRUE(ret == detail::EncodingType::None);
  2045. #endif
  2046. }
  2047. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  2048. Request req;
  2049. req.set_header("Accept-Encoding",
  2050. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  2051. Response res;
  2052. res.set_header("Content-Type", "text/plain");
  2053. auto ret = detail::encoding_type(req, res);
  2054. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2055. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2056. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2057. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2058. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2059. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2060. #else
  2061. EXPECT_TRUE(ret == detail::EncodingType::None);
  2062. #endif
  2063. }
  2064. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  2065. // All supported encodings rejected with q=0 should return None
  2066. Request req;
  2067. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  2068. Response res;
  2069. res.set_header("Content-Type", "text/plain");
  2070. auto ret = detail::encoding_type(req, res);
  2071. EXPECT_TRUE(ret == detail::EncodingType::None);
  2072. }
  2073. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  2074. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  2075. Request req;
  2076. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  2077. Response res;
  2078. res.set_header("Content-Type", "text/plain");
  2079. auto ret = detail::encoding_type(req, res);
  2080. EXPECT_TRUE(ret == detail::EncodingType::None);
  2081. }
  2082. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  2083. Request req;
  2084. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  2085. Response res;
  2086. res.set_header("Content-Type", "text/plain");
  2087. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  2088. }
  2089. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  2090. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  2091. Request req;
  2092. req.set_header("Accept-Encoding", "x-gzip;q=0");
  2093. Response res;
  2094. res.set_header("Content-Type", "text/plain");
  2095. auto ret = detail::encoding_type(req, res);
  2096. EXPECT_TRUE(ret == detail::EncodingType::None);
  2097. }
  2098. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  2099. // RFC 7231: Accept-Encoding values are case-insensitive
  2100. Request req;
  2101. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  2102. Response res;
  2103. res.set_header("Content-Type", "text/plain");
  2104. auto ret = detail::encoding_type(req, res);
  2105. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  2106. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2107. #elif CPPHTTPLIB_ZLIB_SUPPORT
  2108. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2109. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2110. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2111. #else
  2112. EXPECT_TRUE(ret == detail::EncodingType::None);
  2113. #endif
  2114. }
  2115. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  2116. // q value should determine priority, not hardcoded order
  2117. Request req;
  2118. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  2119. Response res;
  2120. res.set_header("Content-Type", "text/plain");
  2121. auto ret = detail::encoding_type(req, res);
  2122. // gzip has highest q=1.0, so it should be selected even though
  2123. // br and zstd are also supported
  2124. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  2125. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  2126. #elif CPPHTTPLIB_ZSTD_SUPPORT
  2127. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  2128. #elif CPPHTTPLIB_BROTLI_SUPPORT
  2129. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  2130. #else
  2131. EXPECT_TRUE(ret == detail::EncodingType::None);
  2132. #endif
  2133. }
  2134. TEST(BufferStreamTest, read) {
  2135. detail::BufferStream strm1;
  2136. Stream &strm = strm1;
  2137. EXPECT_EQ(5, strm.write("hello"));
  2138. char buf[512];
  2139. EXPECT_EQ(2, strm.read(buf, 2));
  2140. EXPECT_EQ('h', buf[0]);
  2141. EXPECT_EQ('e', buf[1]);
  2142. EXPECT_EQ(2, strm.read(buf, 2));
  2143. EXPECT_EQ('l', buf[0]);
  2144. EXPECT_EQ('l', buf[1]);
  2145. EXPECT_EQ(1, strm.read(buf, 1));
  2146. EXPECT_EQ('o', buf[0]);
  2147. EXPECT_EQ(0, strm.read(buf, 1));
  2148. }
  2149. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  2150. auto host = "www.httpwatch.com";
  2151. auto ip = hosted_at(host);
  2152. EXPECT_EQ("23.96.13.243", ip);
  2153. std::vector<std::string> addrs;
  2154. hosted_at(host, addrs);
  2155. EXPECT_EQ(1u, addrs.size());
  2156. }
  2157. #if 0 // It depends on each test environment...
  2158. TEST(HostnameToIPConversionTest, YouTube_Online) {
  2159. auto host = "www.youtube.com";
  2160. std::vector<std::string> addrs;
  2161. hosted_at(host, addrs);
  2162. EXPECT_EQ(20u, addrs.size());
  2163. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  2164. EXPECT_TRUE(it != addrs.end());
  2165. }
  2166. #endif
  2167. class ChunkedEncodingTest : public ::testing::Test {
  2168. protected:
  2169. ChunkedEncodingTest()
  2170. : cli_(HOST, PORT)
  2171. #ifdef CPPHTTPLIB_SSL_ENABLED
  2172. ,
  2173. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  2174. #endif
  2175. {
  2176. cli_.set_connection_timeout(2);
  2177. #ifdef CPPHTTPLIB_SSL_ENABLED
  2178. cli_.enable_server_certificate_verification(false);
  2179. #endif
  2180. }
  2181. virtual void SetUp() {
  2182. read_file("./image.jpg", image_data_);
  2183. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  2184. res.set_content("Hello World!", "text/plain");
  2185. });
  2186. svr_.Get(
  2187. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  2188. res.set_chunked_content_provider(
  2189. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  2190. size_t remaining = image_data_.size() - offset;
  2191. if (remaining == 0) {
  2192. sink.done();
  2193. } else {
  2194. constexpr size_t CHUNK_SIZE = 1024;
  2195. size_t send_size = std::min(CHUNK_SIZE, remaining);
  2196. sink.write(&image_data_[offset], send_size);
  2197. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  2198. }
  2199. return true;
  2200. });
  2201. });
  2202. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  2203. svr_.wait_until_ready();
  2204. }
  2205. virtual void TearDown() {
  2206. svr_.stop();
  2207. if (!request_threads_.empty()) {
  2208. std::this_thread::sleep_for(std::chrono::seconds(1));
  2209. for (auto &t : request_threads_) {
  2210. t.join();
  2211. }
  2212. }
  2213. t_.join();
  2214. }
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. SSLClient cli_;
  2217. SSLServer svr_;
  2218. #else
  2219. Client cli_;
  2220. Server svr_;
  2221. #endif
  2222. thread t_;
  2223. std::vector<thread> request_threads_;
  2224. std::string image_data_;
  2225. };
  2226. TEST_F(ChunkedEncodingTest, NormalGet) {
  2227. auto res = cli_.Get("/chunked");
  2228. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2229. std::string out;
  2230. read_file("./image.jpg", out);
  2231. EXPECT_EQ(StatusCode::OK_200, res->status);
  2232. EXPECT_EQ(out, res->body);
  2233. }
  2234. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  2235. std::string body;
  2236. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  2237. body.append(data, data_length);
  2238. return true;
  2239. });
  2240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2241. std::string out;
  2242. read_file("./image.jpg", out);
  2243. EXPECT_EQ(StatusCode::OK_200, res->status);
  2244. EXPECT_EQ(out, body);
  2245. }
  2246. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  2247. std::string body;
  2248. auto res = cli_.Get(
  2249. "/chunked",
  2250. [&](const Response &response) {
  2251. EXPECT_EQ(StatusCode::OK_200, response.status);
  2252. return true;
  2253. },
  2254. [&](const char *data, size_t data_length) {
  2255. body.append(data, data_length);
  2256. return true;
  2257. });
  2258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2259. std::string out;
  2260. read_file("./image.jpg", out);
  2261. EXPECT_EQ(StatusCode::OK_200, res->status);
  2262. EXPECT_EQ(out, body);
  2263. }
  2264. TEST(RangeTest, FromHTTPBin_Online) {
  2265. auto host = "httpbingo.org";
  2266. auto path = std::string{"/range/32"};
  2267. #ifdef CPPHTTPLIB_SSL_ENABLED
  2268. auto port = 443;
  2269. SSLClient cli(host, port);
  2270. #else
  2271. auto port = 80;
  2272. Client cli(host, port);
  2273. #endif
  2274. cli.set_connection_timeout(5);
  2275. {
  2276. auto res = cli.Get(path);
  2277. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2278. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2279. EXPECT_EQ(StatusCode::OK_200, res->status);
  2280. }
  2281. {
  2282. Headers headers = {make_range_header({{1, -1}})};
  2283. auto res = cli.Get(path, headers);
  2284. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2285. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2286. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2287. }
  2288. {
  2289. Headers headers = {make_range_header({{1, 10}})};
  2290. auto res = cli.Get(path, headers);
  2291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2292. EXPECT_EQ("bcdefghijk", res->body);
  2293. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  2294. }
  2295. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  2296. // entire resource, while the original httpbin returned 200. Both are
  2297. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  2298. {
  2299. Headers headers = {make_range_header({{0, 31}})};
  2300. auto res = cli.Get(path, headers);
  2301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2302. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2303. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2304. res->status == StatusCode::PartialContent_206);
  2305. }
  2306. {
  2307. Headers headers = {make_range_header({{0, -1}})};
  2308. auto res = cli.Get(path, headers);
  2309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2310. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2311. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2312. res->status == StatusCode::PartialContent_206);
  2313. }
  2314. // go-httpbin returns 206 with clamped range for over-range requests,
  2315. // while the original httpbin returned 416. Both behaviors are observed
  2316. // in real servers, so we only verify the request succeeds.
  2317. {
  2318. Headers headers = {make_range_header({{0, 32}})};
  2319. auto res = cli.Get(path, headers);
  2320. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2321. }
  2322. }
  2323. TEST(RangeTest, IgnoredForPost) {
  2324. Server svr;
  2325. svr.Post("/", [](const Request &, Response &res) {
  2326. res.set_content("abcdefg", "text/plain");
  2327. });
  2328. auto port = svr.bind_to_any_port(HOST);
  2329. ASSERT_GT(port, 0);
  2330. thread t = thread([&] { svr.listen_after_bind(); });
  2331. auto se = detail::scope_exit([&] {
  2332. svr.stop();
  2333. t.join();
  2334. ASSERT_FALSE(svr.is_running());
  2335. });
  2336. svr.wait_until_ready();
  2337. Client cli(HOST, port);
  2338. for (auto range : {"bytes=1-2", "bytes=x"}) {
  2339. auto res = cli.Post("/", Headers{{"Range", range}});
  2340. ASSERT_TRUE(res) << range << ": " << to_string(res.error());
  2341. EXPECT_EQ(StatusCode::OK_200, res->status) << range;
  2342. EXPECT_EQ("abcdefg", res->body) << range;
  2343. }
  2344. }
  2345. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2346. auto host = "unresolvableaddress.local";
  2347. auto path = std::string{"/"};
  2348. #ifdef CPPHTTPLIB_SSL_ENABLED
  2349. auto port = 443;
  2350. SSLClient cli(host, port);
  2351. #else
  2352. auto port = 80;
  2353. Client cli(host, port);
  2354. #endif
  2355. cli.set_connection_timeout(1);
  2356. {
  2357. auto res = cli.Get(path);
  2358. ASSERT_FALSE(res);
  2359. }
  2360. std::this_thread::sleep_for(std::chrono::seconds(8));
  2361. }
  2362. #if defined(__linux__) && defined(__GLIBC__) && \
  2363. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2364. // Forward declaration: in split builds split.py strips `inline` and moves the
  2365. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2366. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2367. // against the symbol in both header-only and split builds.
  2368. namespace httplib {
  2369. namespace detail {
  2370. int getaddrinfo_with_timeout(const char *node, const char *service,
  2371. const struct addrinfo *hints,
  2372. struct addrinfo **res, time_t timeout_sec);
  2373. } // namespace detail
  2374. } // namespace httplib
  2375. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2376. //
  2377. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2378. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2379. // gai_suspend() call hits the connection timeout the function calls
  2380. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2381. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2382. // still alive and still references the now-destroyed stack frame.
  2383. //
  2384. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2385. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2386. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2387. // and runs them in a container.
  2388. namespace {
  2389. bool should_run_issue_2431_tests() {
  2390. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2391. return v && *v && std::string(v) != "0";
  2392. }
  2393. std::string unique_unresolvable_host(int n) {
  2394. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2395. // glibc still asks the configured nameserver — which is exactly the path
  2396. // we want to exercise. A unique label per call avoids the resolver cache.
  2397. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2398. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2399. std::to_string(n) + ".invalid";
  2400. }
  2401. } // namespace
  2402. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2403. if (!should_run_issue_2431_tests()) {
  2404. GTEST_SKIP()
  2405. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2406. }
  2407. for (int i = 0; i < 8; ++i) {
  2408. struct addrinfo hints;
  2409. memset(&hints, 0, sizeof(hints));
  2410. hints.ai_family = AF_UNSPEC;
  2411. hints.ai_socktype = SOCK_STREAM;
  2412. auto host = unique_unresolvable_host(i);
  2413. struct addrinfo *result = nullptr;
  2414. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2415. &result, /*timeout_sec=*/1);
  2416. if (rc == 0 && result) { freeaddrinfo(result); }
  2417. }
  2418. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2419. // stack region they still believe holds their gaicb.
  2420. std::this_thread::sleep_for(std::chrono::seconds(3));
  2421. }
  2422. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2423. if (!should_run_issue_2431_tests()) {
  2424. GTEST_SKIP()
  2425. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2426. }
  2427. std::atomic<bool> stop{false};
  2428. std::vector<std::thread> threads;
  2429. for (int t = 0; t < 8; ++t) {
  2430. threads.emplace_back([t, &stop] {
  2431. int i = 0;
  2432. while (!stop.load(std::memory_order_relaxed)) {
  2433. struct addrinfo hints;
  2434. memset(&hints, 0, sizeof(hints));
  2435. hints.ai_family = AF_UNSPEC;
  2436. hints.ai_socktype = SOCK_STREAM;
  2437. auto host = unique_unresolvable_host(t * 100000 + i++);
  2438. struct addrinfo *result = nullptr;
  2439. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2440. &result, /*timeout_sec=*/1);
  2441. if (rc == 0 && result) { freeaddrinfo(result); }
  2442. }
  2443. });
  2444. }
  2445. std::this_thread::sleep_for(std::chrono::seconds(8));
  2446. stop.store(true, std::memory_order_relaxed);
  2447. for (auto &th : threads) {
  2448. th.join();
  2449. }
  2450. std::this_thread::sleep_for(std::chrono::seconds(3));
  2451. }
  2452. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2453. if (!should_run_issue_2431_tests()) {
  2454. GTEST_SKIP()
  2455. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2456. }
  2457. std::atomic<bool> stop{false};
  2458. std::vector<std::thread> threads;
  2459. for (int t = 0; t < 8; ++t) {
  2460. threads.emplace_back([t, &stop] {
  2461. int i = 0;
  2462. while (!stop.load(std::memory_order_relaxed)) {
  2463. auto host = unique_unresolvable_host(t * 100000 + i++);
  2464. Client cli(host, 80);
  2465. cli.set_connection_timeout(1, 0);
  2466. cli.set_read_timeout(1, 0);
  2467. cli.set_write_timeout(1, 0);
  2468. (void)cli.Get("/");
  2469. }
  2470. });
  2471. }
  2472. std::this_thread::sleep_for(std::chrono::seconds(8));
  2473. stop.store(true, std::memory_order_relaxed);
  2474. for (auto &th : threads) {
  2475. th.join();
  2476. }
  2477. std::this_thread::sleep_for(std::chrono::seconds(3));
  2478. }
  2479. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2480. TEST(ConnectionErrorTest, InvalidHost) {
  2481. auto host = "-abcde.com";
  2482. #ifdef CPPHTTPLIB_SSL_ENABLED
  2483. auto port = 443;
  2484. SSLClient cli(host, port);
  2485. #else
  2486. auto port = 80;
  2487. Client cli(host, port);
  2488. #endif
  2489. cli.set_connection_timeout(std::chrono::seconds(2));
  2490. auto res = cli.Get("/");
  2491. ASSERT_TRUE(!res);
  2492. EXPECT_EQ(Error::Connection, res.error());
  2493. }
  2494. TEST(ConnectionErrorTest, InvalidHost2) {
  2495. auto host = "httpcan.org/";
  2496. #ifdef CPPHTTPLIB_SSL_ENABLED
  2497. SSLClient cli(host);
  2498. #else
  2499. Client cli(host);
  2500. #endif
  2501. cli.set_connection_timeout(std::chrono::seconds(2));
  2502. auto res = cli.Get("/");
  2503. ASSERT_TRUE(!res);
  2504. EXPECT_EQ(Error::Connection, res.error());
  2505. }
  2506. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2507. auto host = "httpcan.org/";
  2508. #ifdef CPPHTTPLIB_SSL_ENABLED
  2509. SSLClient cli(host);
  2510. #else
  2511. Client cli(host);
  2512. #endif
  2513. cli.set_connection_timeout(std::chrono::seconds(2));
  2514. auto res = cli.Get("/");
  2515. ASSERT_TRUE(!res);
  2516. stringstream s;
  2517. s << "error code: " << res.error();
  2518. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2519. }
  2520. TEST(ConnectionErrorTest, InvalidPort) {
  2521. auto host = "localhost";
  2522. auto port = 44380;
  2523. #ifdef CPPHTTPLIB_SSL_ENABLED
  2524. SSLClient cli(host, port);
  2525. #else
  2526. Client cli(host, port);
  2527. #endif
  2528. cli.set_connection_timeout(std::chrono::seconds(2));
  2529. auto res = cli.Get("/");
  2530. ASSERT_TRUE(!res);
  2531. EXPECT_TRUE(Error::Connection == res.error() ||
  2532. Error::ConnectionTimeout == res.error());
  2533. }
  2534. TEST(ConnectionErrorTest, Timeout_Online) {
  2535. auto host = "google.com";
  2536. #ifdef CPPHTTPLIB_SSL_ENABLED
  2537. auto port = 44380;
  2538. SSLClient cli(host, port);
  2539. #else
  2540. auto port = 8080;
  2541. Client cli(host, port);
  2542. #endif
  2543. cli.set_connection_timeout(std::chrono::seconds(2));
  2544. // only probe one address type so that the error reason
  2545. // correlates to the timed-out IPv4, not the unsupported
  2546. // IPv6 connection attempt
  2547. cli.set_address_family(AF_INET);
  2548. auto res = cli.Get("/");
  2549. ASSERT_TRUE(!res);
  2550. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2551. }
  2552. TEST(CancelTest, NoCancel_Online) {
  2553. auto host = "httpbingo.org";
  2554. auto path = std::string{"/range/32"};
  2555. #ifdef CPPHTTPLIB_SSL_ENABLED
  2556. auto port = 443;
  2557. SSLClient cli(host, port);
  2558. #else
  2559. auto port = 80;
  2560. Client cli(host, port);
  2561. #endif
  2562. cli.set_connection_timeout(std::chrono::seconds(5));
  2563. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2565. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2566. EXPECT_EQ(StatusCode::OK_200, res->status);
  2567. }
  2568. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2569. // Use /bytes with a large payload so that the DownloadProgress callback
  2570. // (which only fires for Content-Length responses) is invoked before the
  2571. // entire body is received, giving cancellation a chance to fire.
  2572. auto host = "httpbingo.org";
  2573. auto path = std::string{"/bytes/524288"};
  2574. #ifdef CPPHTTPLIB_SSL_ENABLED
  2575. auto port = 443;
  2576. SSLClient cli(host, port);
  2577. #else
  2578. auto port = 80;
  2579. Client cli(host, port);
  2580. #endif
  2581. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2582. cli.set_connection_timeout(std::chrono::seconds(5));
  2583. ASSERT_TRUE(!res);
  2584. EXPECT_EQ(Error::Canceled, res.error());
  2585. }
  2586. TEST(CancelTest, WithCancelLargePayload_Online) {
  2587. auto host = "httpbingo.org";
  2588. auto path = std::string{"/bytes/524288"};
  2589. #ifdef CPPHTTPLIB_SSL_ENABLED
  2590. auto port = 443;
  2591. SSLClient cli(host, port);
  2592. #else
  2593. auto port = 80;
  2594. Client cli(host, port);
  2595. #endif
  2596. cli.set_connection_timeout(std::chrono::seconds(5));
  2597. uint32_t count = 0;
  2598. auto res =
  2599. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2600. ASSERT_TRUE(!res);
  2601. EXPECT_EQ(Error::Canceled, res.error());
  2602. }
  2603. TEST(CancelTest, NoCancelPost) {
  2604. Server svr;
  2605. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2606. res.set_content("Hello World!", "text/plain");
  2607. });
  2608. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2609. auto se = detail::scope_exit([&] {
  2610. svr.stop();
  2611. thread.join();
  2612. ASSERT_FALSE(svr.is_running());
  2613. });
  2614. svr.wait_until_ready();
  2615. Client cli(HOST, PORT);
  2616. cli.set_connection_timeout(std::chrono::seconds(5));
  2617. auto res =
  2618. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2619. "application/json", [](uint64_t, uint64_t) { return true; });
  2620. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2621. EXPECT_EQ("Hello World!", res->body);
  2622. EXPECT_EQ(StatusCode::OK_200, res->status);
  2623. }
  2624. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2625. Server svr;
  2626. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2627. res.set_content("Hello World!", "text/plain");
  2628. });
  2629. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2630. auto se = detail::scope_exit([&] {
  2631. svr.stop();
  2632. thread.join();
  2633. ASSERT_FALSE(svr.is_running());
  2634. });
  2635. svr.wait_until_ready();
  2636. Client cli(HOST, PORT);
  2637. cli.set_connection_timeout(std::chrono::seconds(5));
  2638. auto res =
  2639. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2640. "application/json", [](uint64_t, uint64_t) { return false; });
  2641. ASSERT_TRUE(!res);
  2642. EXPECT_EQ(Error::Canceled, res.error());
  2643. }
  2644. TEST(CancelTest, WithCancelLargePayloadPost) {
  2645. Server svr;
  2646. svr.set_payload_max_length(200 * 1024 * 1024);
  2647. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2648. res.set_content(LARGE_DATA, "text/plain");
  2649. });
  2650. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2651. auto se = detail::scope_exit([&] {
  2652. svr.stop();
  2653. thread.join();
  2654. ASSERT_FALSE(svr.is_running());
  2655. });
  2656. svr.wait_until_ready();
  2657. Client cli(HOST, PORT);
  2658. cli.set_payload_max_length(200 * 1024 * 1024);
  2659. cli.set_connection_timeout(std::chrono::seconds(5));
  2660. auto res =
  2661. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2662. "application/json", [](uint64_t, uint64_t) { return false; });
  2663. ASSERT_TRUE(!res);
  2664. EXPECT_EQ(Error::Canceled, res.error());
  2665. }
  2666. TEST(CancelTest, NoCancelPut) {
  2667. Server svr;
  2668. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2669. res.set_content("Hello World!", "text/plain");
  2670. });
  2671. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2672. auto se = detail::scope_exit([&] {
  2673. svr.stop();
  2674. thread.join();
  2675. ASSERT_FALSE(svr.is_running());
  2676. });
  2677. svr.wait_until_ready();
  2678. Client cli(HOST, PORT);
  2679. cli.set_connection_timeout(std::chrono::seconds(5));
  2680. auto res =
  2681. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2682. "application/json", [](uint64_t, uint64_t) { return true; });
  2683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2684. EXPECT_EQ("Hello World!", res->body);
  2685. EXPECT_EQ(StatusCode::OK_200, res->status);
  2686. }
  2687. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2688. Server svr;
  2689. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2690. res.set_content("Hello World!", "text/plain");
  2691. });
  2692. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2693. auto se = detail::scope_exit([&] {
  2694. svr.stop();
  2695. thread.join();
  2696. ASSERT_FALSE(svr.is_running());
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, PORT);
  2700. cli.set_connection_timeout(std::chrono::seconds(5));
  2701. auto res =
  2702. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2703. "application/json", [](uint64_t, uint64_t) { return false; });
  2704. ASSERT_TRUE(!res);
  2705. EXPECT_EQ(Error::Canceled, res.error());
  2706. }
  2707. TEST(CancelTest, WithCancelLargePayloadPut) {
  2708. Server svr;
  2709. svr.set_payload_max_length(200 * 1024 * 1024);
  2710. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2711. res.set_content(LARGE_DATA, "text/plain");
  2712. });
  2713. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2714. auto se = detail::scope_exit([&] {
  2715. svr.stop();
  2716. thread.join();
  2717. ASSERT_FALSE(svr.is_running());
  2718. });
  2719. svr.wait_until_ready();
  2720. Client cli(HOST, PORT);
  2721. cli.set_payload_max_length(200 * 1024 * 1024);
  2722. cli.set_connection_timeout(std::chrono::seconds(5));
  2723. auto res =
  2724. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2725. "application/json", [](uint64_t, uint64_t) { return false; });
  2726. ASSERT_TRUE(!res);
  2727. EXPECT_EQ(Error::Canceled, res.error());
  2728. }
  2729. TEST(CancelTest, NoCancelPatch) {
  2730. Server svr;
  2731. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2732. res.set_content("Hello World!", "text/plain");
  2733. });
  2734. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2735. auto se = detail::scope_exit([&] {
  2736. svr.stop();
  2737. thread.join();
  2738. ASSERT_FALSE(svr.is_running());
  2739. });
  2740. svr.wait_until_ready();
  2741. Client cli(HOST, PORT);
  2742. cli.set_connection_timeout(std::chrono::seconds(5));
  2743. auto res =
  2744. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2745. "application/json", [](uint64_t, uint64_t) { return true; });
  2746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2747. EXPECT_EQ("Hello World!", res->body);
  2748. EXPECT_EQ(StatusCode::OK_200, res->status);
  2749. }
  2750. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2751. Server svr;
  2752. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2753. res.set_content("Hello World!", "text/plain");
  2754. });
  2755. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2756. auto se = detail::scope_exit([&] {
  2757. svr.stop();
  2758. thread.join();
  2759. ASSERT_FALSE(svr.is_running());
  2760. });
  2761. svr.wait_until_ready();
  2762. Client cli(HOST, PORT);
  2763. cli.set_connection_timeout(std::chrono::seconds(5));
  2764. auto res =
  2765. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2766. "application/json", [](uint64_t, uint64_t) { return false; });
  2767. ASSERT_TRUE(!res);
  2768. EXPECT_EQ(Error::Canceled, res.error());
  2769. }
  2770. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2771. Server svr;
  2772. svr.set_payload_max_length(200 * 1024 * 1024);
  2773. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2774. res.set_content(LARGE_DATA, "text/plain");
  2775. });
  2776. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2777. auto se = detail::scope_exit([&] {
  2778. svr.stop();
  2779. thread.join();
  2780. ASSERT_FALSE(svr.is_running());
  2781. });
  2782. svr.wait_until_ready();
  2783. Client cli(HOST, PORT);
  2784. cli.set_payload_max_length(200 * 1024 * 1024);
  2785. cli.set_connection_timeout(std::chrono::seconds(5));
  2786. auto res =
  2787. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2788. "application/json", [](uint64_t, uint64_t) { return false; });
  2789. ASSERT_TRUE(!res);
  2790. EXPECT_EQ(Error::Canceled, res.error());
  2791. }
  2792. TEST(CancelTest, NoCancelDelete) {
  2793. Server svr;
  2794. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2795. res.set_content("Hello World!", "text/plain");
  2796. });
  2797. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2798. auto se = detail::scope_exit([&] {
  2799. svr.stop();
  2800. thread.join();
  2801. ASSERT_FALSE(svr.is_running());
  2802. });
  2803. svr.wait_until_ready();
  2804. Client cli(HOST, PORT);
  2805. cli.set_connection_timeout(std::chrono::seconds(5));
  2806. auto res =
  2807. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2808. "application/json", [](uint64_t, uint64_t) { return true; });
  2809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2810. EXPECT_EQ("Hello World!", res->body);
  2811. EXPECT_EQ(StatusCode::OK_200, res->status);
  2812. }
  2813. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2814. Server svr;
  2815. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2816. res.set_content("Hello World!", "text/plain");
  2817. });
  2818. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2819. auto se = detail::scope_exit([&] {
  2820. svr.stop();
  2821. thread.join();
  2822. ASSERT_FALSE(svr.is_running());
  2823. });
  2824. svr.wait_until_ready();
  2825. Client cli(HOST, PORT);
  2826. cli.set_connection_timeout(std::chrono::seconds(5));
  2827. auto res =
  2828. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2829. "application/json", [](uint64_t, uint64_t) { return false; });
  2830. ASSERT_TRUE(!res);
  2831. EXPECT_EQ(Error::Canceled, res.error());
  2832. }
  2833. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2834. Server svr;
  2835. svr.set_payload_max_length(200 * 1024 * 1024);
  2836. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2837. res.set_content(LARGE_DATA, "text/plain");
  2838. });
  2839. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2840. auto se = detail::scope_exit([&] {
  2841. svr.stop();
  2842. thread.join();
  2843. ASSERT_FALSE(svr.is_running());
  2844. });
  2845. svr.wait_until_ready();
  2846. Client cli(HOST, PORT);
  2847. cli.set_payload_max_length(200 * 1024 * 1024);
  2848. cli.set_connection_timeout(std::chrono::seconds(5));
  2849. auto res =
  2850. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2851. "application/json", [](uint64_t, uint64_t) { return false; });
  2852. ASSERT_TRUE(!res);
  2853. EXPECT_EQ(Error::Canceled, res.error());
  2854. }
  2855. static std::string remove_whitespace(const std::string &input) {
  2856. std::string output;
  2857. output.reserve(input.size());
  2858. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2859. [](unsigned char c) { return !std::isspace(c); });
  2860. return output;
  2861. }
  2862. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2863. auto host = "httpbingo.org";
  2864. auto path = std::string{"/basic-auth/hello/world"};
  2865. #ifdef CPPHTTPLIB_SSL_ENABLED
  2866. auto port = 443;
  2867. SSLClient cli(host, port);
  2868. #else
  2869. auto port = 80;
  2870. Client cli(host, port);
  2871. #endif
  2872. {
  2873. auto res = cli.Get(path);
  2874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2875. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2876. }
  2877. {
  2878. auto res = cli.Get(
  2879. path, Headers{make_basic_authentication_header("hello", "world")});
  2880. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2881. auto body = remove_whitespace(res->body);
  2882. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2883. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2884. EXPECT_EQ(StatusCode::OK_200, res->status);
  2885. }
  2886. {
  2887. cli.set_basic_auth("hello", "world");
  2888. auto res = cli.Get(path);
  2889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2890. auto body = remove_whitespace(res->body);
  2891. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2892. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2893. EXPECT_EQ(StatusCode::OK_200, res->status);
  2894. }
  2895. {
  2896. cli.set_basic_auth("hello", "bad");
  2897. auto res = cli.Get(path);
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2900. }
  2901. {
  2902. cli.set_basic_auth("bad", "world");
  2903. auto res = cli.Get(path);
  2904. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2905. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2906. }
  2907. }
  2908. #ifdef CPPHTTPLIB_SSL_ENABLED
  2909. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2910. auto host = "httpbingo.org";
  2911. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2912. auto paths = std::vector<std::string>{
  2913. "/digest-auth/auth/hello/world/MD5",
  2914. "/digest-auth/auth/hello/world/SHA-256",
  2915. };
  2916. auto port = 443;
  2917. SSLClient cli(host, port);
  2918. {
  2919. auto res = cli.Get(unauth_path);
  2920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2921. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2922. }
  2923. {
  2924. cli.set_digest_auth("hello", "world");
  2925. for (const auto &path : paths) {
  2926. auto res = cli.Get(path.c_str());
  2927. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2928. auto body = remove_whitespace(res->body);
  2929. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2930. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2931. EXPECT_EQ(StatusCode::OK_200, res->status);
  2932. }
  2933. cli.set_digest_auth("hello", "bad");
  2934. for (const auto &path : paths) {
  2935. auto res = cli.Get(path.c_str());
  2936. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2937. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2938. }
  2939. }
  2940. }
  2941. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2942. // comma-separated list of challenges, and each challenge may itself carry a
  2943. // comma-separated auth-param list, so a server can legally offer Basic
  2944. // before Digest, either as two field lines or packed into one. Runs one 401
  2945. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2946. // value() joins them in receipt order) and checks that the retry carries a
  2947. // well-formed Digest Authorization header naming expected_realm.
  2948. static void
  2949. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2950. const std::string &expected_realm) {
  2951. std::atomic<int> hits{0};
  2952. Server svr;
  2953. svr.Get("/x", [&](const Request &req, Response &res) {
  2954. if (++hits == 1) {
  2955. res.status = StatusCode::Unauthorized_401;
  2956. for (const auto &challenge : challenges) {
  2957. res.set_header("WWW-Authenticate", challenge);
  2958. }
  2959. } else {
  2960. auto authorization = req.get_header_value("Authorization");
  2961. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2962. EXPECT_NE(std::string::npos,
  2963. authorization.find("realm=\"" + expected_realm + "\""));
  2964. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2965. res.set_content("ok", "text/plain");
  2966. }
  2967. });
  2968. auto port = svr.bind_to_any_port(HOST);
  2969. std::thread t([&]() { svr.listen_after_bind(); });
  2970. auto se = detail::scope_exit([&] {
  2971. svr.stop();
  2972. t.join();
  2973. });
  2974. svr.wait_until_ready();
  2975. Client cli(HOST, port);
  2976. cli.set_digest_auth("hello", "world");
  2977. auto res = cli.Get("/x");
  2978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2979. EXPECT_EQ(2, hits.load());
  2980. }
  2981. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2982. static const char *kDigestChallenge =
  2983. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2984. "algorithm=MD5";
  2985. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2986. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2987. "testrealm");
  2988. }
  2989. // Same challenge list with the schemes in the opposite order, to make sure
  2990. // the fix above didn't just special-case "Basic first".
  2991. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2992. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2993. "testrealm");
  2994. }
  2995. // A comma inside a quoted auth-param value must not be mistaken for the
  2996. // separator between two challenges (or two auth-params).
  2997. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2998. run_digest_challenge_list_test(
  2999. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  3000. "algorithm=MD5"},
  3001. "test,realm");
  3002. }
  3003. // RFC 7616 3.4: uri is the request-target as sent, which is encoded, carries
  3004. // the params and leaves out the fragment.
  3005. TEST(DigestAuthTest, UriIsTheRequestTargetSent) {
  3006. Server svr;
  3007. std::string uri, target;
  3008. svr.Get("/a b", [&](const Request &req, Response &res) {
  3009. auto auth = req.get_header_value("Authorization");
  3010. if (auth.empty()) {
  3011. res.status = StatusCode::Unauthorized_401;
  3012. res.set_header("WWW-Authenticate",
  3013. "Digest realm=\"r\", qop=\"auth\", nonce=\"n\"");
  3014. return;
  3015. }
  3016. auto b = auth.find("uri=\"") + 5;
  3017. uri = auth.substr(b, auth.find('"', b) - b);
  3018. target = req.target;
  3019. });
  3020. auto port = svr.bind_to_any_port(HOST);
  3021. std::thread t([&]() { svr.listen_after_bind(); });
  3022. auto se = detail::scope_exit([&] {
  3023. svr.stop();
  3024. t.join();
  3025. });
  3026. svr.wait_until_ready();
  3027. Client cli(HOST, port);
  3028. cli.set_digest_auth("hello", "world");
  3029. auto res = cli.Get("/a b#f", Params{{"x", "1"}}, Headers{});
  3030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3031. EXPECT_EQ("/a%20b?x=1", target);
  3032. EXPECT_EQ(target, uri);
  3033. }
  3034. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  3035. // make_digest_authentication_header() dereferences both unconditionally, so
  3036. // a server sending a challenge missing either one must not be treated as
  3037. // usable -- doing so used to crash the client with std::out_of_range.
  3038. static void run_digest_challenge_missing_field_test(const char *challenge) {
  3039. Server svr;
  3040. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  3041. res.status = StatusCode::Unauthorized_401;
  3042. res.set_header("WWW-Authenticate", challenge);
  3043. });
  3044. auto port = svr.bind_to_any_port(HOST);
  3045. std::thread t([&]() { svr.listen_after_bind(); });
  3046. auto se = detail::scope_exit([&] {
  3047. svr.stop();
  3048. t.join();
  3049. });
  3050. svr.wait_until_ready();
  3051. Client cli(HOST, port);
  3052. cli.set_digest_auth("hello", "world");
  3053. auto res = cli.Get("/x");
  3054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3055. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  3056. }
  3057. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  3058. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  3059. }
  3060. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  3061. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  3062. }
  3063. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  3064. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  3065. }
  3066. // A hostile server can put a '"' in realm/nonce/opaque, or a non-token
  3067. // algorithm, in its challenge. parse_www_authenticate() de-escapes quoted-pairs
  3068. // when storing the values, so the header builder has to re-escape them (and
  3069. // keep algorithm a bare token); otherwise the value breaks out of its
  3070. // quoted-string and injects extra auth-params into the client's Authorization.
  3071. TEST(DigestAuthTest, EscapesInjectedAuthParams) {
  3072. std::atomic<int> hits{0};
  3073. std::string authorization;
  3074. Server svr;
  3075. svr.Get("/x", [&](const Request &req, Response &res) {
  3076. if (++hits == 1) {
  3077. res.status = StatusCode::Unauthorized_401;
  3078. // On the wire the quotes embedded in the values are backslash-escaped.
  3079. res.set_header("WWW-Authenticate",
  3080. "Digest realm=\"testrealm\", "
  3081. "nonce=\"n\\\"; injected=\\\"x\", "
  3082. "algorithm=\"MD5, injected2=\\\"y\\\"\", qop=\"auth\"");
  3083. } else {
  3084. authorization = req.get_header_value("Authorization");
  3085. res.set_content("ok", "text/plain");
  3086. }
  3087. });
  3088. auto port = svr.bind_to_any_port(HOST);
  3089. std::thread t([&]() { svr.listen_after_bind(); });
  3090. auto se = detail::scope_exit([&] {
  3091. svr.stop();
  3092. t.join();
  3093. });
  3094. svr.wait_until_ready();
  3095. Client cli(HOST, port);
  3096. cli.set_digest_auth("hello", "world");
  3097. auto res = cli.Get("/x");
  3098. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3099. EXPECT_EQ(2, hits.load());
  3100. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  3101. // The nonce (de-escaped to n"; injected="x ) must be re-escaped so it stays
  3102. // inside its quoted-string rather than starting an "injected" auth-param.
  3103. EXPECT_NE(std::string::npos,
  3104. authorization.find("nonce=\"n\\\"; injected=\\\"x\""));
  3105. // A non-token algorithm falls back to a bare MD5 token, dropping the payload.
  3106. EXPECT_EQ(std::string::npos, authorization.find("injected2"));
  3107. }
  3108. #endif
  3109. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  3110. auto host = "google.com";
  3111. auto another_host = "example.com";
  3112. auto wrong_ip = "0.0.0.0";
  3113. #ifdef CPPHTTPLIB_SSL_ENABLED
  3114. SSLClient cli(host);
  3115. #else
  3116. Client cli(host);
  3117. #endif
  3118. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  3119. auto res = cli.Get("/");
  3120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3121. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  3122. }
  3123. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  3124. auto host = "google.com";
  3125. auto wrong_ip = "0.0.0.0";
  3126. #ifdef CPPHTTPLIB_SSL_ENABLED
  3127. SSLClient cli(host);
  3128. #else
  3129. Client cli(host);
  3130. #endif
  3131. cli.set_hostname_addr_map({{host, wrong_ip}});
  3132. auto res = cli.Get("/");
  3133. ASSERT_TRUE(!res);
  3134. EXPECT_EQ(Error::Connection, res.error());
  3135. }
  3136. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  3137. // A mapped value that is not an IP literal must be resolved. "localhost"
  3138. // resolves from the hosts file, so this test needs no external DNS.
  3139. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  3140. auto host = "target.invalid";
  3141. Server svr;
  3142. std::string received_host;
  3143. svr.Get("/hi", [&](const Request &req, Response &res) {
  3144. received_host = req.get_header_value("Host");
  3145. res.set_content("Hello World!", "text/plain");
  3146. });
  3147. auto port = svr.bind_to_any_port(HOST);
  3148. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3149. auto se = detail::scope_exit([&] {
  3150. svr.stop();
  3151. thread.join();
  3152. ASSERT_FALSE(svr.is_running());
  3153. });
  3154. svr.wait_until_ready();
  3155. Client cli(host, port);
  3156. cli.set_hostname_addr_map({{host, HOST}});
  3157. auto res = cli.Get("/hi");
  3158. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3159. EXPECT_EQ(StatusCode::OK_200, res->status);
  3160. // The mapping only redirects the connection; the identity stays host_.
  3161. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  3162. }
  3163. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  3164. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  3165. auto host = "target.invalid";
  3166. Server svr;
  3167. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3168. res.set_content("Hello World!", "text/plain");
  3169. });
  3170. auto port = svr.bind_to_any_port("127.0.0.1");
  3171. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3172. auto se = detail::scope_exit([&] {
  3173. svr.stop();
  3174. thread.join();
  3175. ASSERT_FALSE(svr.is_running());
  3176. });
  3177. svr.wait_until_ready();
  3178. Client cli(host, port);
  3179. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  3180. auto res = cli.Get("/hi");
  3181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3182. EXPECT_EQ(StatusCode::OK_200, res->status);
  3183. }
  3184. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  3185. // An empty mapped value must leave host_ as the connection target. Without
  3186. // that guard the empty value would become the host argument, getaddrinfo
  3187. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  3188. // loopback - silently connecting somewhere the caller never asked for.
  3189. // The server listens on loopback, so such a fallback would succeed and is
  3190. // therefore observable as a failure of this test.
  3191. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  3192. Server svr;
  3193. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3194. res.set_content("Hello World!", "text/plain");
  3195. });
  3196. auto port = svr.bind_to_any_port(HOST);
  3197. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3198. auto se = detail::scope_exit([&] {
  3199. svr.stop();
  3200. thread.join();
  3201. ASSERT_FALSE(svr.is_running());
  3202. });
  3203. svr.wait_until_ready();
  3204. Client cli(blackhole, port);
  3205. cli.set_hostname_addr_map({{blackhole, ""}});
  3206. cli.set_connection_timeout(1);
  3207. auto res = cli.Get("/hi");
  3208. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  3209. }
  3210. TEST(AbsoluteRedirectTest, Redirect_Online) {
  3211. auto host = "httpbingo.org";
  3212. auto path = std::string{"/absolute-redirect/3"};
  3213. #ifdef CPPHTTPLIB_SSL_ENABLED
  3214. SSLClient cli(host);
  3215. #else
  3216. Client cli(host);
  3217. #endif
  3218. cli.set_follow_location(true);
  3219. auto res = cli.Get(path);
  3220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3221. EXPECT_EQ(StatusCode::OK_200, res->status);
  3222. }
  3223. TEST(RedirectTest, Redirect_Online) {
  3224. auto host = "httpbingo.org";
  3225. auto path = std::string{"/redirect/3"};
  3226. #ifdef CPPHTTPLIB_SSL_ENABLED
  3227. SSLClient cli(host);
  3228. #else
  3229. Client cli(host);
  3230. #endif
  3231. cli.set_follow_location(true);
  3232. auto res = cli.Get(path);
  3233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3234. EXPECT_EQ(StatusCode::OK_200, res->status);
  3235. }
  3236. TEST(RelativeRedirectTest, Redirect_Online) {
  3237. auto host = "httpbingo.org";
  3238. auto path = std::string{"/relative-redirect/3"};
  3239. #ifdef CPPHTTPLIB_SSL_ENABLED
  3240. SSLClient cli(host);
  3241. #else
  3242. Client cli(host);
  3243. #endif
  3244. cli.set_follow_location(true);
  3245. auto res = cli.Get(path);
  3246. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3247. EXPECT_EQ(StatusCode::OK_200, res->status);
  3248. }
  3249. TEST(TooManyRedirectTest, Redirect_Online) {
  3250. auto host = "httpbingo.org";
  3251. auto path = std::string{"/redirect/21"};
  3252. #ifdef CPPHTTPLIB_SSL_ENABLED
  3253. SSLClient cli(host);
  3254. #else
  3255. Client cli(host);
  3256. #endif
  3257. cli.set_follow_location(true);
  3258. auto res = cli.Get(path);
  3259. ASSERT_TRUE(!res);
  3260. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  3261. }
  3262. #ifdef CPPHTTPLIB_SSL_ENABLED
  3263. TEST(YahooRedirectTest, Redirect_Online) {
  3264. Client cli("yahoo.com");
  3265. auto res = cli.Get("/");
  3266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3267. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  3268. cli.set_follow_location(true);
  3269. res = cli.Get("/");
  3270. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3271. EXPECT_EQ(StatusCode::OK_200, res->status);
  3272. EXPECT_EQ("https://www.yahoo.com/", res->location);
  3273. }
  3274. // Previously "nghttp2.org" "/httpbin/redirect-to"
  3275. #define REDIR_HOST "httpbingo.org"
  3276. #define REDIR_PATH "/redirect-to"
  3277. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  3278. SSLClient cli(REDIR_HOST);
  3279. cli.set_follow_location(true);
  3280. auto res =
  3281. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  3282. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3283. EXPECT_EQ(StatusCode::OK_200, res->status);
  3284. }
  3285. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  3286. SSLClient cli(REDIR_HOST);
  3287. cli.set_follow_location(true);
  3288. Params params;
  3289. params.emplace("url", "http://example.com");
  3290. params.emplace("status_code", "302");
  3291. auto res = cli.Get(REDIR_PATH, params, Headers{});
  3292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3293. EXPECT_EQ(StatusCode::OK_200, res->status);
  3294. }
  3295. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  3296. SSLClient cli(REDIR_HOST);
  3297. cli.set_follow_location(true);
  3298. Params params;
  3299. params.emplace("url", "http://example.com");
  3300. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  3301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3302. EXPECT_EQ(StatusCode::OK_200, res->status);
  3303. }
  3304. TEST(UrlWithSpace, Redirect_Online) {
  3305. SSLClient cli("edge.forgecdn.net");
  3306. cli.set_follow_location(true);
  3307. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  3308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3309. EXPECT_EQ(StatusCode::OK_200, res->status);
  3310. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  3311. }
  3312. #endif
  3313. #if !defined(_WIN32) && !defined(_WIN64)
  3314. TEST(ReceiveSignals, Signal) {
  3315. auto setupSignalHandlers = []() {
  3316. struct sigaction act;
  3317. sigemptyset(&act.sa_mask);
  3318. act.sa_flags = SA_SIGINFO;
  3319. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  3320. switch (sig) {
  3321. case SIGINT:
  3322. default: break;
  3323. }
  3324. };
  3325. ::sigaction(SIGINT, &act, nullptr);
  3326. };
  3327. Server svr;
  3328. int port = 0;
  3329. auto thread = std::thread([&]() {
  3330. setupSignalHandlers();
  3331. port = svr.bind_to_any_port(HOST);
  3332. svr.listen_after_bind();
  3333. });
  3334. auto se = detail::scope_exit([&] {
  3335. svr.stop();
  3336. thread.join();
  3337. ASSERT_FALSE(svr.is_running());
  3338. });
  3339. svr.wait_until_ready();
  3340. ASSERT_TRUE(svr.is_running());
  3341. pthread_kill(thread.native_handle(), SIGINT);
  3342. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  3343. ASSERT_TRUE(svr.is_running());
  3344. }
  3345. #endif
  3346. TEST(RedirectToDifferentPort, Redirect) {
  3347. Server svr1;
  3348. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  3349. res.set_content("Hello World!", "text/plain");
  3350. });
  3351. int svr1_port = 0;
  3352. auto thread1 = std::thread([&]() {
  3353. svr1_port = svr1.bind_to_any_port(HOST);
  3354. svr1.listen_after_bind();
  3355. });
  3356. Server svr2;
  3357. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  3358. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  3359. });
  3360. int svr2_port = 0;
  3361. auto thread2 = std::thread([&]() {
  3362. svr2_port = svr2.bind_to_any_port(HOST);
  3363. svr2.listen_after_bind();
  3364. });
  3365. auto se = detail::scope_exit([&] {
  3366. svr2.stop();
  3367. thread2.join();
  3368. svr1.stop();
  3369. thread1.join();
  3370. ASSERT_FALSE(svr2.is_running());
  3371. ASSERT_FALSE(svr1.is_running());
  3372. });
  3373. svr1.wait_until_ready();
  3374. svr2.wait_until_ready();
  3375. Client cli("localhost", svr2_port);
  3376. cli.set_follow_location(true);
  3377. auto res = cli.Get("/2");
  3378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3379. EXPECT_EQ(StatusCode::OK_200, res->status);
  3380. EXPECT_EQ("Hello World!", res->body);
  3381. }
  3382. // GET /redir on one server redirects to /target on another port, so the
  3383. // client follows it with a new client.
  3384. static Result
  3385. GetThroughRedirectToDifferentPort(Server::Handler target,
  3386. const std::function<void(Client &)> &setup,
  3387. const Headers &headers = Headers()) {
  3388. Server target_svr;
  3389. target_svr.Get("/target", target);
  3390. int target_port = 0;
  3391. auto target_thread = std::thread([&]() {
  3392. target_port = target_svr.bind_to_any_port(HOST);
  3393. target_svr.listen_after_bind();
  3394. });
  3395. Server origin_svr;
  3396. origin_svr.Get("/redir", [&](const Request &, Response &res) {
  3397. res.set_redirect(
  3398. "http://localhost:" + std::to_string(target_port) + "/target", 302);
  3399. });
  3400. int origin_port = 0;
  3401. auto origin_thread = std::thread([&]() {
  3402. origin_port = origin_svr.bind_to_any_port(HOST);
  3403. origin_svr.listen_after_bind();
  3404. });
  3405. auto se = detail::scope_exit([&] {
  3406. origin_svr.stop();
  3407. origin_thread.join();
  3408. target_svr.stop();
  3409. target_thread.join();
  3410. });
  3411. target_svr.wait_until_ready();
  3412. origin_svr.wait_until_ready();
  3413. Client cli("localhost", origin_port);
  3414. cli.set_follow_location(true);
  3415. setup(cli);
  3416. return cli.Get("/redir", headers);
  3417. }
  3418. static void
  3419. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  3420. std::string captured_authorization;
  3421. auto result = GetThroughRedirectToDifferentPort(
  3422. [&](const Request &req, Response &res) {
  3423. captured_authorization = req.get_header_value("Authorization");
  3424. res.set_content("OK", "text/plain");
  3425. },
  3426. set_auth);
  3427. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3428. EXPECT_EQ(StatusCode::OK_200, result->status);
  3429. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3430. EXPECT_TRUE(captured_authorization.empty());
  3431. }
  3432. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3433. TestDoNotForwardCredentialsOnRedirect(
  3434. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3435. }
  3436. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3437. TestDoNotForwardCredentialsOnRedirect(
  3438. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3439. }
  3440. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3441. std::string captured_cookie;
  3442. auto result = GetThroughRedirectToDifferentPort(
  3443. [&](const Request &req, Response &res) {
  3444. captured_cookie = req.get_header_value("Cookie");
  3445. res.set_content("OK", "text/plain");
  3446. },
  3447. [](Client &) {}, {{"Cookie", "session_id=SECRET; auth=PRIVATE"}});
  3448. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3449. EXPECT_EQ(StatusCode::OK_200, result->status);
  3450. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3451. EXPECT_TRUE(captured_cookie.empty());
  3452. }
  3453. TEST(RedirectToSamePort, ForwardCookie) {
  3454. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3455. // header so that ordinary session flows keep working.
  3456. Server svr;
  3457. std::string captured_cookie;
  3458. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3459. res.set_redirect("/target", 302);
  3460. });
  3461. svr.Get("/target", [&](const Request &req, Response &res) {
  3462. captured_cookie = req.get_header_value("Cookie");
  3463. res.set_content("OK", "text/plain");
  3464. });
  3465. auto port = svr.bind_to_any_port(HOST);
  3466. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3467. auto se = detail::scope_exit([&] {
  3468. svr.stop();
  3469. thread.join();
  3470. ASSERT_FALSE(svr.is_running());
  3471. });
  3472. svr.wait_until_ready();
  3473. Client cli(HOST, port);
  3474. cli.set_follow_location(true);
  3475. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3476. auto res = cli.Get("/redir", headers);
  3477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3478. EXPECT_EQ(StatusCode::OK_200, res->status);
  3479. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3480. }
  3481. TEST(RedirectToDifferentPort, ForwardDefaultHeadersButNotCredentials) {
  3482. std::string authorization;
  3483. std::string trace_id;
  3484. auto result = GetThroughRedirectToDifferentPort(
  3485. [&](const Request &req, Response &res) {
  3486. authorization = req.get_header_value("Authorization");
  3487. trace_id = req.get_header_value("X-Trace-Id");
  3488. res.set_content("OK", "text/plain");
  3489. },
  3490. [](Client &cli) {
  3491. cli.set_default_headers(
  3492. {{"Authorization", "Bearer SECRET"}, {"X-Trace-Id", "42"}});
  3493. });
  3494. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3495. EXPECT_EQ(StatusCode::OK_200, result->status);
  3496. // Like a header given with the request, a default one goes along unless it
  3497. // carries credentials (RFC 9110 15.4).
  3498. EXPECT_TRUE(authorization.empty());
  3499. EXPECT_EQ("42", trace_id);
  3500. }
  3501. TEST(RedirectToDifferentPort, KeepPayloadMaxLength) {
  3502. auto result = GetThroughRedirectToDifferentPort(
  3503. [](const Request &, Response &res) {
  3504. res.set_content(std::string(2048, 'x'), "text/plain");
  3505. },
  3506. [](Client &cli) { cli.set_payload_max_length(1024); });
  3507. EXPECT_FALSE(result);
  3508. }
  3509. TEST(RedirectToDifferentPort, KeepMaxTimeout) {
  3510. auto result = GetThroughRedirectToDifferentPort(
  3511. [](const Request &req, Response &res) {
  3512. // Answer after a second, or once the client gives up.
  3513. for (auto i = 0; i < 100 && !req.is_connection_closed(); i++) {
  3514. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  3515. }
  3516. res.set_content("late", "text/plain");
  3517. },
  3518. [](Client &cli) { cli.set_max_timeout(std::chrono::milliseconds(200)); });
  3519. ASSERT_FALSE(result);
  3520. EXPECT_EQ(Error::Read, result.error());
  3521. }
  3522. #ifdef CPPHTTPLIB_SSL_ENABLED
  3523. TEST(RedirectToDifferentPort, DoNotAnswerChallengeFromRedirectTarget) {
  3524. auto result = GetThroughRedirectToDifferentPort(
  3525. [](const Request &, Response &res) {
  3526. res.status = StatusCode::Unauthorized_401;
  3527. res.set_header("WWW-Authenticate",
  3528. "Digest realm=\"r\", nonce=\"n\", qop=\"auth\"");
  3529. },
  3530. [](Client &cli) { cli.set_digest_auth("user", "pass"); });
  3531. ASSERT_TRUE(result) << "Error: " << to_string(result.error());
  3532. EXPECT_EQ(StatusCode::Unauthorized_401, result->status);
  3533. }
  3534. #endif
  3535. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3536. Server svr;
  3537. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3538. // Port number that overflows int — should not crash
  3539. res.set_redirect("http://localhost:99999999999999999999/target");
  3540. });
  3541. auto port = svr.bind_to_any_port(HOST);
  3542. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3543. auto se = detail::scope_exit([&] {
  3544. svr.stop();
  3545. thread.join();
  3546. ASSERT_FALSE(svr.is_running());
  3547. });
  3548. svr.wait_until_ready();
  3549. Client cli(HOST, port);
  3550. cli.set_follow_location(true);
  3551. auto res = cli.Get("/redir");
  3552. // Should fail gracefully, not crash (no valid response due to bad port)
  3553. EXPECT_FALSE(res);
  3554. }
  3555. TEST(RedirectToDifferentPort, TrailingCharactersInPort) {
  3556. Server svr;
  3557. auto port = svr.bind_to_any_port(HOST);
  3558. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3559. // The server's own port followed by junk must not be followed
  3560. res.set_redirect("http://" + std::string(HOST) + ":" +
  3561. std::to_string(port) + "junk/target");
  3562. });
  3563. svr.Get("/target", [&](const Request & /*req*/, Response &res) {
  3564. res.set_content("target", "text/plain");
  3565. });
  3566. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3567. auto se = detail::scope_exit([&] {
  3568. svr.stop();
  3569. thread.join();
  3570. ASSERT_FALSE(svr.is_running());
  3571. });
  3572. svr.wait_until_ready();
  3573. Client cli(HOST, port);
  3574. cli.set_follow_location(true);
  3575. auto res = cli.Get("/redir");
  3576. EXPECT_FALSE(res);
  3577. }
  3578. TEST(RedirectFromPageWithContent, Redirect) {
  3579. Server svr;
  3580. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3581. res.set_content("___", "text/plain");
  3582. res.set_redirect("/2");
  3583. });
  3584. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3585. res.set_content("Hello World!", "text/plain");
  3586. });
  3587. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3588. auto se = detail::scope_exit([&] {
  3589. svr.stop();
  3590. th.join();
  3591. ASSERT_FALSE(svr.is_running());
  3592. });
  3593. svr.wait_until_ready();
  3594. {
  3595. Client cli("localhost", PORT);
  3596. cli.set_follow_location(true);
  3597. std::string body;
  3598. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3599. body.append(data, data_length);
  3600. return true;
  3601. });
  3602. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3603. EXPECT_EQ(StatusCode::OK_200, res->status);
  3604. EXPECT_EQ("Hello World!", body);
  3605. }
  3606. {
  3607. Client cli("localhost", PORT);
  3608. std::string body;
  3609. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3610. body.append(data, data_length);
  3611. return true;
  3612. });
  3613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3614. EXPECT_EQ(StatusCode::Found_302, res->status);
  3615. EXPECT_EQ("___", body);
  3616. }
  3617. }
  3618. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3619. Server svr;
  3620. auto port_str = std::to_string(PORT);
  3621. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3622. auto expected_host = "[::1]:" + port_str;
  3623. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3624. res.set_content("___", "text/plain");
  3625. // res.set_redirect("/2");
  3626. res.set_redirect(redirect_url);
  3627. });
  3628. svr.Get("/2", [&](const Request &req, Response &res) {
  3629. auto host_header = req.headers.find("Host");
  3630. ASSERT_TRUE(host_header != req.headers.end());
  3631. EXPECT_EQ(expected_host, host_header->second);
  3632. res.set_content("Hello World!", "text/plain");
  3633. });
  3634. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3635. auto se = detail::scope_exit([&] {
  3636. svr.stop();
  3637. th.join();
  3638. ASSERT_FALSE(svr.is_running());
  3639. });
  3640. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3641. // actually starts anything, so the condition !svr.is_running() will
  3642. // always remain true, and the loop never stops.
  3643. // This basically counts how many milliseconds have passed since the
  3644. // call to svr.listen(), and if after 5 seconds nothing started yet
  3645. // aborts the test.
  3646. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3647. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3648. ASSERT_LT(milliseconds, 5000U);
  3649. }
  3650. {
  3651. Client cli("::1", PORT);
  3652. cli.set_follow_location(true);
  3653. std::string body;
  3654. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3655. body.append(data, data_length);
  3656. return true;
  3657. });
  3658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3659. EXPECT_EQ(StatusCode::OK_200, res->status);
  3660. EXPECT_EQ("Hello World!", body);
  3661. }
  3662. {
  3663. Client cli("::1", PORT);
  3664. std::string body;
  3665. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3666. body.append(data, data_length);
  3667. return true;
  3668. });
  3669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3670. EXPECT_EQ(StatusCode::Found_302, res->status);
  3671. EXPECT_EQ("___", body);
  3672. }
  3673. }
  3674. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3675. Server svr;
  3676. svr.Get("/foo", [](const Request &req, Response &res) {
  3677. auto a = req.params.find("a");
  3678. if (a != req.params.end()) {
  3679. res.set_content((*a).second, "text/plain");
  3680. res.status = StatusCode::OK_200;
  3681. } else {
  3682. res.status = StatusCode::BadRequest_400;
  3683. }
  3684. });
  3685. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  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. {
  3693. Client cli(HOST, PORT);
  3694. cli.set_path_encode(false);
  3695. auto res = cli.Get("/foo?a=explicitly+encoded");
  3696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3697. EXPECT_EQ(StatusCode::OK_200, res->status);
  3698. // This expects it back with a space, as the `+` won't have been
  3699. // url-encoded, and server-side the params get decoded turning `+`
  3700. // into spaces.
  3701. EXPECT_EQ("explicitly encoded", res->body);
  3702. }
  3703. }
  3704. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3705. // When path encoding is disabled the client must transmit the supplied
  3706. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3707. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3708. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3709. // than a space (0x20). Assert on the raw wire target to catch this.
  3710. Server svr;
  3711. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3712. svr.Get("/foo", [&](const Request &req, Response &res) {
  3713. EXPECT_EQ(expected_target, req.target);
  3714. res.status = StatusCode::OK_200;
  3715. });
  3716. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3717. auto se = detail::scope_exit([&] {
  3718. svr.stop();
  3719. thread.join();
  3720. ASSERT_FALSE(svr.is_running());
  3721. });
  3722. svr.wait_until_ready();
  3723. {
  3724. Client cli(HOST, PORT);
  3725. cli.set_path_encode(false);
  3726. auto res = cli.Get(expected_target.c_str());
  3727. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3728. EXPECT_EQ(StatusCode::OK_200, res->status);
  3729. }
  3730. }
  3731. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3732. // `open_stream()` used to skip the path encoding that the buffered send
  3733. // path applies, so the same `path` produced different bytes in the request
  3734. // line depending on which API was used. Assert the two agree.
  3735. Server svr;
  3736. std::string target;
  3737. svr.Get(".*", [&](const Request &req, Response &res) {
  3738. target = req.target;
  3739. res.status = StatusCode::OK_200;
  3740. });
  3741. auto port = svr.bind_to_any_port(HOST);
  3742. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3743. auto se = detail::scope_exit([&] {
  3744. svr.stop();
  3745. thread.join();
  3746. ASSERT_FALSE(svr.is_running());
  3747. });
  3748. svr.wait_until_ready();
  3749. struct {
  3750. const char *path;
  3751. const char *expected;
  3752. } cases[] = {
  3753. {"/a b?x=1", "/a%20b?x=1"},
  3754. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3755. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3756. };
  3757. for (const auto &c : cases) {
  3758. Client cli(HOST, port);
  3759. target.clear();
  3760. auto res = cli.Get(c.path);
  3761. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3762. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3763. auto buffered_target = target;
  3764. target.clear();
  3765. auto handle = cli.open_stream("GET", c.path);
  3766. EXPECT_TRUE(handle.is_valid())
  3767. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3768. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3769. }
  3770. }
  3771. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3772. // The `set_path_encode(false)` contract — transmit the supplied target
  3773. // verbatim — must hold for the streaming API too.
  3774. Server svr;
  3775. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3776. std::string target;
  3777. svr.Get("/foo", [&](const Request &req, Response &res) {
  3778. target = req.target;
  3779. res.status = StatusCode::OK_200;
  3780. });
  3781. auto port = svr.bind_to_any_port(HOST);
  3782. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3783. auto se = detail::scope_exit([&] {
  3784. svr.stop();
  3785. thread.join();
  3786. ASSERT_FALSE(svr.is_running());
  3787. });
  3788. svr.wait_until_ready();
  3789. {
  3790. Client cli(HOST, port);
  3791. cli.set_path_encode(false);
  3792. auto handle = cli.open_stream("GET", expected_target);
  3793. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3794. EXPECT_EQ(expected_target, target);
  3795. }
  3796. }
  3797. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3798. // With path encoding enabled a CR/LF in the target is percent-encoded
  3799. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3800. // write_request_line still backstops `set_path_encode(false)`, which is
  3801. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3802. Server svr;
  3803. // Captured before routing: the decoded path contains a newline, which a
  3804. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3805. std::string target;
  3806. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3807. target = req.target;
  3808. res.status = StatusCode::OK_200;
  3809. return Server::HandlerResponse::Handled;
  3810. });
  3811. auto port = svr.bind_to_any_port(HOST);
  3812. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3813. auto se = detail::scope_exit([&] {
  3814. svr.stop();
  3815. thread.join();
  3816. ASSERT_FALSE(svr.is_running());
  3817. });
  3818. svr.wait_until_ready();
  3819. {
  3820. Client cli(HOST, port);
  3821. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3822. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3823. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3824. }
  3825. }
  3826. TEST(PathUrlEncodeTest, ControlCharsInPathAreEncoded) {
  3827. // Every control character is percent-encoded, not just CR/LF, so the target
  3828. // passes the request-target check in write_request_line.
  3829. Server svr;
  3830. std::string target;
  3831. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3832. target = req.target;
  3833. res.status = StatusCode::OK_200;
  3834. return Server::HandlerResponse::Handled;
  3835. });
  3836. auto port = svr.bind_to_any_port(HOST);
  3837. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3838. auto se = detail::scope_exit([&] {
  3839. svr.stop();
  3840. thread.join();
  3841. ASSERT_FALSE(svr.is_running());
  3842. });
  3843. svr.wait_until_ready();
  3844. {
  3845. Client cli(HOST, port);
  3846. auto res = cli.Get("/a\tb\x1b\x7f");
  3847. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3848. EXPECT_EQ("/a%09b%1B%7F", target);
  3849. }
  3850. }
  3851. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3852. // Nothing may reach the wire: a raw CR/LF target would split the request
  3853. // line and inject headers.
  3854. Server svr;
  3855. // Pre-routing so that "not called" means nothing reached the server at all,
  3856. // rather than merely failing to match a handler pattern.
  3857. auto handler_called = false;
  3858. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3859. handler_called = true;
  3860. res.status = StatusCode::OK_200;
  3861. return Server::HandlerResponse::Handled;
  3862. });
  3863. auto port = svr.bind_to_any_port(HOST);
  3864. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3865. auto se = detail::scope_exit([&] {
  3866. svr.stop();
  3867. thread.join();
  3868. ASSERT_FALSE(svr.is_running());
  3869. });
  3870. svr.wait_until_ready();
  3871. {
  3872. Client cli(HOST, port);
  3873. cli.set_path_encode(false);
  3874. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3875. EXPECT_FALSE(handle.is_valid());
  3876. EXPECT_EQ(Error::Write, handle.error);
  3877. EXPECT_FALSE(handler_called);
  3878. }
  3879. }
  3880. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3881. // Which of the two branches runs is decided by whether the query component
  3882. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3883. // an empty query and must still fall back to building one from
  3884. // `req.params`, while a non-empty query must win over `req.params`.
  3885. Server svr;
  3886. std::string target;
  3887. svr.Get("/foo", [&](const Request &req, Response &res) {
  3888. target = req.target;
  3889. res.status = StatusCode::OK_200;
  3890. });
  3891. auto port = svr.bind_to_any_port(HOST);
  3892. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3893. auto se = detail::scope_exit([&] {
  3894. svr.stop();
  3895. thread.join();
  3896. ASSERT_FALSE(svr.is_running());
  3897. });
  3898. svr.wait_until_ready();
  3899. {
  3900. // Trailing `?` -> empty query component -> `req.params` is used.
  3901. Client cli(HOST, port);
  3902. Request req;
  3903. req.method = "GET";
  3904. req.path = "/foo?";
  3905. req.params.emplace("a", "1");
  3906. target.clear();
  3907. auto res = cli.send(req);
  3908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3909. EXPECT_EQ("/foo?a=1", target);
  3910. }
  3911. {
  3912. // Non-empty query in `req.path` -> `req.params` is not appended.
  3913. Client cli(HOST, port);
  3914. Request req;
  3915. req.method = "GET";
  3916. req.path = "/foo?b=2";
  3917. req.params.emplace("a", "1");
  3918. target.clear();
  3919. auto res = cli.send(req);
  3920. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3921. EXPECT_EQ("/foo?b=2", target);
  3922. }
  3923. }
  3924. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3925. Server svr;
  3926. svr.Get("/", [](const Request &req, Response &) {
  3927. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3928. });
  3929. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3930. auto se = detail::scope_exit([&] {
  3931. svr.stop();
  3932. thread.join();
  3933. ASSERT_FALSE(svr.is_running());
  3934. });
  3935. svr.wait_until_ready();
  3936. {
  3937. Client cli(HOST, PORT);
  3938. cli.set_path_encode(false);
  3939. auto res = cli.Get("/?something=%0A");
  3940. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3941. EXPECT_EQ(StatusCode::OK_200, res->status);
  3942. }
  3943. }
  3944. TEST(BindServerTest, BindDualStack) {
  3945. Server svr;
  3946. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3947. res.set_content("Hello World!", "text/plain");
  3948. });
  3949. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3950. auto se = detail::scope_exit([&] {
  3951. svr.stop();
  3952. thread.join();
  3953. ASSERT_FALSE(svr.is_running());
  3954. });
  3955. svr.wait_until_ready();
  3956. {
  3957. Client cli("127.0.0.1", PORT);
  3958. auto res = cli.Get("/1");
  3959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3960. EXPECT_EQ(StatusCode::OK_200, res->status);
  3961. EXPECT_EQ("Hello World!", res->body);
  3962. }
  3963. {
  3964. Client cli("::1", PORT);
  3965. auto res = cli.Get("/1");
  3966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3967. EXPECT_EQ(StatusCode::OK_200, res->status);
  3968. EXPECT_EQ("Hello World!", res->body);
  3969. }
  3970. }
  3971. TEST(BindServerTest, BindAndListenSeparately) {
  3972. Server svr;
  3973. int port = svr.bind_to_any_port("0.0.0.0");
  3974. ASSERT_TRUE(svr.is_valid());
  3975. ASSERT_TRUE(port > 0);
  3976. svr.stop();
  3977. }
  3978. // Reports whether anything is still listening on a loopback port. A plain
  3979. // connect() is used instead of a Client request because a socket left bound by
  3980. // mistake accepts the connection into its backlog and never answers, which
  3981. // would hang the test instead of failing it.
  3982. static bool is_loopback_port_accepting(int port) {
  3983. sockaddr_in addr{};
  3984. addr.sin_family = AF_INET;
  3985. addr.sin_port = htons(static_cast<uint16_t>(port));
  3986. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3987. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3988. EXPECT_NE(sock, INVALID_SOCKET);
  3989. if (sock == INVALID_SOCKET) { return false; }
  3990. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3991. static_cast<socklen_t>(sizeof(addr)));
  3992. detail::close_socket(sock);
  3993. return ret == 0;
  3994. }
  3995. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3996. Server svr;
  3997. auto port = svr.bind_to_any_port("127.0.0.1");
  3998. ASSERT_TRUE(port > 0);
  3999. svr.stop();
  4000. // bind_to_any_port() already called listen(2), so until stop() closed the
  4001. // descriptor the port kept accepting connections into the backlog. ASSERT
  4002. // rather than EXPECT: with the socket still open, the listen_after_bind()
  4003. // below blocks forever in the accept loop.
  4004. ASSERT_FALSE(is_loopback_port_accepting(port));
  4005. // Nothing is left to accept on, so listen_after_bind() must report failure
  4006. // instead of returning success without ever serving.
  4007. EXPECT_FALSE(svr.listen_after_bind());
  4008. // The failed listen marks the server decommissioned, so a waiter returns
  4009. // instead of spinning forever.
  4010. svr.wait_until_ready();
  4011. }
  4012. #ifdef CPPHTTPLIB_SSL_ENABLED
  4013. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  4014. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4015. CLIENT_CA_CERT_DIR);
  4016. int port = svr.bind_to_any_port("0.0.0.0");
  4017. ASSERT_TRUE(svr.is_valid());
  4018. ASSERT_TRUE(port > 0);
  4019. svr.stop();
  4020. }
  4021. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  4022. // or a rejected CustomRoute() registration would not stop the server binding.
  4023. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  4024. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  4025. CLIENT_CA_CERT_DIR);
  4026. ASSERT_TRUE(svr.is_valid());
  4027. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  4028. EXPECT_FALSE(svr.is_valid());
  4029. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  4030. }
  4031. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  4032. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  4033. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  4034. int port = svr.bind_to_any_port("0.0.0.0");
  4035. ASSERT_TRUE(svr.is_valid());
  4036. ASSERT_TRUE(port > 0);
  4037. svr.stop();
  4038. }
  4039. TEST(BindServerTest, UpdateCertsPem) {
  4040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4041. int port = svr.bind_to_any_port("0.0.0.0");
  4042. ASSERT_TRUE(svr.is_valid());
  4043. ASSERT_TRUE(port > 0);
  4044. // Read PEM files
  4045. std::string cert_pem, key_pem, ca_pem;
  4046. read_file(SERVER_CERT_FILE, cert_pem);
  4047. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4048. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4049. // Update server certificates using PEM API
  4050. ASSERT_TRUE(
  4051. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4052. ASSERT_TRUE(svr.is_valid());
  4053. svr.stop();
  4054. }
  4055. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  4056. // Start server with client CA (enables client auth)
  4057. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4058. ASSERT_TRUE(svr.is_valid());
  4059. bool handler_called = false;
  4060. svr.Get("/test", [&](const Request &req, Response &res) {
  4061. handler_called = true;
  4062. // Verify client certificate is present
  4063. auto cert = req.peer_cert();
  4064. EXPECT_TRUE(static_cast<bool>(cert));
  4065. res.set_content("ok", "text/plain");
  4066. });
  4067. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4068. auto se = detail::scope_exit([&] {
  4069. svr.stop();
  4070. t.join();
  4071. ASSERT_FALSE(svr.is_running());
  4072. });
  4073. svr.wait_until_ready();
  4074. // Read PEM files
  4075. std::string cert_pem, key_pem, ca_pem;
  4076. read_file(SERVER_CERT_FILE, cert_pem);
  4077. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4078. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  4079. // Update server certificates and client CA using PEM API while server running
  4080. ASSERT_TRUE(
  4081. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  4082. // Connect with client certificate
  4083. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4084. cli.enable_server_certificate_verification(false);
  4085. cli.set_connection_timeout(30);
  4086. auto res = cli.Get("/test");
  4087. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4088. ASSERT_EQ(StatusCode::OK_200, res->status);
  4089. ASSERT_TRUE(handler_called);
  4090. EXPECT_EQ("ok", res->body);
  4091. }
  4092. // Puts a CA that did not sign the client's certificate in the old one's place.
  4093. static bool replace_client_ca(SSLServer &svr) {
  4094. std::string cert_pem, key_pem, ca_pem;
  4095. read_file(SERVER_CERT_FILE, cert_pem);
  4096. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4097. read_file(SERVER_CERT2_FILE, ca_pem);
  4098. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(),
  4099. ca_pem.c_str());
  4100. }
  4101. TEST(SSLClientServerTest, UpdateCertsPemReplacesClientCA) {
  4102. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4103. ASSERT_TRUE(svr.is_valid());
  4104. svr.Get("/test", [](const Request &, Response &res) {
  4105. res.set_content("ok", "text/plain");
  4106. });
  4107. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4108. auto se = detail::scope_exit([&] {
  4109. svr.stop();
  4110. t.join();
  4111. ASSERT_FALSE(svr.is_running());
  4112. });
  4113. svr.wait_until_ready();
  4114. auto get = [] {
  4115. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4116. cli.enable_server_certificate_verification(false);
  4117. return cli.Get("/test");
  4118. };
  4119. ASSERT_TRUE(get());
  4120. ASSERT_TRUE(replace_client_ca(svr));
  4121. EXPECT_FALSE(get());
  4122. }
  4123. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4124. TEST(SSLClientServerTest, ThrowingVerifyCallbackRejectsTheCertificate) {
  4125. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4126. ASSERT_TRUE(svr.is_valid());
  4127. tls::set_verify_callback(svr.tls_context(),
  4128. [](const tls::VerifyContext &) -> bool {
  4129. throw std::runtime_error("verify");
  4130. });
  4131. svr.Get("/test", [](const Request &, Response &res) {
  4132. res.set_content("ok", "text/plain");
  4133. });
  4134. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4135. auto se = detail::scope_exit([&] {
  4136. svr.stop();
  4137. t.join();
  4138. ASSERT_FALSE(svr.is_running());
  4139. });
  4140. svr.wait_until_ready();
  4141. auto get = [] {
  4142. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  4143. cli.enable_server_certificate_verification(false);
  4144. return cli.Get("/test");
  4145. };
  4146. EXPECT_FALSE(get());
  4147. // The handshake is over, so an update does not wait for it.
  4148. std::string cert_pem, key_pem;
  4149. read_file(SERVER_CERT_FILE, cert_pem);
  4150. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4151. EXPECT_TRUE(svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str()));
  4152. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4153. return v.preverify_ok;
  4154. });
  4155. auto res = get();
  4156. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4157. EXPECT_EQ("ok", res->body);
  4158. }
  4159. #endif
  4160. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  4161. // Sends each request over a new connection with a client certificate,
  4162. // resuming the session of the one before when there is one.
  4163. class ResumingClient {
  4164. public:
  4165. ResumingClient() : ctx_(SSL_CTX_new(TLS_client_method())) {
  4166. SSL_CTX_use_certificate_file(ctx_, CLIENT_CERT_FILE, SSL_FILETYPE_PEM);
  4167. SSL_CTX_use_PrivateKey_file(ctx_, CLIENT_PRIVATE_KEY_FILE,
  4168. SSL_FILETYPE_PEM);
  4169. // BoringSSL hands out a resumable TLS 1.3 session only through this
  4170. // callback, not through SSL_get1_session().
  4171. SSL_CTX_set_app_data(ctx_, this);
  4172. SSL_CTX_set_session_cache_mode(ctx_, SSL_SESS_CACHE_CLIENT |
  4173. SSL_SESS_CACHE_NO_INTERNAL_STORE);
  4174. SSL_CTX_sess_set_new_cb(ctx_, [](SSL *ssl, SSL_SESSION *session) {
  4175. auto self = static_cast<ResumingClient *>(
  4176. SSL_CTX_get_app_data(SSL_get_SSL_CTX(ssl)));
  4177. SSL_SESSION_free(self->session_);
  4178. self->session_ = session;
  4179. return 1; // Keeps the reference
  4180. });
  4181. }
  4182. ~ResumingClient() {
  4183. SSL_SESSION_free(session_);
  4184. SSL_CTX_free(ctx_);
  4185. }
  4186. // Tells whether the request was answered.
  4187. bool get() {
  4188. auto error = Error::Success;
  4189. auto sock = detail::create_client_socket(
  4190. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4191. /*connection_timeout_sec=*/5, 0,
  4192. /*read_timeout_sec=*/5, 0,
  4193. /*write_timeout_sec=*/5, 0, std::string(), error);
  4194. if (sock == INVALID_SOCKET) { return false; }
  4195. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4196. auto ssl = SSL_new(ctx_);
  4197. auto ssl_se = detail::scope_exit([&] { SSL_free(ssl); });
  4198. SSL_set_fd(ssl, static_cast<int>(sock));
  4199. if (session_) { SSL_set_session(ssl, session_); }
  4200. if (SSL_connect(ssl) != 1) { return false; }
  4201. reused_ = SSL_session_reused(ssl) == 1;
  4202. // Reading the response also takes in a TLS 1.3 session ticket.
  4203. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4204. "Connection: close\r\n\r\n";
  4205. SSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4206. std::string res;
  4207. char buf[256];
  4208. int n;
  4209. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  4210. res.append(buf, static_cast<size_t>(n));
  4211. }
  4212. // Without a proper shutdown, OpenSSL marks the session not resumable.
  4213. SSL_shutdown(ssl);
  4214. return res.find("200 OK") != std::string::npos;
  4215. }
  4216. // Whether the last connection resumed a session
  4217. bool reused() const { return reused_; }
  4218. private:
  4219. SSL_CTX *ctx_;
  4220. SSL_SESSION *session_ = nullptr;
  4221. bool reused_ = false;
  4222. };
  4223. // A client that resumes its session gets through, but not once the client CA
  4224. // has changed, as a resumed session does not show the certificate again.
  4225. TEST(SSLClientServerTest, ClientResumesSessionUntilClientCAChanges) {
  4226. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4227. ASSERT_TRUE(svr.is_valid());
  4228. svr.Get("/test", [](const Request &, Response &res) {
  4229. res.set_content("ok", "text/plain");
  4230. });
  4231. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4232. auto se = detail::scope_exit([&] {
  4233. svr.stop();
  4234. t.join();
  4235. ASSERT_FALSE(svr.is_running());
  4236. });
  4237. svr.wait_until_ready();
  4238. ResumingClient cli;
  4239. ASSERT_TRUE(cli.get());
  4240. ASSERT_TRUE(cli.get());
  4241. EXPECT_TRUE(cli.reused());
  4242. ASSERT_TRUE(replace_client_ca(svr));
  4243. EXPECT_FALSE(cli.get());
  4244. }
  4245. // A resumed session does not show the certificate again, so the server does
  4246. // not resume one with a verify callback to run on it.
  4247. TEST(SSLClientServerTest, NoSessionResumptionWithVerifyCallback) {
  4248. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4249. ASSERT_TRUE(svr.is_valid());
  4250. tls::set_verify_callback(svr.tls_context(), [](const tls::VerifyContext &v) {
  4251. return v.preverify_ok;
  4252. });
  4253. svr.Get("/test", [](const Request &, Response &res) {
  4254. res.set_content("ok", "text/plain");
  4255. });
  4256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4257. auto se = detail::scope_exit([&] {
  4258. svr.stop();
  4259. t.join();
  4260. ASSERT_FALSE(svr.is_running());
  4261. });
  4262. svr.wait_until_ready();
  4263. ResumingClient cli;
  4264. ASSERT_TRUE(cli.get());
  4265. ASSERT_TRUE(cli.get());
  4266. EXPECT_FALSE(cli.reused());
  4267. }
  4268. #endif
  4269. #ifdef CPPHTTPLIB_WOLFSSL_SUPPORT
  4270. // wolfSSL shares its session cache between contexts, so a resumed session
  4271. // could carry a client certificate checked against another server's CA, or
  4272. // against a client CA since replaced.
  4273. TEST(SSLClientServerTest, ClientSessionIsNotResumedPastItsCA) {
  4274. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  4275. ASSERT_TRUE(svr.is_valid());
  4276. // Trusts a CA that did not sign the client's certificate.
  4277. SSLServer other(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, SERVER_CERT2_FILE);
  4278. ASSERT_TRUE(other.is_valid());
  4279. for (auto s : {&svr, &other}) {
  4280. s->Get("/test", [](const Request &, Response &res) {
  4281. res.set_content("ok", "text/plain");
  4282. });
  4283. }
  4284. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4285. thread t2 = thread([&]() { ASSERT_TRUE(other.listen(HOST, PORT + 1)); });
  4286. auto se = detail::scope_exit([&] {
  4287. other.stop();
  4288. svr.stop();
  4289. t2.join();
  4290. t.join();
  4291. });
  4292. svr.wait_until_ready();
  4293. other.wait_until_ready();
  4294. auto ctx = wolfSSL_CTX_new(wolfTLSv1_2_client_method());
  4295. auto ctx_se = detail::scope_exit([&] { wolfSSL_CTX_free(ctx); });
  4296. wolfSSL_CTX_set_verify(ctx, WOLFSSL_VERIFY_NONE, nullptr);
  4297. ASSERT_EQ(WOLFSSL_SUCCESS, wolfSSL_CTX_use_certificate_file(
  4298. ctx, CLIENT_CERT_FILE, WOLFSSL_FILETYPE_PEM));
  4299. ASSERT_EQ(WOLFSSL_SUCCESS,
  4300. wolfSSL_CTX_use_PrivateKey_file(ctx, CLIENT_PRIVATE_KEY_FILE,
  4301. WOLFSSL_FILETYPE_PEM));
  4302. WOLFSSL_SESSION *session = nullptr;
  4303. auto session_se = detail::scope_exit([&] {
  4304. if (session) { wolfSSL_SESSION_free(session); }
  4305. });
  4306. // A request over a new connection, resuming `session` when there is one and
  4307. // keeping the connection's own in its place. Tells whether it was answered.
  4308. auto get = [&](int port) {
  4309. auto error = Error::Success;
  4310. auto sock = detail::create_client_socket(
  4311. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  4312. /*connection_timeout_sec=*/5, 0,
  4313. /*read_timeout_sec=*/5, 0,
  4314. /*write_timeout_sec=*/5, 0, std::string(), error);
  4315. if (sock == INVALID_SOCKET) { return false; }
  4316. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  4317. auto ssl = wolfSSL_new(ctx);
  4318. auto ssl_se = detail::scope_exit([&] { wolfSSL_free(ssl); });
  4319. wolfSSL_set_fd(ssl, static_cast<int>(sock));
  4320. if (session) { wolfSSL_set_session(ssl, session); }
  4321. if (wolfSSL_connect(ssl) != WOLFSSL_SUCCESS) { return false; }
  4322. std::string req = "GET /test HTTP/1.1\r\nHost: x\r\n"
  4323. "Connection: close\r\n\r\n";
  4324. wolfSSL_write(ssl, req.data(), static_cast<int>(req.size()));
  4325. std::string res;
  4326. char buf[256];
  4327. int n;
  4328. while ((n = wolfSSL_read(ssl, buf, sizeof(buf))) > 0) {
  4329. res.append(buf, static_cast<size_t>(n));
  4330. }
  4331. wolfSSL_shutdown(ssl);
  4332. if (session) { wolfSSL_SESSION_free(session); }
  4333. session = wolfSSL_get1_session(ssl);
  4334. return res.find("200 OK") != std::string::npos;
  4335. };
  4336. ASSERT_TRUE(get(PORT));
  4337. EXPECT_FALSE(get(PORT + 1));
  4338. ASSERT_TRUE(get(PORT));
  4339. ASSERT_TRUE(replace_client_ca(svr));
  4340. EXPECT_FALSE(get(PORT));
  4341. }
  4342. #endif
  4343. TEST(SSLClientServerTest, UpdateCertsPemWaitsForHandshakeInProgress) {
  4344. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4345. ASSERT_TRUE(svr.is_valid());
  4346. svr.Get("/test", [](const Request &, Response &res) {
  4347. res.set_content("ok", "text/plain");
  4348. });
  4349. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  4350. auto se = detail::scope_exit([&] {
  4351. svr.stop();
  4352. t.join();
  4353. ASSERT_FALSE(svr.is_running());
  4354. });
  4355. svr.wait_until_ready();
  4356. // A connection that sends no ClientHello keeps its handshake in progress,
  4357. // once the server has had a moment to start it.
  4358. auto error = Error::Success;
  4359. auto sock = detail::create_client_socket(
  4360. HOST, "", PORT, AF_UNSPEC, false, false, nullptr,
  4361. /*connection_timeout_sec=*/5, 0,
  4362. /*read_timeout_sec=*/5, 0,
  4363. /*write_timeout_sec=*/5, 0, std::string(), error);
  4364. ASSERT_NE(INVALID_SOCKET, sock);
  4365. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  4366. std::string cert_pem, key_pem;
  4367. read_file(SERVER_CERT_FILE, cert_pem);
  4368. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  4369. auto update = std::async(std::launch::async, [&]() {
  4370. return svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str());
  4371. });
  4372. EXPECT_EQ(std::future_status::timeout,
  4373. update.wait_for(std::chrono::milliseconds(200)));
  4374. detail::close_socket(sock);
  4375. EXPECT_TRUE(update.get());
  4376. SSLClient cli(HOST, PORT);
  4377. cli.enable_server_certificate_verification(false);
  4378. auto res = cli.Get("/test");
  4379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4380. EXPECT_EQ(StatusCode::OK_200, res->status);
  4381. }
  4382. #endif
  4383. TEST(ErrorHandlerTest, ContentLength) {
  4384. Server svr;
  4385. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4386. res.status = StatusCode::OK_200;
  4387. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4388. "text/html"); // <= Content-Length still 13
  4389. });
  4390. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4391. res.set_content("Hello World!\n", "text/plain");
  4392. res.status = 524;
  4393. });
  4394. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4395. auto se = detail::scope_exit([&] {
  4396. svr.stop();
  4397. thread.join();
  4398. ASSERT_FALSE(svr.is_running());
  4399. });
  4400. svr.wait_until_ready();
  4401. {
  4402. Client cli(HOST, PORT);
  4403. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4404. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4405. EXPECT_EQ(StatusCode::OK_200, res->status);
  4406. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4407. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4408. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4409. }
  4410. }
  4411. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4412. TEST(ExceptionTest, WithoutExceptionHandler) {
  4413. Server svr;
  4414. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  4415. throw std::runtime_error("exception...");
  4416. });
  4417. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  4418. throw std::runtime_error("exception\r\n...");
  4419. });
  4420. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  4421. auto se = detail::scope_exit([&] {
  4422. svr.stop();
  4423. listen_thread.join();
  4424. ASSERT_FALSE(svr.is_running());
  4425. });
  4426. svr.wait_until_ready();
  4427. Client cli("localhost", PORT);
  4428. {
  4429. auto res = cli.Get("/exception");
  4430. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4431. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4432. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4433. }
  4434. {
  4435. auto res = cli.Get("/unknown");
  4436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4437. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4438. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  4439. }
  4440. }
  4441. TEST(ExceptionTest, WithExceptionHandler) {
  4442. Server svr;
  4443. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  4444. std::exception_ptr ep) {
  4445. EXPECT_FALSE(ep == nullptr);
  4446. try {
  4447. std::rethrow_exception(ep);
  4448. } catch (std::exception &e) {
  4449. EXPECT_EQ("abc", std::string(e.what()));
  4450. } catch (...) {}
  4451. res.status = StatusCode::InternalServerError_500;
  4452. res.set_content("abcdefghijklmnopqrstuvwxyz",
  4453. "text/html"); // <= Content-Length still 13 at this point
  4454. });
  4455. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4456. res.set_content("Hello World!\n", "text/plain");
  4457. throw std::runtime_error("abc");
  4458. });
  4459. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4460. auto se = detail::scope_exit([&] {
  4461. svr.stop();
  4462. thread.join();
  4463. ASSERT_FALSE(svr.is_running());
  4464. });
  4465. svr.wait_until_ready();
  4466. for (size_t i = 0; i < 10; i++) {
  4467. Client cli(HOST, PORT);
  4468. for (size_t j = 0; j < 100; j++) {
  4469. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4470. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4471. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4472. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4473. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4474. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4475. }
  4476. cli.set_keep_alive(true);
  4477. for (size_t j = 0; j < 100; j++) {
  4478. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  4479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4480. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4481. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4482. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  4483. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  4484. }
  4485. }
  4486. }
  4487. TEST(ExceptionTest, StatusIs500UnlessExceptionHandlerSetsIt) {
  4488. Server svr;
  4489. svr.set_exception_handler(
  4490. [](const Request &, Response &res, std::exception_ptr) {
  4491. res.set_content("oops", "text/plain");
  4492. });
  4493. svr.Get("/throw", [](const Request &, Response &) {
  4494. throw std::runtime_error("throw");
  4495. });
  4496. svr.Get("/created-then-throw", [](const Request &, Response &res) {
  4497. res.status = StatusCode::Created_201;
  4498. throw std::runtime_error("created-then-throw");
  4499. });
  4500. auto port = svr.bind_to_any_port(HOST);
  4501. ASSERT_GT(port, 0);
  4502. thread t = thread([&] { svr.listen_after_bind(); });
  4503. auto se = detail::scope_exit([&] {
  4504. svr.stop();
  4505. t.join();
  4506. ASSERT_FALSE(svr.is_running());
  4507. });
  4508. svr.wait_until_ready();
  4509. Client cli(HOST, port);
  4510. for (auto path : {"/throw", "/created-then-throw"}) {
  4511. auto res = cli.Get(path);
  4512. ASSERT_TRUE(res) << path << ": " << to_string(res.error());
  4513. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  4514. }
  4515. }
  4516. TEST(ExceptionTest, AndErrorHandler) {
  4517. Server svr;
  4518. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4519. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  4520. });
  4521. svr.set_exception_handler(
  4522. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  4523. EXPECT_FALSE(ep == nullptr);
  4524. try {
  4525. std::rethrow_exception(ep);
  4526. } catch (std::exception &e) {
  4527. res.set_content(e.what(), "text/html");
  4528. } catch (...) {}
  4529. res.status = StatusCode::InternalServerError_500;
  4530. });
  4531. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  4532. throw std::runtime_error("EXCEPTION");
  4533. });
  4534. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  4535. res.set_content("ERROR", "text/html");
  4536. res.status = StatusCode::InternalServerError_500;
  4537. });
  4538. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4539. auto se = detail::scope_exit([&] {
  4540. svr.stop();
  4541. thread.join();
  4542. ASSERT_FALSE(svr.is_running());
  4543. });
  4544. svr.wait_until_ready();
  4545. Client cli(HOST, PORT);
  4546. {
  4547. auto res = cli.Get("/exception");
  4548. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4549. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  4550. EXPECT_EQ("EXCEPTION", res->body);
  4551. }
  4552. {
  4553. auto res = cli.Get("/error");
  4554. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4555. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  4556. EXPECT_EQ("ERROR", res->body);
  4557. }
  4558. {
  4559. auto res = cli.Get("/invalid");
  4560. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4561. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4562. EXPECT_EQ("NOT_FOUND", res->body);
  4563. }
  4564. }
  4565. #endif
  4566. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4567. // An exception from a user callback outside process_request()'s try/catch
  4568. // used to unwind into the task queue - which does not catch - and terminate
  4569. // the process. Each test below runs the server on a single worker thread: a
  4570. // guard that catches the exception but still loses the thread would otherwise
  4571. // be hidden by a spare worker serving the follow-up request. Note that a
  4572. // regression here aborts the whole test binary rather than failing one test.
  4573. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  4574. Server svr;
  4575. svr.new_task_queue = [] { return new ThreadPool(1); };
  4576. std::atomic<int> reported{0};
  4577. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4578. if (err == Error::UserCallbackException) { reported++; }
  4579. });
  4580. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4581. res.set_content_provider(
  4582. 1024, "text/plain",
  4583. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4584. sink.write("hello", 5);
  4585. throw std::runtime_error("from the content provider");
  4586. });
  4587. });
  4588. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4589. res.set_content("ok", "text/plain");
  4590. });
  4591. auto port = svr.bind_to_any_port(HOST);
  4592. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4593. auto se = detail::scope_exit([&] {
  4594. svr.stop();
  4595. listen_thread.join();
  4596. ASSERT_FALSE(svr.is_running());
  4597. });
  4598. svr.wait_until_ready();
  4599. {
  4600. Client cli(HOST, port);
  4601. cli.set_read_timeout(5, 0);
  4602. EXPECT_FALSE(cli.Get("/throw"));
  4603. }
  4604. EXPECT_TRUE(svr.is_running());
  4605. EXPECT_EQ(1, reported.load());
  4606. // A request on a fresh connection is still served.
  4607. {
  4608. Client cli(HOST, port);
  4609. auto res = cli.Get("/ok");
  4610. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4611. EXPECT_EQ(StatusCode::OK_200, res->status);
  4612. EXPECT_EQ("ok", res->body);
  4613. }
  4614. }
  4615. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  4616. Server svr;
  4617. svr.new_task_queue = [] { return new ThreadPool(1); };
  4618. std::atomic<bool> should_throw{true};
  4619. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4620. res.set_content("hi", "text/plain");
  4621. });
  4622. svr.set_post_routing_handler(
  4623. [&](const Request & /*req*/, Response & /*res*/) {
  4624. if (should_throw) {
  4625. throw std::runtime_error("from the post-routing handler");
  4626. }
  4627. });
  4628. auto port = svr.bind_to_any_port(HOST);
  4629. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4630. auto se = detail::scope_exit([&] {
  4631. svr.stop();
  4632. listen_thread.join();
  4633. ASSERT_FALSE(svr.is_running());
  4634. });
  4635. svr.wait_until_ready();
  4636. {
  4637. Client cli(HOST, port);
  4638. cli.set_read_timeout(5, 0);
  4639. EXPECT_FALSE(cli.Get("/hi"));
  4640. }
  4641. EXPECT_TRUE(svr.is_running());
  4642. should_throw = false;
  4643. {
  4644. Client cli(HOST, port);
  4645. auto res = cli.Get("/hi");
  4646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4647. EXPECT_EQ(StatusCode::OK_200, res->status);
  4648. EXPECT_EQ("hi", res->body);
  4649. }
  4650. }
  4651. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  4652. // The guard reports the caught exception through the error logger, which is
  4653. // a user callback too. A logger that throws has to be contained as well, or
  4654. // the process would terminate from inside the catch.
  4655. Server svr;
  4656. svr.new_task_queue = [] { return new ThreadPool(1); };
  4657. std::atomic<int> reported{0};
  4658. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4659. if (err == Error::UserCallbackException) {
  4660. reported++;
  4661. throw std::runtime_error("from the error logger");
  4662. }
  4663. });
  4664. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4665. res.set_content_provider(
  4666. 1024, "text/plain",
  4667. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4668. sink.write("hello", 5);
  4669. throw std::runtime_error("from the content provider");
  4670. });
  4671. });
  4672. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4673. res.set_content("ok", "text/plain");
  4674. });
  4675. auto port = svr.bind_to_any_port(HOST);
  4676. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4677. auto se = detail::scope_exit([&] {
  4678. svr.stop();
  4679. listen_thread.join();
  4680. ASSERT_FALSE(svr.is_running());
  4681. });
  4682. svr.wait_until_ready();
  4683. {
  4684. Client cli(HOST, port);
  4685. cli.set_read_timeout(5, 0);
  4686. EXPECT_FALSE(cli.Get("/throw"));
  4687. }
  4688. EXPECT_TRUE(svr.is_running());
  4689. EXPECT_EQ(1, reported.load());
  4690. {
  4691. Client cli(HOST, port);
  4692. auto res = cli.Get("/ok");
  4693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4694. EXPECT_EQ(StatusCode::OK_200, res->status);
  4695. EXPECT_EQ("ok", res->body);
  4696. }
  4697. }
  4698. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  4699. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  4700. // so the exception unwinds through the ws::WebSocket object on its way to
  4701. // the guard. None of the HTTP cases above cross that.
  4702. Server svr;
  4703. svr.new_task_queue = [] { return new ThreadPool(1); };
  4704. std::atomic<int> reported{0};
  4705. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4706. if (err == Error::UserCallbackException) { reported++; }
  4707. });
  4708. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  4709. throw std::runtime_error("from the WebSocket handler");
  4710. });
  4711. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4712. res.set_content("ok", "text/plain");
  4713. });
  4714. auto port = svr.bind_to_any_port(HOST);
  4715. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4716. auto se = detail::scope_exit([&] {
  4717. svr.stop();
  4718. listen_thread.join();
  4719. ASSERT_FALSE(svr.is_running());
  4720. });
  4721. svr.wait_until_ready();
  4722. {
  4723. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  4724. "/ws");
  4725. auto res = client.connect();
  4726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4727. // The server dropped the connection instead of dying.
  4728. std::string msg;
  4729. EXPECT_FALSE(client.read(msg));
  4730. client.close();
  4731. }
  4732. EXPECT_TRUE(svr.is_running());
  4733. EXPECT_EQ(1, reported.load());
  4734. {
  4735. Client cli(HOST, port);
  4736. auto res = cli.Get("/ok");
  4737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4738. EXPECT_EQ(StatusCode::OK_200, res->status);
  4739. EXPECT_EQ("ok", res->body);
  4740. }
  4741. }
  4742. #ifdef CPPHTTPLIB_SSL_ENABLED
  4743. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  4744. // SSLServer::process_and_close_socket() is a separate overload with its own
  4745. // guard, so it is exercised on its own.
  4746. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4747. ASSERT_TRUE(svr.is_valid());
  4748. svr.new_task_queue = [] { return new ThreadPool(1); };
  4749. std::atomic<int> reported{0};
  4750. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  4751. if (err == Error::UserCallbackException) { reported++; }
  4752. });
  4753. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  4754. res.set_content_provider(
  4755. 1024, "text/plain",
  4756. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  4757. sink.write("hello", 5);
  4758. throw std::runtime_error("from the content provider");
  4759. });
  4760. });
  4761. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  4762. res.set_content("ok", "text/plain");
  4763. });
  4764. auto port = svr.bind_to_any_port(HOST);
  4765. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  4766. auto se = detail::scope_exit([&] {
  4767. svr.stop();
  4768. listen_thread.join();
  4769. ASSERT_FALSE(svr.is_running());
  4770. });
  4771. svr.wait_until_ready();
  4772. {
  4773. SSLClient cli(HOST, port);
  4774. cli.enable_server_certificate_verification(false);
  4775. cli.set_read_timeout(5, 0);
  4776. EXPECT_FALSE(cli.Get("/throw"));
  4777. }
  4778. EXPECT_TRUE(svr.is_running());
  4779. EXPECT_EQ(1, reported.load());
  4780. {
  4781. SSLClient cli(HOST, port);
  4782. cli.enable_server_certificate_verification(false);
  4783. auto res = cli.Get("/ok");
  4784. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4785. EXPECT_EQ(StatusCode::OK_200, res->status);
  4786. EXPECT_EQ("ok", res->body);
  4787. }
  4788. }
  4789. #endif
  4790. #endif
  4791. TEST(NoContentTest, ContentLength) {
  4792. Server svr;
  4793. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4794. res.status = StatusCode::NoContent_204;
  4795. });
  4796. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4797. auto se = detail::scope_exit([&] {
  4798. svr.stop();
  4799. thread.join();
  4800. ASSERT_FALSE(svr.is_running());
  4801. });
  4802. svr.wait_until_ready();
  4803. {
  4804. Client cli(HOST, PORT);
  4805. auto res = cli.Get("/hi");
  4806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4807. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4808. // RFC 9110 8.6: none in a 204 response
  4809. EXPECT_FALSE(res->has_header("Content-Length"));
  4810. }
  4811. }
  4812. TEST(ResponseFramingTest, HandlerFramingHeadersAreReplaced) {
  4813. Server svr;
  4814. svr.Get("/body", [](const Request & /*req*/, Response &res) {
  4815. res.set_header("Content-Length", "5");
  4816. res.set_content("hello world", "text/plain");
  4817. });
  4818. svr.Get("/chunked", [](const Request & /*req*/, Response &res) {
  4819. // A body that reads as the last chunk, were it taken as chunked
  4820. res.set_header("Transfer-Encoding", "chunked");
  4821. res.set_content("0\r\n\r\n", "text/plain");
  4822. });
  4823. svr.Get("/provider", [](const Request & /*req*/, Response &res) {
  4824. res.set_header("Content-Length", "2");
  4825. res.set_content_provider(5, "text/plain",
  4826. [](size_t offset, size_t length, DataSink &sink) {
  4827. sink.write(&"hello"[offset], length);
  4828. return true;
  4829. });
  4830. });
  4831. svr.Get("/empty", [](const Request & /*req*/, Response &res) {
  4832. res.set_header("Content-Length", "1234");
  4833. });
  4834. thread t = thread([&] { svr.listen(HOST, PORT); });
  4835. auto se = detail::scope_exit([&] {
  4836. svr.stop();
  4837. t.join();
  4838. ASSERT_FALSE(svr.is_running());
  4839. });
  4840. svr.wait_until_ready();
  4841. Client cli(HOST, PORT);
  4842. cli.set_read_timeout(1, 0);
  4843. auto expect_body = [&](const Result &res, const std::string &body) {
  4844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4845. EXPECT_EQ(body, res->body);
  4846. EXPECT_EQ(1u, res->get_header_value_count("Content-Length"));
  4847. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4848. };
  4849. Headers identity{{"Accept-Encoding", ""}};
  4850. expect_body(cli.Get("/body", identity), "hello world");
  4851. expect_body(cli.Get("/chunked", identity), "0\r\n\r\n");
  4852. expect_body(cli.Get("/body",
  4853. Headers{{"Accept-Encoding", ""}, {"Range", "bytes=0-1"}}),
  4854. "he");
  4855. expect_body(cli.Get("/provider", identity), "hello");
  4856. expect_body(cli.Get("/empty", identity), "");
  4857. // A HEAD response may give the length of the body a GET would get.
  4858. auto res = cli.Head("/empty");
  4859. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4860. EXPECT_EQ("1234", res->get_header_value("Content-Length"));
  4861. }
  4862. TEST(ResponseFramingTest, PostRoutingHandlerChangesAreFramed) {
  4863. Server svr;
  4864. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4865. res.set_content("short", "text/plain");
  4866. });
  4867. svr.set_post_routing_handler([](const Request & /*req*/, Response &res) {
  4868. res.body += " with a footer";
  4869. res.set_header("Transfer-Encoding", "chunked");
  4870. });
  4871. thread t = thread([&] { svr.listen(HOST, PORT); });
  4872. auto se = detail::scope_exit([&] {
  4873. svr.stop();
  4874. t.join();
  4875. ASSERT_FALSE(svr.is_running());
  4876. });
  4877. svr.wait_until_ready();
  4878. Client cli(HOST, PORT);
  4879. cli.set_read_timeout(1, 0);
  4880. auto res = cli.Get("/", Headers{{"Accept-Encoding", ""}});
  4881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4882. EXPECT_EQ("short with a footer", res->body);
  4883. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  4884. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  4885. }
  4886. TEST(ResponseFramingTest, BodyWithoutLengthEndsWithTheConnection) {
  4887. Server svr;
  4888. svr.Get("/", [](const Request & /*req*/, Response &res) {
  4889. res.set_header("Content-Length", "3");
  4890. res.set_content_provider("text/plain", [](size_t, DataSink &sink) {
  4891. sink.write("abc", 3);
  4892. sink.done();
  4893. return true;
  4894. });
  4895. });
  4896. thread t = thread([&] { svr.listen(HOST, PORT); });
  4897. auto se = detail::scope_exit([&] {
  4898. svr.stop();
  4899. t.join();
  4900. ASSERT_FALSE(svr.is_running());
  4901. });
  4902. svr.wait_until_ready();
  4903. Client cli(HOST, PORT);
  4904. cli.set_keep_alive(true);
  4905. auto res = cli.Get("/");
  4906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4907. EXPECT_EQ("abc", res->body);
  4908. EXPECT_FALSE(res->has_header("Content-Length"));
  4909. EXPECT_EQ("close", res->get_header_value("Connection"));
  4910. EXPECT_FALSE(res->has_header("Keep-Alive"));
  4911. // No body to delimit
  4912. auto head = cli.Head("/");
  4913. ASSERT_TRUE(head) << "Error: " << to_string(head.error());
  4914. EXPECT_FALSE(head->has_header("Connection"));
  4915. }
  4916. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4917. #ifdef CPPHTTPLIB_SSL_ENABLED
  4918. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4919. ASSERT_TRUE(svr.is_valid());
  4920. #else
  4921. Server svr;
  4922. #endif
  4923. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4924. if (req.path == "/routing_handler") {
  4925. res.set_header("PRE_ROUTING", "on");
  4926. res.set_content("Routing Handler", "text/plain");
  4927. return httplib::Server::HandlerResponse::Handled;
  4928. }
  4929. return httplib::Server::HandlerResponse::Unhandled;
  4930. });
  4931. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4932. res.set_content("Error", "text/html");
  4933. });
  4934. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4935. if (req.path == "/routing_handler") {
  4936. res.set_header("POST_ROUTING", "on");
  4937. }
  4938. });
  4939. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4940. res.set_content("Hello World!\n", "text/plain");
  4941. });
  4942. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4943. auto se = detail::scope_exit([&] {
  4944. svr.stop();
  4945. thread.join();
  4946. ASSERT_FALSE(svr.is_running());
  4947. });
  4948. svr.wait_until_ready();
  4949. {
  4950. #ifdef CPPHTTPLIB_SSL_ENABLED
  4951. SSLClient cli(HOST, PORT);
  4952. cli.enable_server_certificate_verification(false);
  4953. #else
  4954. Client cli(HOST, PORT);
  4955. #endif
  4956. auto res = cli.Get("/routing_handler");
  4957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4958. EXPECT_EQ(StatusCode::OK_200, res->status);
  4959. EXPECT_EQ("Routing Handler", res->body);
  4960. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4961. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4962. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4963. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4964. }
  4965. {
  4966. #ifdef CPPHTTPLIB_SSL_ENABLED
  4967. SSLClient cli(HOST, PORT);
  4968. cli.enable_server_certificate_verification(false);
  4969. #else
  4970. Client cli(HOST, PORT);
  4971. #endif
  4972. auto res = cli.Get("/hi");
  4973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4974. EXPECT_EQ(StatusCode::OK_200, res->status);
  4975. EXPECT_EQ("Hello World!\n", res->body);
  4976. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4977. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4978. }
  4979. {
  4980. #ifdef CPPHTTPLIB_SSL_ENABLED
  4981. SSLClient cli(HOST, PORT);
  4982. cli.enable_server_certificate_verification(false);
  4983. #else
  4984. Client cli(HOST, PORT);
  4985. #endif
  4986. auto res = cli.Get("/aaa");
  4987. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4988. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4989. EXPECT_EQ("Error", res->body);
  4990. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4991. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4992. }
  4993. }
  4994. TEST(RequestHandlerTest, PreRequestHandler) {
  4995. auto route_path = "/user/:user";
  4996. Server svr;
  4997. svr.Get("/hi", [](const Request &, Response &res) {
  4998. res.set_content("hi", "text/plain");
  4999. });
  5000. svr.Get(route_path, [](const Request &req, Response &res) {
  5001. res.set_content(req.path_params.at("user"), "text/plain");
  5002. });
  5003. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  5004. if (req.matched_route == route_path) {
  5005. auto user = req.path_params.at("user");
  5006. if (user != "john") {
  5007. res.status = StatusCode::Forbidden_403;
  5008. res.set_content("error", "text/html");
  5009. return Server::HandlerResponse::Handled;
  5010. }
  5011. }
  5012. return Server::HandlerResponse::Unhandled;
  5013. });
  5014. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5015. auto se = detail::scope_exit([&] {
  5016. svr.stop();
  5017. thread.join();
  5018. ASSERT_FALSE(svr.is_running());
  5019. });
  5020. svr.wait_until_ready();
  5021. Client cli(HOST, PORT);
  5022. {
  5023. auto res = cli.Get("/hi");
  5024. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5025. EXPECT_EQ(StatusCode::OK_200, res->status);
  5026. EXPECT_EQ("hi", res->body);
  5027. }
  5028. {
  5029. auto res = cli.Get("/user/john");
  5030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5031. EXPECT_EQ(StatusCode::OK_200, res->status);
  5032. EXPECT_EQ("john", res->body);
  5033. }
  5034. {
  5035. auto res = cli.Get("/user/invalid-user");
  5036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5037. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5038. EXPECT_EQ("error", res->body);
  5039. }
  5040. }
  5041. // The pre-request handler must run before the request body is read, so a
  5042. // rejected request never forces the server to buffer a (potentially large)
  5043. // body. Here the posted body is larger than the payload limit: if the body
  5044. // were read first the server would answer 413, but because the pre-request
  5045. // handler runs first it answers 403 and the body is never read.
  5046. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  5047. Server svr;
  5048. svr.set_payload_max_length(8);
  5049. auto handler_ran = false;
  5050. svr.Post("/reject", [&](const Request &req, Response &res) {
  5051. handler_ran = true;
  5052. res.set_content(req.body, "text/plain");
  5053. });
  5054. svr.Post("/accept", [](const Request &req, Response &res) {
  5055. res.set_content(req.body, "text/plain");
  5056. });
  5057. svr.set_pre_request_handler([](const Request &req, Response &res) {
  5058. if (req.matched_route == "/reject") {
  5059. res.status = StatusCode::Forbidden_403;
  5060. res.set_content("denied", "text/plain");
  5061. return Server::HandlerResponse::Handled;
  5062. }
  5063. return Server::HandlerResponse::Unhandled;
  5064. });
  5065. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5066. auto se = detail::scope_exit([&] {
  5067. svr.stop();
  5068. thread.join();
  5069. ASSERT_FALSE(svr.is_running());
  5070. });
  5071. svr.wait_until_ready();
  5072. Client cli(HOST, PORT);
  5073. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  5074. // rejects with 403 before the body is read, so 413 is never reached.
  5075. {
  5076. auto res = cli.Post("/reject", "0123456789", "text/plain");
  5077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5078. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  5079. EXPECT_EQ("denied", res->body);
  5080. EXPECT_FALSE(handler_ran);
  5081. }
  5082. // An approved route still reads the body and enforces the payload limit.
  5083. {
  5084. auto res = cli.Post("/accept", "0123456789", "text/plain");
  5085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5086. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  5087. }
  5088. }
  5089. TEST(UserDataTest, BasicOperations) {
  5090. httplib::UserData ud;
  5091. // Initially empty
  5092. EXPECT_FALSE(ud.has("key"));
  5093. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5094. // set and get
  5095. ud.set("key", 42);
  5096. EXPECT_TRUE(ud.has("key"));
  5097. auto *p = ud.get<int>("key");
  5098. ASSERT_NE(nullptr, p);
  5099. EXPECT_EQ(42, *p);
  5100. // Type mismatch → nullptr
  5101. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  5102. // Overwrite with different type
  5103. ud.set("key", std::string("hello"));
  5104. EXPECT_EQ(nullptr, ud.get<int>("key"));
  5105. auto *s = ud.get<std::string>("key");
  5106. ASSERT_NE(nullptr, s);
  5107. EXPECT_EQ("hello", *s);
  5108. // erase
  5109. ud.erase("key");
  5110. EXPECT_FALSE(ud.has("key"));
  5111. // clear
  5112. ud.set("a", 1);
  5113. ud.set("b", 2);
  5114. ud.clear();
  5115. EXPECT_FALSE(ud.has("a"));
  5116. EXPECT_FALSE(ud.has("b"));
  5117. }
  5118. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  5119. struct AuthCtx {
  5120. std::string user_id;
  5121. };
  5122. Server svr;
  5123. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  5124. res.user_data.set("auth", AuthCtx{"alice"});
  5125. return Server::HandlerResponse::Unhandled;
  5126. });
  5127. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  5128. auto *ctx = res.user_data.get<AuthCtx>("auth");
  5129. ASSERT_NE(nullptr, ctx);
  5130. res.set_content("Hello " + ctx->user_id, "text/plain");
  5131. });
  5132. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5133. auto se = detail::scope_exit([&] {
  5134. svr.stop();
  5135. thread.join();
  5136. ASSERT_FALSE(svr.is_running());
  5137. });
  5138. svr.wait_until_ready();
  5139. Client cli(HOST, PORT);
  5140. auto res = cli.Get("/me");
  5141. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5142. EXPECT_EQ(StatusCode::OK_200, res->status);
  5143. EXPECT_EQ("Hello alice", res->body);
  5144. }
  5145. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  5146. struct RoleCtx {
  5147. std::string role;
  5148. };
  5149. Server svr;
  5150. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  5151. res.user_data.set("role", RoleCtx{"admin"});
  5152. return Server::HandlerResponse::Unhandled;
  5153. });
  5154. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  5155. auto *ctx = res.user_data.get<RoleCtx>("role");
  5156. ASSERT_NE(nullptr, ctx);
  5157. res.set_content(ctx->role, "text/plain");
  5158. });
  5159. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5160. auto se = detail::scope_exit([&] {
  5161. svr.stop();
  5162. thread.join();
  5163. ASSERT_FALSE(svr.is_running());
  5164. });
  5165. svr.wait_until_ready();
  5166. Client cli(HOST, PORT);
  5167. auto res = cli.Get("/role");
  5168. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5169. EXPECT_EQ(StatusCode::OK_200, res->status);
  5170. EXPECT_EQ("admin", res->body);
  5171. }
  5172. TEST(InvalidFormatTest, StatusCode) {
  5173. Server svr;
  5174. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  5175. res.set_content("Hello World!\n", "text/plain");
  5176. res.status = 9999; // Status should be a three-digit code...
  5177. });
  5178. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5179. auto se = detail::scope_exit([&] {
  5180. svr.stop();
  5181. thread.join();
  5182. ASSERT_FALSE(svr.is_running());
  5183. });
  5184. svr.wait_until_ready();
  5185. {
  5186. Client cli(HOST, PORT);
  5187. auto res = cli.Get("/hi");
  5188. ASSERT_FALSE(res);
  5189. }
  5190. }
  5191. TEST(URLFragmentTest, WithFragment) {
  5192. Server svr;
  5193. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  5194. EXPECT_TRUE(req.target == "/hi");
  5195. });
  5196. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5197. auto se = detail::scope_exit([&] {
  5198. svr.stop();
  5199. thread.join();
  5200. ASSERT_FALSE(svr.is_running());
  5201. });
  5202. svr.wait_until_ready();
  5203. {
  5204. Client cli(HOST, PORT);
  5205. auto res = cli.Get("/hi#key1=val1=key2=val2");
  5206. EXPECT_TRUE(res);
  5207. EXPECT_EQ(StatusCode::OK_200, res->status);
  5208. res = cli.Get("/hi%23key1=val1=key2=val2");
  5209. EXPECT_TRUE(res);
  5210. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5211. }
  5212. }
  5213. TEST(URLFragmentTest, ParamsGoBeforeTheFragment) {
  5214. EXPECT_EQ("/a?b=1#f", append_query_params("/a#f", {{"b", "1"}}));
  5215. EXPECT_EQ("/a?q=0&b=1#f", append_query_params("/a?q=0#f", {{"b", "1"}}));
  5216. Server svr;
  5217. std::vector<std::string> targets;
  5218. svr.Get("/hi", [&](const Request &req, Response & /*res*/) {
  5219. targets.push_back(req.target);
  5220. });
  5221. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5222. auto se = detail::scope_exit([&] {
  5223. svr.stop();
  5224. thread.join();
  5225. ASSERT_FALSE(svr.is_running());
  5226. });
  5227. svr.wait_until_ready();
  5228. Client cli(HOST, PORT);
  5229. EXPECT_TRUE(cli.Get("/hi#f", Params{{"a", "1"}}, Headers{}));
  5230. EXPECT_TRUE(cli.Get("/hi?q=0#f", Params{{"a", "1"}}, Headers{}));
  5231. EXPECT_TRUE(cli.open_stream("GET", "/hi#f", {{"a", "1"}}).is_valid());
  5232. // A '?' after the '#' belongs to the fragment, not to the query.
  5233. Request req;
  5234. req.method = "GET";
  5235. req.path = "/hi#f?x=1";
  5236. req.params.emplace("a", "1");
  5237. Response res;
  5238. auto error = Error::Success;
  5239. EXPECT_TRUE(cli.send(req, res, error));
  5240. EXPECT_EQ((std::vector<std::string>{"/hi?a=1", "/hi?q=0&a=1", "/hi?a=1",
  5241. "/hi?a=1"}),
  5242. targets);
  5243. }
  5244. TEST(HeaderWriter, SetHeaderWriter) {
  5245. Server svr;
  5246. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  5247. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  5248. return detail::write_headers(strm, hdrs);
  5249. });
  5250. svr.Get("/hi", [](const Request &req, Response &res) {
  5251. auto it = req.headers.find("CustomClientHeader");
  5252. EXPECT_TRUE(it != req.headers.end());
  5253. EXPECT_EQ(it->second, "CustomClientValue");
  5254. res.set_content("Hello World!\n", "text/plain");
  5255. });
  5256. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  5257. auto se = detail::scope_exit([&] {
  5258. svr.stop();
  5259. thread.join();
  5260. ASSERT_FALSE(svr.is_running());
  5261. });
  5262. svr.wait_until_ready();
  5263. {
  5264. Client cli(HOST, PORT);
  5265. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  5266. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  5267. return detail::write_headers(strm, hdrs);
  5268. });
  5269. auto res = cli.Get("/hi");
  5270. EXPECT_TRUE(res);
  5271. EXPECT_EQ(StatusCode::OK_200, res->status);
  5272. auto it = res->headers.find("CustomServerHeader");
  5273. EXPECT_TRUE(it != res->headers.end());
  5274. EXPECT_EQ(it->second, "CustomServerValue");
  5275. }
  5276. }
  5277. class ServerTest : public ::testing::Test {
  5278. protected:
  5279. ServerTest()
  5280. : cli_(HOST, PORT)
  5281. #ifdef CPPHTTPLIB_SSL_ENABLED
  5282. ,
  5283. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  5284. #endif
  5285. {
  5286. #ifdef CPPHTTPLIB_SSL_ENABLED
  5287. cli_.enable_server_certificate_verification(false);
  5288. #endif
  5289. // Allow LARGE_DATA (100MB) responses
  5290. cli_.set_payload_max_length(200 * 1024 * 1024);
  5291. }
  5292. virtual void SetUp() {
  5293. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  5294. svr_.set_payload_max_length(200 * 1024 * 1024);
  5295. svr_.set_mount_point("/", "./www");
  5296. svr_.set_mount_point("/mount", "./www2");
  5297. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  5298. svr_.Get("/hi",
  5299. [&](const Request & /*req*/, Response &res) {
  5300. res.set_content("Hello World!", "text/plain");
  5301. })
  5302. .Get("/file_content",
  5303. [&](const Request & /*req*/, Response &res) {
  5304. res.set_file_content("./www/dir/test.html");
  5305. })
  5306. .Get("/file_content_with_content_type",
  5307. [&](const Request & /*req*/, Response &res) {
  5308. res.set_file_content("./www/file", "text/plain");
  5309. })
  5310. .Get("/invalid_file_content",
  5311. [&](const Request & /*req*/, Response &res) {
  5312. res.set_file_content("./www/dir/invalid_file_path");
  5313. })
  5314. .Get("/http_response_splitting",
  5315. [&](const Request & /*req*/, Response &res) {
  5316. res.set_header("a", "1\r\nSet-Cookie: a=1");
  5317. EXPECT_EQ(0U, res.headers.size());
  5318. EXPECT_FALSE(res.has_header("a"));
  5319. res.set_header("a", "1\nSet-Cookie: a=1");
  5320. EXPECT_EQ(0U, res.headers.size());
  5321. EXPECT_FALSE(res.has_header("a"));
  5322. res.set_header("a", "1\rSet-Cookie: a=1");
  5323. EXPECT_EQ(0U, res.headers.size());
  5324. EXPECT_FALSE(res.has_header("a"));
  5325. res.set_header("a\r\nb", "0");
  5326. EXPECT_EQ(0U, res.headers.size());
  5327. EXPECT_FALSE(res.has_header("a"));
  5328. res.set_header("a\rb", "0");
  5329. EXPECT_EQ(0U, res.headers.size());
  5330. EXPECT_FALSE(res.has_header("a"));
  5331. res.set_header("a\nb", "0");
  5332. EXPECT_EQ(0U, res.headers.size());
  5333. EXPECT_FALSE(res.has_header("a"));
  5334. res.set_redirect("1\r\nSet-Cookie: a=1");
  5335. EXPECT_EQ(0U, res.headers.size());
  5336. EXPECT_FALSE(res.has_header("Location"));
  5337. })
  5338. .Get("/slow",
  5339. [&](const Request & /*req*/, Response &res) {
  5340. std::this_thread::sleep_for(std::chrono::seconds(4));
  5341. res.set_content("slow", "text/plain");
  5342. })
  5343. #if 0
  5344. .Post("/slowpost",
  5345. [&](const Request & /*req*/, Response &res) {
  5346. std::this_thread::sleep_for(std::chrono::seconds(2));
  5347. res.set_content("slow", "text/plain");
  5348. })
  5349. #endif
  5350. .Get("/remote_addr",
  5351. [&](const Request &req, Response &res) {
  5352. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  5353. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  5354. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5355. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  5356. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  5357. #endif
  5358. res.set_content(req.remote_addr, "text/plain");
  5359. })
  5360. .Get("/local_addr",
  5361. [&](const Request &req, Response &res) {
  5362. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  5363. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  5364. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  5365. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  5366. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  5367. #endif
  5368. auto local_addr = req.local_addr;
  5369. auto local_port = std::to_string(req.local_port);
  5370. res.set_content(local_addr.append(":").append(local_port),
  5371. "text/plain");
  5372. })
  5373. .Get("/endwith%",
  5374. [&](const Request & /*req*/, Response &res) {
  5375. res.set_content("Hello World!", "text/plain");
  5376. })
  5377. .Get("/a\\+\\+b",
  5378. [&](const Request &req, Response &res) {
  5379. ASSERT_TRUE(req.has_param("a +b"));
  5380. auto val = req.get_param_value("a +b");
  5381. res.set_content(val, "text/plain");
  5382. })
  5383. .Get("/", [&](const Request & /*req*/,
  5384. Response &res) { res.set_redirect("/hi"); })
  5385. .Post("/1",
  5386. [](const Request & /*req*/, Response &res) {
  5387. res.set_redirect("/2", StatusCode::SeeOther_303);
  5388. })
  5389. .Get("/2",
  5390. [](const Request & /*req*/, Response &res) {
  5391. res.set_content("redirected.", "text/plain");
  5392. res.status = StatusCode::OK_200;
  5393. })
  5394. .Post("/person",
  5395. [&](const Request &req, Response &res) {
  5396. if (req.has_param("name") && req.has_param("note")) {
  5397. persons_[req.get_param_value("name")] =
  5398. req.get_param_value("note");
  5399. } else {
  5400. res.status = StatusCode::BadRequest_400;
  5401. }
  5402. })
  5403. .Put("/person",
  5404. [&](const Request &req, Response &res) {
  5405. if (req.has_param("name") && req.has_param("note")) {
  5406. persons_[req.get_param_value("name")] =
  5407. req.get_param_value("note");
  5408. } else {
  5409. res.status = StatusCode::BadRequest_400;
  5410. }
  5411. })
  5412. .Get("/person/(.*)",
  5413. [&](const Request &req, Response &res) {
  5414. string name = req.matches[1];
  5415. if (persons_.find(name) != persons_.end()) {
  5416. auto note = persons_[name];
  5417. res.set_content(note, "text/plain");
  5418. } else {
  5419. res.status = StatusCode::NotFound_404;
  5420. }
  5421. })
  5422. .Delete("/person",
  5423. [&](const Request &req, Response &res) {
  5424. if (req.has_param("name")) {
  5425. string name = req.get_param_value("name");
  5426. if (persons_.find(name) != persons_.end()) {
  5427. persons_.erase(name);
  5428. res.set_content("DELETED", "text/plain");
  5429. } else {
  5430. res.status = StatusCode::NotFound_404;
  5431. }
  5432. } else {
  5433. res.status = StatusCode::BadRequest_400;
  5434. }
  5435. })
  5436. .Post("/x-www-form-urlencoded-json",
  5437. [&](const Request &req, Response &res) {
  5438. auto json = req.get_param_value("json");
  5439. ASSERT_EQ(JSON_DATA, json);
  5440. res.set_content(json, "appliation/json");
  5441. res.status = StatusCode::OK_200;
  5442. })
  5443. .Get("/streamed-chunked",
  5444. [&](const Request & /*req*/, Response &res) {
  5445. res.set_chunked_content_provider(
  5446. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  5447. sink.os << "123";
  5448. sink.os << "456";
  5449. sink.os << "789";
  5450. sink.done();
  5451. return true;
  5452. });
  5453. })
  5454. .Get("/streamed-chunked-with-prohibited-trailer",
  5455. [&](const Request & /*req*/, Response &res) {
  5456. auto i = new int(0);
  5457. // Declare both a prohibited trailer (Content-Length) and an
  5458. // allowed one
  5459. res.set_header("Trailer", "Content-Length, X-Allowed");
  5460. res.set_chunked_content_provider(
  5461. "text/plain",
  5462. [i](size_t /*offset*/, DataSink &sink) {
  5463. switch (*i) {
  5464. case 0: sink.os << "123"; break;
  5465. case 1: sink.os << "456"; break;
  5466. case 2: sink.os << "789"; break;
  5467. case 3: {
  5468. sink.done_with_trailer(
  5469. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  5470. } break;
  5471. }
  5472. (*i)++;
  5473. return true;
  5474. },
  5475. [i](bool success) {
  5476. EXPECT_TRUE(success);
  5477. delete i;
  5478. });
  5479. })
  5480. .Get("/streamed-chunked2",
  5481. [&](const Request & /*req*/, Response &res) {
  5482. auto i = new int(0);
  5483. res.set_chunked_content_provider(
  5484. "text/plain",
  5485. [i](size_t /*offset*/, DataSink &sink) {
  5486. switch (*i) {
  5487. case 0: sink.os << "123"; break;
  5488. case 1: sink.os << "456"; break;
  5489. case 2: sink.os << "789"; break;
  5490. case 3: sink.done(); break;
  5491. }
  5492. (*i)++;
  5493. return true;
  5494. },
  5495. [i](bool success) {
  5496. EXPECT_TRUE(success);
  5497. delete i;
  5498. });
  5499. })
  5500. .Get("/streamed-chunked-with-trailer",
  5501. [&](const Request & /*req*/, Response &res) {
  5502. auto i = new int(0);
  5503. res.set_header("Trailer", "Dummy1, Dummy2");
  5504. res.set_chunked_content_provider(
  5505. "text/plain",
  5506. [i](size_t /*offset*/, DataSink &sink) {
  5507. switch (*i) {
  5508. case 0: sink.os << "123"; break;
  5509. case 1: sink.os << "456"; break;
  5510. case 2: sink.os << "789"; break;
  5511. case 3: {
  5512. sink.done_with_trailer(
  5513. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  5514. } break;
  5515. }
  5516. (*i)++;
  5517. return true;
  5518. },
  5519. [i](bool success) {
  5520. EXPECT_TRUE(success);
  5521. delete i;
  5522. });
  5523. })
  5524. .Get("/streamed",
  5525. [&](const Request & /*req*/, Response &res) {
  5526. res.set_content_provider(
  5527. 6, "text/plain",
  5528. [](size_t offset, size_t /*length*/, DataSink &sink) {
  5529. sink.os << (offset < 3 ? "a" : "b");
  5530. return true;
  5531. });
  5532. })
  5533. .Get("/streamed-without-length",
  5534. [&](const Request & /*req*/, Response &res) {
  5535. auto data = new std::string("abcdefg");
  5536. res.set_content_provider(
  5537. "text/plain",
  5538. [data](size_t offset, DataSink &sink) {
  5539. if (offset < data->size()) {
  5540. sink.os << data->substr(offset);
  5541. }
  5542. sink.done();
  5543. return true;
  5544. },
  5545. [data](bool success) {
  5546. EXPECT_TRUE(success);
  5547. delete data;
  5548. });
  5549. })
  5550. .Get("/streamed-with-range",
  5551. [&](const Request &req, Response &res) {
  5552. auto data = new std::string("abcdefg");
  5553. // An explicit status keeps the server from picking the 206 it
  5554. // would otherwise choose for a ranged request, so the response
  5555. // is not a partial representation.
  5556. auto status = req.get_param_value("status");
  5557. if (status == "200") {
  5558. res.status = StatusCode::OK_200;
  5559. } else if (status == "403") {
  5560. res.status = StatusCode::Forbidden_403;
  5561. }
  5562. res.set_content_provider(
  5563. data->size(), "text/plain",
  5564. [data](size_t offset, size_t length, DataSink &sink) {
  5565. size_t DATA_CHUNK_SIZE = 4;
  5566. const auto &d = *data;
  5567. auto out_len =
  5568. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  5569. auto ret =
  5570. sink.write(&d[static_cast<size_t>(offset)], out_len);
  5571. EXPECT_TRUE(ret);
  5572. return true;
  5573. },
  5574. [data, &req](bool success) {
  5575. EXPECT_EQ(success, !req.has_param("error"));
  5576. delete data;
  5577. });
  5578. })
  5579. .Get("/streamed-cancel",
  5580. [&](const Request & /*req*/, Response &res) {
  5581. res.set_content_provider(
  5582. size_t(-1), "text/plain",
  5583. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  5584. sink.os << "data_chunk";
  5585. return true;
  5586. });
  5587. })
  5588. .Get("/regex-with-delimiter",
  5589. [&](const Request &req, Response & /*res*/) {
  5590. ASSERT_TRUE(req.has_param("key"));
  5591. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  5592. })
  5593. .Get("/with-range",
  5594. [&](const Request & /*req*/, Response &res) {
  5595. res.set_content("abcdefg", "text/plain");
  5596. })
  5597. .Get("/test-start-time",
  5598. [&](const Request &req, Response & /*res*/) {
  5599. EXPECT_NE(req.start_time_,
  5600. std::chrono::steady_clock::time_point::min());
  5601. })
  5602. .Get("/with-range-customized-response",
  5603. [&](const Request & /*req*/, Response &res) {
  5604. res.status = StatusCode::BadRequest_400;
  5605. res.set_content(JSON_DATA, "application/json");
  5606. })
  5607. .Post("/chunked",
  5608. [&](const Request &req, Response & /*res*/) {
  5609. EXPECT_EQ(req.body, "dechunked post body");
  5610. })
  5611. .Post("/large-chunked",
  5612. [&](const Request &req, Response & /*res*/) {
  5613. std::string expected(6 * 30 * 1024u, 'a');
  5614. EXPECT_EQ(req.body, expected);
  5615. })
  5616. .Post("/multipart",
  5617. [&](const Request &req, Response & /*res*/) {
  5618. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  5619. req.form.get_field_count("text2") +
  5620. req.form.get_field_count("file3") +
  5621. req.form.get_field_count("file4"));
  5622. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  5623. req.form.get_file_count("file2"));
  5624. ASSERT_TRUE(!req.form.has_file("???"));
  5625. ASSERT_TRUE(!req.form.has_field("???"));
  5626. ASSERT_TRUE(req.body.empty());
  5627. {
  5628. const auto &text = req.form.get_field("text1");
  5629. EXPECT_EQ("text default", text);
  5630. }
  5631. {
  5632. const auto &text = req.form.get_field("text2");
  5633. EXPECT_EQ("aωb", text);
  5634. }
  5635. {
  5636. const auto &file = req.form.get_file("file1");
  5637. EXPECT_EQ("hello.txt", file.filename);
  5638. EXPECT_EQ("text/plain", file.content_type);
  5639. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5640. }
  5641. {
  5642. const auto &file = req.form.get_file("file2");
  5643. EXPECT_EQ("world.json", file.filename);
  5644. EXPECT_EQ("application/json", file.content_type);
  5645. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  5646. }
  5647. {
  5648. const auto &text = req.form.get_field("file3");
  5649. EXPECT_EQ(0u, text.size());
  5650. }
  5651. {
  5652. const auto &text = req.form.get_field("file4");
  5653. EXPECT_EQ(0u, text.size());
  5654. }
  5655. })
  5656. .Post("/multipart/multi_file_values",
  5657. [&](const Request &req, Response & /*res*/) {
  5658. EXPECT_EQ(3u, req.form.get_field_count("text") +
  5659. req.form.get_field_count("multi_text1"));
  5660. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  5661. ASSERT_TRUE(!req.form.has_file("???"));
  5662. ASSERT_TRUE(!req.form.has_field("???"));
  5663. ASSERT_TRUE(req.body.empty());
  5664. {
  5665. const auto &text = req.form.get_field("text");
  5666. EXPECT_EQ("default text", text);
  5667. }
  5668. {
  5669. const auto &text1_values = req.form.get_fields("multi_text1");
  5670. EXPECT_EQ(2u, text1_values.size());
  5671. EXPECT_EQ("aaaaa", text1_values[0]);
  5672. EXPECT_EQ("bbbbb", text1_values[1]);
  5673. }
  5674. {
  5675. const auto &file1_values = req.form.get_files("multi_file1");
  5676. EXPECT_EQ(2u, file1_values.size());
  5677. auto file1 = file1_values[0];
  5678. EXPECT_EQ(file1.filename, "hello.txt");
  5679. EXPECT_EQ(file1.content_type, "text/plain");
  5680. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  5681. auto file2 = file1_values[1];
  5682. EXPECT_EQ(file2.filename, "world.json");
  5683. EXPECT_EQ(file2.content_type, "application/json");
  5684. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  5685. }
  5686. })
  5687. .Post("/empty",
  5688. [&](const Request &req, Response &res) {
  5689. EXPECT_EQ(req.body, "");
  5690. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  5691. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5692. res.set_content("empty", "text/plain");
  5693. })
  5694. .Post("/empty-no-content-type",
  5695. [&](const Request &req, Response &res) {
  5696. EXPECT_EQ(req.body, "");
  5697. EXPECT_FALSE(req.has_header("Content-Type"));
  5698. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5699. res.set_content("empty-no-content-type", "text/plain");
  5700. })
  5701. .Post("/path-only",
  5702. [&](const Request &req, Response &res) {
  5703. EXPECT_EQ(req.body, "");
  5704. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5705. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5706. res.set_content("path-only", "text/plain");
  5707. })
  5708. .Post("/path-headers-only",
  5709. [&](const Request &req, Response &res) {
  5710. EXPECT_EQ(req.body, "");
  5711. EXPECT_EQ("", req.get_header_value("Content-Type"));
  5712. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5713. EXPECT_EQ("world", req.get_header_value("hello"));
  5714. EXPECT_EQ("world2", req.get_header_value("hello2"));
  5715. res.set_content("path-headers-only", "text/plain");
  5716. })
  5717. .Post("/post-large",
  5718. [&](const Request &req, Response &res) {
  5719. EXPECT_EQ(req.body, LARGE_DATA);
  5720. res.set_content(req.body, "text/plain");
  5721. })
  5722. .Post("/post-loopback",
  5723. [&](const Request &, Response &res,
  5724. ContentReader const &content_reader) {
  5725. std::string body;
  5726. content_reader([&](const char *data, size_t data_length) {
  5727. body.append(data, data_length);
  5728. return true;
  5729. });
  5730. res.set_content(body, "text/plain");
  5731. })
  5732. .Put("/put-loopback",
  5733. [&](const Request &, Response &res,
  5734. ContentReader const &content_reader) {
  5735. std::string body;
  5736. content_reader([&](const char *data, size_t data_length) {
  5737. body.append(data, data_length);
  5738. return true;
  5739. });
  5740. res.set_content(body, "text/plain");
  5741. })
  5742. .Patch("/patch-loopback",
  5743. [&](const Request &, Response &res,
  5744. ContentReader const &content_reader) {
  5745. std::string body;
  5746. content_reader([&](const char *data, size_t data_length) {
  5747. body.append(data, data_length);
  5748. return true;
  5749. });
  5750. res.set_content(body, "text/plain");
  5751. })
  5752. .Put("/empty-no-content-type",
  5753. [&](const Request &req, Response &res) {
  5754. EXPECT_EQ(req.body, "");
  5755. EXPECT_FALSE(req.has_header("Content-Type"));
  5756. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  5757. res.set_content("empty-no-content-type", "text/plain");
  5758. })
  5759. .Put("/put",
  5760. [&](const Request &req, Response &res) {
  5761. EXPECT_EQ(req.body, "PUT");
  5762. res.set_content(req.body, "text/plain");
  5763. })
  5764. .Put("/put-large",
  5765. [&](const Request &req, Response &res) {
  5766. EXPECT_EQ(req.body, LARGE_DATA);
  5767. res.set_content(req.body, "text/plain");
  5768. })
  5769. .Patch("/patch",
  5770. [&](const Request &req, Response &res) {
  5771. EXPECT_EQ(req.body, "PATCH");
  5772. res.set_content(req.body, "text/plain");
  5773. })
  5774. .Delete("/delete",
  5775. [&](const Request & /*req*/, Response &res) {
  5776. res.set_content("DELETE", "text/plain");
  5777. })
  5778. .Delete("/delete-body",
  5779. [&](const Request &req, Response &res) {
  5780. EXPECT_EQ(req.body, "content");
  5781. res.set_content(req.body, "text/plain");
  5782. })
  5783. .Options(R"(\*)",
  5784. [&](const Request & /*req*/, Response &res) {
  5785. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  5786. })
  5787. .CustomRoute("PROPFIND", "/dav/:id",
  5788. [&](const Request &req, Response &res) {
  5789. res.set_header("x-body-size",
  5790. std::to_string(req.body.size()));
  5791. res.set_header("x-matched-route", req.matched_route);
  5792. res.set_header("x-dav-id", req.path_params.at("id"));
  5793. res.status = StatusCode::MultiStatus_207;
  5794. res.set_content(req.body, "application/xml");
  5795. })
  5796. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  5797. [&](const Request &req, Response &res) {
  5798. res.set_header("x-dav-match", req.matches[1]);
  5799. res.status = StatusCode::MultiStatus_207;
  5800. })
  5801. .CustomRoute("MKCOL", "/dav-mkcol",
  5802. [&](const Request &req, Response &res) {
  5803. EXPECT_TRUE(req.body.empty());
  5804. res.status = StatusCode::Created_201;
  5805. })
  5806. .CustomRoute(
  5807. "REPORT", "/dav-report",
  5808. [&](const Request & /*req*/, Response &res,
  5809. const ContentReader &content_reader) {
  5810. std::string body;
  5811. content_reader([&](const char *data, size_t data_length) {
  5812. body.append(data, data_length);
  5813. return true;
  5814. });
  5815. res.set_header("x-body-size", std::to_string(body.size()));
  5816. res.status = StatusCode::MultiStatus_207;
  5817. res.set_content(body, "application/xml");
  5818. })
  5819. .Get("/request-target",
  5820. [&](const Request &req, Response & /*res*/) {
  5821. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  5822. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  5823. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  5824. })
  5825. .Get("/long-query-value",
  5826. [&](const Request &req, Response & /*res*/) {
  5827. EXPECT_EQ(LONG_QUERY_URL, req.target);
  5828. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  5829. })
  5830. .Get("/too-long-query-value",
  5831. [&](const Request &req, Response & /*res*/) {
  5832. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  5833. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  5834. })
  5835. .Get("/array-param",
  5836. [&](const Request &req, Response & /*res*/) {
  5837. EXPECT_EQ(3u, req.get_param_value_count("array"));
  5838. EXPECT_EQ("value1", req.get_param_value("array", 0));
  5839. EXPECT_EQ("value2", req.get_param_value("array", 1));
  5840. EXPECT_EQ("value3", req.get_param_value("array", 2));
  5841. })
  5842. .Get("/array-param-values",
  5843. [&](const Request &req, Response & /*res*/) {
  5844. auto values = req.get_param_values("array");
  5845. EXPECT_EQ(3u, values.size());
  5846. EXPECT_EQ("value1", values[0]);
  5847. EXPECT_EQ("value2", values[1]);
  5848. EXPECT_EQ("value3", values[2]);
  5849. auto empty = req.get_param_values("nonexistent");
  5850. EXPECT_TRUE(empty.empty());
  5851. })
  5852. .Post("/validate-no-multiple-headers",
  5853. [&](const Request &req, Response & /*res*/) {
  5854. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  5855. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  5856. })
  5857. .Post("/content_receiver",
  5858. [&](const Request &req, Response &res,
  5859. const ContentReader &content_reader) {
  5860. if (req.is_multipart_form_data()) {
  5861. std::vector<FormData> items;
  5862. content_reader(
  5863. [&](const FormData &file) {
  5864. items.push_back(file);
  5865. return true;
  5866. },
  5867. [&](const char *data, size_t data_length) {
  5868. items.back().content.append(data, data_length);
  5869. return true;
  5870. });
  5871. EXPECT_EQ(5u, items.size());
  5872. {
  5873. const auto &file = get_file_value(items, "text1");
  5874. EXPECT_TRUE(file.filename.empty());
  5875. EXPECT_EQ("text default", file.content);
  5876. }
  5877. {
  5878. const auto &file = get_file_value(items, "text2");
  5879. EXPECT_TRUE(file.filename.empty());
  5880. EXPECT_EQ("aωb", file.content);
  5881. }
  5882. {
  5883. const auto &file = get_file_value(items, "file1");
  5884. EXPECT_EQ("hello.txt", file.filename);
  5885. EXPECT_EQ("text/plain", file.content_type);
  5886. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  5887. }
  5888. {
  5889. const auto &file = get_file_value(items, "file2");
  5890. EXPECT_EQ("world.json", file.filename);
  5891. EXPECT_EQ("application/json", file.content_type);
  5892. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  5893. }
  5894. {
  5895. const auto &file = get_file_value(items, "file3");
  5896. EXPECT_TRUE(file.filename.empty());
  5897. EXPECT_EQ("application/octet-stream", file.content_type);
  5898. EXPECT_EQ(0u, file.content.size());
  5899. }
  5900. } else {
  5901. std::string body;
  5902. content_reader([&](const char *data, size_t data_length) {
  5903. EXPECT_EQ(7U, data_length);
  5904. body.append(data, data_length);
  5905. return true;
  5906. });
  5907. EXPECT_EQ(body, "content");
  5908. res.set_content(body, "text/plain");
  5909. }
  5910. })
  5911. .Put("/content_receiver",
  5912. [&](const Request & /*req*/, Response &res,
  5913. const ContentReader &content_reader) {
  5914. std::string body;
  5915. content_reader([&](const char *data, size_t data_length) {
  5916. body.append(data, data_length);
  5917. return true;
  5918. });
  5919. EXPECT_EQ(body, "content");
  5920. res.set_content(body, "text/plain");
  5921. })
  5922. .Patch("/content_receiver",
  5923. [&](const Request & /*req*/, Response &res,
  5924. const ContentReader &content_reader) {
  5925. std::string body;
  5926. content_reader([&](const char *data, size_t data_length) {
  5927. body.append(data, data_length);
  5928. return true;
  5929. });
  5930. EXPECT_EQ(body, "content");
  5931. res.set_content(body, "text/plain");
  5932. })
  5933. .Post("/query-string-and-body",
  5934. [&](const Request &req, Response & /*res*/) {
  5935. ASSERT_TRUE(req.has_param("key"));
  5936. EXPECT_EQ(req.get_param_value("key"), "value");
  5937. EXPECT_EQ(req.body, "content");
  5938. })
  5939. .Get("/last-request",
  5940. [&](const Request &req, Response & /*res*/) {
  5941. EXPECT_EQ("close", req.get_header_value("Connection"));
  5942. })
  5943. .Get(R"(/redirect/(\d+))",
  5944. [&](const Request &req, Response &res) {
  5945. auto num = std::stoi(req.matches[1]) + 1;
  5946. std::string url = "/redirect/" + std::to_string(num);
  5947. res.set_redirect(url);
  5948. })
  5949. .Post("/binary",
  5950. [&](const Request &req, Response &res) {
  5951. EXPECT_EQ(4U, req.body.size());
  5952. EXPECT_EQ("application/octet-stream",
  5953. req.get_header_value("Content-Type"));
  5954. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5955. res.set_content(req.body, "application/octet-stream");
  5956. })
  5957. .Put("/binary",
  5958. [&](const Request &req, Response &res) {
  5959. EXPECT_EQ(4U, req.body.size());
  5960. EXPECT_EQ("application/octet-stream",
  5961. req.get_header_value("Content-Type"));
  5962. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5963. res.set_content(req.body, "application/octet-stream");
  5964. })
  5965. .Patch("/binary",
  5966. [&](const Request &req, Response &res) {
  5967. EXPECT_EQ(4U, req.body.size());
  5968. EXPECT_EQ("application/octet-stream",
  5969. req.get_header_value("Content-Type"));
  5970. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5971. res.set_content(req.body, "application/octet-stream");
  5972. })
  5973. .Delete("/binary",
  5974. [&](const Request &req, Response &res) {
  5975. EXPECT_EQ(4U, req.body.size());
  5976. EXPECT_EQ("application/octet-stream",
  5977. req.get_header_value("Content-Type"));
  5978. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5979. res.set_content(req.body, "application/octet-stream");
  5980. })
  5981. .Get("/issue1772",
  5982. [&](const Request & /*req*/, Response &res) {
  5983. res.status = 401;
  5984. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5985. })
  5986. .Delete("/issue609",
  5987. [](const httplib::Request &, httplib::Response &res,
  5988. const httplib::ContentReader &) {
  5989. res.set_content("ok", "text/plain");
  5990. })
  5991. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5992. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5993. .Get("/compress",
  5994. [&](const Request & /*req*/, Response &res) {
  5995. res.set_content(
  5996. "12345678901234567890123456789012345678901234567890123456789"
  5997. "01234567890123456789012345678901234567890",
  5998. "text/plain");
  5999. })
  6000. .Get("/compress-with-charset",
  6001. [&](const Request & /*req*/, Response &res) {
  6002. res.set_content(
  6003. "12345678901234567890123456789012345678901234567890123456789"
  6004. "01234567890123456789012345678901234567890",
  6005. "application/json; charset=utf-8");
  6006. })
  6007. .Get("/nocompress",
  6008. [&](const Request & /*req*/, Response &res) {
  6009. res.set_content(
  6010. "12345678901234567890123456789012345678901234567890123456789"
  6011. "01234567890123456789012345678901234567890",
  6012. "application/octet-stream");
  6013. })
  6014. .Post("/compress-multipart",
  6015. [&](const Request &req, Response & /*res*/) {
  6016. EXPECT_EQ(2u, req.form.fields.size());
  6017. ASSERT_TRUE(!req.form.has_field("???"));
  6018. {
  6019. const auto &text = req.form.get_field("key1");
  6020. EXPECT_EQ("test", text);
  6021. }
  6022. {
  6023. const auto &text = req.form.get_field("key2");
  6024. EXPECT_EQ("--abcdefg123", text);
  6025. }
  6026. })
  6027. #endif
  6028. ;
  6029. persons_["john"] = "programmer";
  6030. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  6031. svr_.wait_until_ready();
  6032. }
  6033. virtual void TearDown() {
  6034. svr_.stop();
  6035. if (!request_threads_.empty()) {
  6036. std::this_thread::sleep_for(std::chrono::seconds(1));
  6037. for (auto &t : request_threads_) {
  6038. t.join();
  6039. }
  6040. }
  6041. t_.join();
  6042. }
  6043. map<string, string> persons_;
  6044. #ifdef CPPHTTPLIB_SSL_ENABLED
  6045. SSLClient cli_;
  6046. SSLServer svr_;
  6047. #else
  6048. Client cli_;
  6049. Server svr_;
  6050. #endif
  6051. thread t_;
  6052. std::vector<thread> request_threads_;
  6053. };
  6054. TEST_F(ServerTest, GetMethod200) {
  6055. auto res = cli_.Get("/hi");
  6056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6057. EXPECT_EQ("HTTP/1.1", res->version);
  6058. EXPECT_EQ(StatusCode::OK_200, res->status);
  6059. EXPECT_EQ("OK", res->reason);
  6060. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6061. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6062. EXPECT_EQ("Hello World!", res->body);
  6063. }
  6064. TEST_F(ServerTest, GetEmptyFile) {
  6065. auto res = cli_.Get("/empty_file");
  6066. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6067. EXPECT_EQ(StatusCode::OK_200, res->status);
  6068. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  6069. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  6070. EXPECT_EQ("", res->body);
  6071. }
  6072. TEST_F(ServerTest, GetFileContent) {
  6073. auto res = cli_.Get("/file_content");
  6074. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6075. EXPECT_EQ(StatusCode::OK_200, res->status);
  6076. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6077. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  6078. EXPECT_EQ("test.html", res->body);
  6079. }
  6080. TEST_F(ServerTest, GetFileContentWithRange) {
  6081. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  6082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6083. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6084. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6085. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  6086. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  6087. EXPECT_EQ("est", res->body);
  6088. }
  6089. TEST_F(ServerTest, GetFileContentWithContentType) {
  6090. auto res = cli_.Get("/file_content_with_content_type");
  6091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6092. EXPECT_EQ(StatusCode::OK_200, res->status);
  6093. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6094. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  6095. EXPECT_EQ("file\n", res->body);
  6096. }
  6097. TEST_F(ServerTest, GetInvalidFileContent) {
  6098. auto res = cli_.Get("/invalid_file_content");
  6099. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6100. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6101. }
  6102. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  6103. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  6104. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6105. EXPECT_EQ("HTTP/1.1", res->version);
  6106. EXPECT_EQ(StatusCode::OK_200, res->status);
  6107. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6108. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  6109. EXPECT_EQ("Hello World!", res->body);
  6110. }
  6111. TEST_F(ServerTest, GetMethod302) {
  6112. auto res = cli_.Get("/");
  6113. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6114. EXPECT_EQ(StatusCode::Found_302, res->status);
  6115. EXPECT_EQ("/hi", res->get_header_value("Location"));
  6116. }
  6117. TEST_F(ServerTest, GetMethod302Redirect) {
  6118. cli_.set_follow_location(true);
  6119. auto res = cli_.Get("/");
  6120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6121. EXPECT_EQ(StatusCode::OK_200, res->status);
  6122. EXPECT_EQ("Hello World!", res->body);
  6123. EXPECT_EQ("/hi", res->location);
  6124. }
  6125. TEST_F(ServerTest, GetMethod404) {
  6126. auto res = cli_.Get("/invalid");
  6127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6128. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6129. }
  6130. TEST_F(ServerTest, HeadMethod200) {
  6131. auto res = cli_.Head("/hi");
  6132. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6133. EXPECT_EQ(StatusCode::OK_200, res->status);
  6134. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6135. EXPECT_TRUE(res->body.empty());
  6136. }
  6137. TEST_F(ServerTest, HeadMethod200Static) {
  6138. auto res = cli_.Head("/mount/dir/index.html");
  6139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6140. EXPECT_EQ(StatusCode::OK_200, res->status);
  6141. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6142. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  6143. EXPECT_TRUE(res->body.empty());
  6144. }
  6145. TEST_F(ServerTest, HeadMethod404) {
  6146. auto res = cli_.Head("/invalid");
  6147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6148. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6149. EXPECT_TRUE(res->body.empty());
  6150. }
  6151. TEST_F(ServerTest, GetMethodPersonJohn) {
  6152. auto res = cli_.Get("/person/john");
  6153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6154. EXPECT_EQ(StatusCode::OK_200, res->status);
  6155. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6156. EXPECT_EQ("programmer", res->body);
  6157. }
  6158. TEST_F(ServerTest, PostMethod1) {
  6159. auto res = cli_.Get("/person/john1");
  6160. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6161. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6162. res = cli_.Post("/person", "name=john1&note=coder",
  6163. "application/x-www-form-urlencoded");
  6164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6165. ASSERT_EQ(StatusCode::OK_200, res->status);
  6166. res = cli_.Get("/person/john1");
  6167. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6168. ASSERT_EQ(StatusCode::OK_200, res->status);
  6169. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6170. ASSERT_EQ("coder", res->body);
  6171. }
  6172. TEST_F(ServerTest, PostMethod2) {
  6173. auto res = cli_.Get("/person/john2");
  6174. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6175. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6176. Params params;
  6177. params.emplace("name", "john2");
  6178. params.emplace("note", "coder");
  6179. res = cli_.Post("/person", params);
  6180. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6181. ASSERT_EQ(StatusCode::OK_200, res->status);
  6182. res = cli_.Get("/person/john2");
  6183. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6184. ASSERT_EQ(StatusCode::OK_200, res->status);
  6185. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6186. ASSERT_EQ("coder", res->body);
  6187. }
  6188. TEST_F(ServerTest, PutMethod3) {
  6189. auto res = cli_.Get("/person/john3");
  6190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6191. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6192. Params params;
  6193. params.emplace("name", "john3");
  6194. params.emplace("note", "coder");
  6195. res = cli_.Put("/person", params);
  6196. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6197. ASSERT_EQ(StatusCode::OK_200, res->status);
  6198. res = cli_.Get("/person/john3");
  6199. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6200. ASSERT_EQ(StatusCode::OK_200, res->status);
  6201. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6202. ASSERT_EQ("coder", res->body);
  6203. }
  6204. TEST_F(ServerTest, DeleteMethod1) {
  6205. auto res = cli_.Get("/person/john4");
  6206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6207. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6208. Params params;
  6209. params.emplace("name", "john4");
  6210. params.emplace("note", "coder");
  6211. res = cli_.Post("/person", params);
  6212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6213. ASSERT_EQ(StatusCode::OK_200, res->status);
  6214. res = cli_.Get("/person/john4");
  6215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6216. ASSERT_EQ(StatusCode::OK_200, res->status);
  6217. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6218. ASSERT_EQ("coder", res->body);
  6219. Params delete_params;
  6220. delete_params.emplace("name", "john4");
  6221. res = cli_.Delete("/person", delete_params);
  6222. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6223. ASSERT_EQ(StatusCode::OK_200, res->status);
  6224. ASSERT_EQ("DELETED", res->body);
  6225. res = cli_.Get("/person/john4");
  6226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6227. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6228. }
  6229. TEST_F(ServerTest, DeleteMethod2) {
  6230. auto res = cli_.Get("/person/john5");
  6231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6232. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6233. Params params;
  6234. params.emplace("name", "john5");
  6235. params.emplace("note", "developer");
  6236. res = cli_.Post("/person", params);
  6237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6238. ASSERT_EQ(StatusCode::OK_200, res->status);
  6239. res = cli_.Get("/person/john5");
  6240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6241. ASSERT_EQ(StatusCode::OK_200, res->status);
  6242. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6243. ASSERT_EQ("developer", res->body);
  6244. Params delete_params;
  6245. delete_params.emplace("name", "john5");
  6246. Headers headers;
  6247. headers.emplace("Custom-Header", "test-value");
  6248. res = cli_.Delete("/person", headers, delete_params);
  6249. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6250. ASSERT_EQ(StatusCode::OK_200, res->status);
  6251. ASSERT_EQ("DELETED", res->body);
  6252. res = cli_.Get("/person/john5");
  6253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6254. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6255. }
  6256. TEST_F(ServerTest, DeleteMethod3) {
  6257. auto res = cli_.Get("/person/john6");
  6258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6259. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6260. Params params;
  6261. params.emplace("name", "john6");
  6262. params.emplace("note", "tester");
  6263. res = cli_.Post("/person", params);
  6264. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6265. ASSERT_EQ(StatusCode::OK_200, res->status);
  6266. res = cli_.Get("/person/john6");
  6267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6268. ASSERT_EQ(StatusCode::OK_200, res->status);
  6269. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  6270. ASSERT_EQ("tester", res->body);
  6271. Params delete_params;
  6272. delete_params.emplace("name", "john6");
  6273. Headers headers;
  6274. headers.emplace("Custom-Header", "test-value");
  6275. res = cli_.Delete("/person", headers, delete_params, nullptr);
  6276. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6277. ASSERT_EQ(StatusCode::OK_200, res->status);
  6278. ASSERT_EQ("DELETED", res->body);
  6279. res = cli_.Get("/person/john6");
  6280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6281. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  6282. }
  6283. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  6284. Params params;
  6285. params.emplace("json", JSON_DATA);
  6286. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  6287. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6288. ASSERT_EQ(StatusCode::OK_200, res->status);
  6289. ASSERT_EQ(JSON_DATA, res->body);
  6290. }
  6291. TEST_F(ServerTest, PostEmptyContent) {
  6292. auto res = cli_.Post("/empty", "", "text/plain");
  6293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6294. ASSERT_EQ(StatusCode::OK_200, res->status);
  6295. ASSERT_EQ("empty", res->body);
  6296. }
  6297. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  6298. auto res = cli_.Post("/empty-no-content-type");
  6299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6300. ASSERT_EQ(StatusCode::OK_200, res->status);
  6301. ASSERT_EQ("empty-no-content-type", res->body);
  6302. }
  6303. TEST_F(ServerTest, PostPathOnly) {
  6304. auto res = cli_.Post("/path-only");
  6305. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6306. ASSERT_EQ(StatusCode::OK_200, res->status);
  6307. ASSERT_EQ("path-only", res->body);
  6308. }
  6309. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  6310. auto res = cli_.Post("/path-headers-only",
  6311. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  6312. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6313. ASSERT_EQ(StatusCode::OK_200, res->status);
  6314. ASSERT_EQ("path-headers-only", res->body);
  6315. }
  6316. TEST_F(ServerTest, PostLarge) {
  6317. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. ASSERT_EQ(StatusCode::OK_200, res->status);
  6320. EXPECT_EQ(LARGE_DATA, res->body);
  6321. }
  6322. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  6323. auto res = cli_.Put("/empty-no-content-type");
  6324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6325. ASSERT_EQ(StatusCode::OK_200, res->status);
  6326. ASSERT_EQ("empty-no-content-type", res->body);
  6327. }
  6328. TEST_F(ServerTest, GetMethodDir) {
  6329. auto res = cli_.Get("/dir/");
  6330. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6331. EXPECT_EQ(StatusCode::OK_200, res->status);
  6332. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6333. auto body = R"(<html>
  6334. <head>
  6335. </head>
  6336. <body>
  6337. <a href="/dir/test.html">Test</a>
  6338. <a href="/hi">hi</a>
  6339. </body>
  6340. </html>
  6341. )";
  6342. EXPECT_EQ(body, res->body);
  6343. }
  6344. TEST_F(ServerTest, GetMethodDirTest) {
  6345. auto res = cli_.Get("/dir/test.html");
  6346. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6347. EXPECT_EQ(StatusCode::OK_200, res->status);
  6348. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6349. EXPECT_EQ("test.html", res->body);
  6350. }
  6351. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  6352. auto res = cli_.Get("/dir/../dir/test.html");
  6353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6354. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6355. }
  6356. TEST_F(ServerTest, GetMethodInvalidPath) {
  6357. auto res = cli_.Get("/dir/../test.html");
  6358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6359. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6360. }
  6361. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  6362. auto res = cli_.Get("/../www/dir/test.html");
  6363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6365. }
  6366. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  6367. auto res = cli_.Get("/dir/../../www/dir/test.html");
  6368. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6369. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6370. }
  6371. TEST_F(ServerTest, GetMethodDirMountTest) {
  6372. auto res = cli_.Get("/mount/dir/test.html");
  6373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6374. EXPECT_EQ(StatusCode::OK_200, res->status);
  6375. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  6376. EXPECT_EQ("test.html", res->body);
  6377. }
  6378. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  6379. auto res = cli_.Get("/mount/dir/../dir/test.html");
  6380. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6381. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6382. }
  6383. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  6384. auto res = cli_.Get("/mount/dir/../test.html");
  6385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6386. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6387. }
  6388. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  6389. auto res = cli_.Get("/mount/dir/test.html%00.js");
  6390. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6391. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6392. }
  6393. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  6394. auto res = cli_.Get("/mount/../www2/dir/test.html");
  6395. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6396. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6397. }
  6398. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  6399. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6402. }
  6403. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  6404. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  6405. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6406. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6407. }
  6408. TEST_F(ServerTest, GetMethodDirMountWithoutTrailingSlash) {
  6409. auto res = cli_.Get("/mount/dir");
  6410. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6411. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  6412. EXPECT_EQ("./dir/", res->get_header_value("Location"));
  6413. }
  6414. TEST_F(ServerTest, GetMethodDirWithLeadingDoubleSlash) {
  6415. auto res = cli_.Get("//dir");
  6416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6417. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6418. EXPECT_FALSE(res->has_header("Location"));
  6419. }
  6420. TEST_F(ServerTest, PostMethod303) {
  6421. auto res = cli_.Post("/1", "body", "text/plain");
  6422. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6423. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  6424. EXPECT_EQ("/2", res->get_header_value("Location"));
  6425. }
  6426. TEST_F(ServerTest, PostMethod303Redirect) {
  6427. cli_.set_follow_location(true);
  6428. auto res = cli_.Post("/1", "body", "text/plain");
  6429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6430. EXPECT_EQ(StatusCode::OK_200, res->status);
  6431. EXPECT_EQ("redirected.", res->body);
  6432. EXPECT_EQ("/2", res->location);
  6433. }
  6434. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  6435. auto res = cli_.Get("/dir/test.abcde");
  6436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6437. EXPECT_EQ(StatusCode::OK_200, res->status);
  6438. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6439. EXPECT_EQ("abcde", res->body);
  6440. }
  6441. TEST_F(ServerTest, StaticFileRange) {
  6442. auto res =
  6443. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  6444. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6445. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6446. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6447. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6448. EXPECT_EQ(true, res->has_header("Content-Range"));
  6449. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6450. EXPECT_EQ(std::string("cd"), res->body);
  6451. }
  6452. TEST_F(ServerTest, StaticFileRanges) {
  6453. auto res = cli_.Get("/dir/test.abcde",
  6454. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  6455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6456. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6457. EXPECT_TRUE(
  6458. res->get_header_value("Content-Type")
  6459. .find(
  6460. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  6461. 0);
  6462. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  6463. }
  6464. TEST_F(ServerTest, StaticFileRangeHead) {
  6465. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  6466. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6467. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6468. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  6469. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6470. EXPECT_EQ(true, res->has_header("Content-Range"));
  6471. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  6472. }
  6473. TEST_F(ServerTest, StaticFileRangeBigFile) {
  6474. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  6475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6476. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6477. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6478. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  6479. EXPECT_EQ(true, res->has_header("Content-Range"));
  6480. EXPECT_EQ("bytes 1048571-1048575/1048576",
  6481. res->get_header_value("Content-Range"));
  6482. EXPECT_EQ("LAST\n", res->body);
  6483. }
  6484. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  6485. auto res =
  6486. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  6487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6488. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6489. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6490. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  6491. EXPECT_EQ(true, res->has_header("Content-Range"));
  6492. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  6493. }
  6494. TEST_F(ServerTest, StaticFileBigFile) {
  6495. auto res = cli_.Get("/dir/1MB.txt");
  6496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6497. EXPECT_EQ(StatusCode::OK_200, res->status);
  6498. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6499. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  6500. }
  6501. TEST_F(ServerTest, InvalidBaseDirMount) {
  6502. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  6503. }
  6504. TEST_F(ServerTest, Binary) {
  6505. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  6506. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  6507. "application/octet-stream");
  6508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6509. ASSERT_EQ(StatusCode::OK_200, res->status);
  6510. ASSERT_EQ(4U, res->body.size());
  6511. res = cli_.Put("/binary", binary.data(), binary.size(),
  6512. "application/octet-stream");
  6513. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6514. ASSERT_EQ(StatusCode::OK_200, res->status);
  6515. ASSERT_EQ(4U, res->body.size());
  6516. res = cli_.Patch("/binary", binary.data(), binary.size(),
  6517. "application/octet-stream");
  6518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6519. ASSERT_EQ(StatusCode::OK_200, res->status);
  6520. ASSERT_EQ(4U, res->body.size());
  6521. res = cli_.Delete("/binary", binary.data(), binary.size(),
  6522. "application/octet-stream");
  6523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6524. ASSERT_EQ(StatusCode::OK_200, res->status);
  6525. ASSERT_EQ(4U, res->body.size());
  6526. }
  6527. TEST_F(ServerTest, BinaryString) {
  6528. auto binary = std::string("\x00\x01\x02\x03", 4);
  6529. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  6530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6531. ASSERT_EQ(StatusCode::OK_200, res->status);
  6532. ASSERT_EQ(4U, res->body.size());
  6533. res = cli_.Put("/binary", binary, "application/octet-stream");
  6534. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6535. ASSERT_EQ(StatusCode::OK_200, res->status);
  6536. ASSERT_EQ(4U, res->body.size());
  6537. res = cli_.Patch("/binary", binary, "application/octet-stream");
  6538. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6539. ASSERT_EQ(StatusCode::OK_200, res->status);
  6540. ASSERT_EQ(4U, res->body.size());
  6541. res = cli_.Delete("/binary", binary, "application/octet-stream");
  6542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6543. ASSERT_EQ(StatusCode::OK_200, res->status);
  6544. ASSERT_EQ(4U, res->body.size());
  6545. }
  6546. TEST_F(ServerTest, EmptyRequest) {
  6547. auto res = cli_.Get("");
  6548. ASSERT_TRUE(!res);
  6549. EXPECT_EQ(Error::Connection, res.error());
  6550. }
  6551. TEST_F(ServerTest, LongRequest) {
  6552. std::string request;
  6553. for (size_t i = 0; i < 545; i++) {
  6554. request += "/TooLongRequest";
  6555. }
  6556. request += "OK";
  6557. auto res = cli_.Get(request.c_str());
  6558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6559. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6560. }
  6561. TEST_F(ServerTest, TooLongRequest) {
  6562. std::string request;
  6563. for (size_t i = 0; i < 546; i++) {
  6564. request += "/TooLongRequest";
  6565. }
  6566. request += "_NG";
  6567. auto start = std::chrono::high_resolution_clock::now();
  6568. cli_.set_keep_alive(true);
  6569. auto res = cli_.Get(request.c_str());
  6570. auto end = std::chrono::high_resolution_clock::now();
  6571. auto elapsed =
  6572. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6573. .count();
  6574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6575. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6576. EXPECT_LE(elapsed, 1000);
  6577. EXPECT_EQ("close", res->get_header_value("Connection"));
  6578. EXPECT_FALSE(cli_.is_socket_open());
  6579. }
  6580. TEST_F(ServerTest, AlmostTooLongRequest) {
  6581. // test for #2046 - URI length check shouldn't include other content on req
  6582. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  6583. // leading /, space, HTTP/1.1)
  6584. std::string request =
  6585. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  6586. auto res = cli_.Get(request.c_str());
  6587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6588. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6589. }
  6590. TEST_F(ServerTest, LongHeader) {
  6591. Request req;
  6592. req.method = "GET";
  6593. req.path = "/hi";
  6594. std::string host_and_port;
  6595. host_and_port += HOST;
  6596. host_and_port += ":";
  6597. host_and_port += std::to_string(PORT);
  6598. req.headers.emplace("Host", host_and_port.c_str());
  6599. req.headers.emplace("Accept", "*/*");
  6600. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6601. req.headers.emplace(
  6602. "Header-Name",
  6603. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6604. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6605. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6606. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6607. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6608. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6609. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6610. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6611. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6612. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6613. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6614. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6615. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6616. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6617. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6618. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6619. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6620. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6621. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6622. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6623. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6624. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6625. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6626. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6627. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6628. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6629. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6630. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6631. "@@@@@@@@@@@@@@@@");
  6632. auto res = std::make_shared<Response>();
  6633. auto error = Error::Success;
  6634. auto ret = cli_.send(req, *res, error);
  6635. ASSERT_TRUE(ret);
  6636. EXPECT_EQ(StatusCode::OK_200, res->status);
  6637. }
  6638. TEST_F(ServerTest, LongQueryValue) {
  6639. auto start = std::chrono::high_resolution_clock::now();
  6640. cli_.set_keep_alive(true);
  6641. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  6642. auto end = std::chrono::high_resolution_clock::now();
  6643. auto elapsed =
  6644. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  6645. .count();
  6646. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6647. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  6648. EXPECT_LE(elapsed, 1000);
  6649. EXPECT_EQ("close", res->get_header_value("Connection"));
  6650. EXPECT_FALSE(cli_.is_socket_open());
  6651. }
  6652. TEST_F(ServerTest, TooLongQueryValue) {
  6653. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  6654. ASSERT_FALSE(res);
  6655. EXPECT_EQ(Error::Read, res.error());
  6656. }
  6657. TEST_F(ServerTest, TooLongHeader) {
  6658. Request req;
  6659. req.method = "GET";
  6660. req.path = "/hi";
  6661. std::string host_and_port;
  6662. host_and_port += HOST;
  6663. host_and_port += ":";
  6664. host_and_port += std::to_string(PORT);
  6665. req.headers.emplace("Host", host_and_port.c_str());
  6666. req.headers.emplace("Accept", "*/*");
  6667. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6668. req.headers.emplace(
  6669. "Header-Name",
  6670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6696. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6697. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  6698. "@@@@@@@@@@@@@@@@@");
  6699. auto res = std::make_shared<Response>();
  6700. auto error = Error::Success;
  6701. auto ret = cli_.send(req, *res, error);
  6702. ASSERT_TRUE(ret);
  6703. EXPECT_EQ(StatusCode::OK_200, res->status);
  6704. }
  6705. TEST_F(ServerTest, HeaderCountAtLimit) {
  6706. // Test with headers just under the 100 limit
  6707. httplib::Headers headers;
  6708. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  6709. // This should keep us just under the 100 header limit
  6710. for (int i = 0; i < 95; i++) {
  6711. std::string name = "X-Test-Header-" + std::to_string(i);
  6712. std::string value = "value" + std::to_string(i);
  6713. headers.emplace(name, value);
  6714. }
  6715. // This should work fine as we're under the limit
  6716. auto res = cli_.Get("/hi", headers);
  6717. EXPECT_TRUE(res);
  6718. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  6719. }
  6720. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  6721. // Test with many headers to exceed the 100 limit
  6722. httplib::Headers headers;
  6723. // Add 150 headers to definitely exceed the 100 limit
  6724. for (int i = 0; i < 150; i++) {
  6725. std::string name = "X-Test-Header-" + std::to_string(i);
  6726. std::string value = "value" + std::to_string(i);
  6727. headers.emplace(name, value);
  6728. }
  6729. // This should fail due to exceeding header count limit
  6730. cli_.set_keep_alive(true);
  6731. auto res = cli_.Get("/hi", headers);
  6732. // The server should respond with 400 Bad Request
  6733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6734. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6735. EXPECT_EQ("close", res->get_header_value("Connection"));
  6736. EXPECT_FALSE(cli_.is_socket_open());
  6737. }
  6738. TEST_F(ServerTest, PercentEncoding) {
  6739. auto res = cli_.Get("/e%6edwith%");
  6740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6741. EXPECT_EQ(StatusCode::OK_200, res->status);
  6742. }
  6743. TEST_F(ServerTest, PercentEncodingUnicode) {
  6744. auto res = cli_.Get("/e%u006edwith%");
  6745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6746. EXPECT_EQ(StatusCode::OK_200, res->status);
  6747. }
  6748. TEST_F(ServerTest, InvalidPercentEncoding) {
  6749. auto res = cli_.Get("/%endwith%");
  6750. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6751. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6752. }
  6753. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  6754. auto res = cli_.Get("/%uendwith%");
  6755. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6756. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6757. }
  6758. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  6759. auto res = cli_.Get("/hello?aaa=bbb%");
  6760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6761. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  6762. }
  6763. TEST_F(ServerTest, PlusSignEncoding) {
  6764. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  6765. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6766. EXPECT_EQ(StatusCode::OK_200, res->status);
  6767. EXPECT_EQ("a +b", res->body);
  6768. }
  6769. TEST_F(ServerTest, HeaderCountSecurityTest) {
  6770. // This test simulates a potential DoS attack using many headers
  6771. // to verify our security fix prevents memory exhaustion
  6772. httplib::Headers attack_headers;
  6773. // Attempt to add many headers like an attacker would (200 headers to far
  6774. // exceed limit)
  6775. for (int i = 0; i < 200; i++) {
  6776. std::string name = "X-Attack-Header-" + std::to_string(i);
  6777. std::string value = "attack_payload_" + std::to_string(i);
  6778. attack_headers.emplace(name, value);
  6779. }
  6780. // Try to POST with excessive headers
  6781. cli_.set_keep_alive(true);
  6782. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  6783. // Should either fail or return 400 Bad Request due to security limit
  6784. if (res) {
  6785. // If we get a response, it should be 400 Bad Request
  6786. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6787. EXPECT_EQ("close", res->get_header_value("Connection"));
  6788. }
  6789. EXPECT_FALSE(cli_.is_socket_open());
  6790. }
  6791. TEST_F(ServerTest, MultipartFormData) {
  6792. UploadFormDataItems items = {
  6793. {"text1", "text default", "", ""},
  6794. {"text2", "aωb", "", ""},
  6795. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6796. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  6797. {"file3", "", "", "application/octet-stream"},
  6798. {"file4", "", "", " application/json tmp-string "}};
  6799. auto res = cli_.Post("/multipart", items);
  6800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6801. EXPECT_EQ(StatusCode::OK_200, res->status);
  6802. }
  6803. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  6804. UploadFormDataItems items = {
  6805. {"text", "default text", "", ""},
  6806. {"multi_text1", "aaaaa", "", ""},
  6807. {"multi_text1", "bbbbb", "", ""},
  6808. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6809. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  6810. "application/json"},
  6811. };
  6812. auto res = cli_.Post("/multipart/multi_file_values", items);
  6813. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6814. EXPECT_EQ(StatusCode::OK_200, res->status);
  6815. }
  6816. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  6817. auto res = cli_.Get("/hi");
  6818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6819. EXPECT_EQ(StatusCode::OK_200, res->status);
  6820. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  6821. EXPECT_EQ("Hello World!", res->body);
  6822. }
  6823. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  6824. Request req;
  6825. req.method = "POST";
  6826. req.path = "/chunked";
  6827. std::string host_and_port;
  6828. host_and_port += HOST;
  6829. host_and_port += ":";
  6830. host_and_port += std::to_string(PORT);
  6831. req.headers.emplace("Host", host_and_port.c_str());
  6832. req.headers.emplace("Accept", "*/*");
  6833. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6834. req.headers.emplace("Content-Type", "text/plain");
  6835. req.headers.emplace("Content-Length", "0");
  6836. req.headers.emplace(
  6837. "Transfer-Encoding",
  6838. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  6839. // Client does not chunk, so make a chunked body manually.
  6840. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  6841. auto res = std::make_shared<Response>();
  6842. auto error = Error::Success;
  6843. auto ret = cli_.send(req, *res, error);
  6844. ASSERT_TRUE(ret);
  6845. EXPECT_EQ(StatusCode::OK_200, res->status);
  6846. }
  6847. template <typename ClientT>
  6848. static void expect_chunked_body_status(ClientT &cli, const char *body,
  6849. int expected_status) {
  6850. Request req;
  6851. req.method = "POST";
  6852. req.path = "/chunked";
  6853. std::string host_and_port;
  6854. host_and_port += HOST;
  6855. host_and_port += ":";
  6856. host_and_port += std::to_string(PORT);
  6857. req.headers.emplace("Host", host_and_port.c_str());
  6858. req.headers.emplace("Content-Length", "0");
  6859. req.headers.emplace("Transfer-Encoding", "chunked");
  6860. req.body = body;
  6861. auto res = std::make_shared<Response>();
  6862. auto error = Error::Success;
  6863. ASSERT_TRUE(cli.send(req, *res, error));
  6864. EXPECT_EQ(expected_status, res->status);
  6865. }
  6866. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  6867. // rather than treat them as valid lengths.
  6868. template <typename ClientT>
  6869. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  6870. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  6871. }
  6872. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  6873. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  6874. }
  6875. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  6876. expect_chunked_body_rejected(
  6877. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6878. }
  6879. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  6880. // chunk-size line carries no CR, LF or other control character ahead of its
  6881. // terminator. Such a line must be refused rather than read as extension text.
  6882. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  6883. expect_chunked_body_rejected(
  6884. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6885. }
  6886. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  6887. expect_chunked_body_rejected(
  6888. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6889. }
  6890. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  6891. expect_chunked_body_rejected(
  6892. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6893. }
  6894. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  6895. // The literal stays split: a hex escape consumes every hex digit that
  6896. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  6897. expect_chunked_body_rejected(
  6898. cli_, "4;a\x01"
  6899. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  6900. }
  6901. // The bytes around chunk data are no payload, so they cannot ride on the
  6902. // payload limit
  6903. TEST_F(ServerTest, RejectsChunkOverheadPastItsLimit) {
  6904. // Small enough that the whole request is sent before the server turns it
  6905. // down, yet past the limit by the last chunks
  6906. auto pad = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, 'x');
  6907. auto zeros = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, '0');
  6908. auto spaces = std::string(CPPHTTPLIB_HEADER_MAX_LENGTH / 16, ' ');
  6909. for (const auto &size_line : {"1;" + pad, zeros + "1", "1" + spaces}) {
  6910. SCOPED_TRACE(size_line.substr(0, 2));
  6911. std::string body;
  6912. for (auto c : std::string("dechunked post body")) {
  6913. body += size_line + "\r\n" + c + "\r\n";
  6914. }
  6915. body += "0\r\n\r\n";
  6916. expect_chunked_body_rejected(cli_, body.c_str());
  6917. }
  6918. }
  6919. TEST_F(ServerTest, AcceptsChunkExtension) {
  6920. expect_chunked_body_status(cli_,
  6921. "4;name=value\r\ndech\r\n"
  6922. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  6923. "0;last\r\n\r\n",
  6924. StatusCode::OK_200);
  6925. }
  6926. TEST_F(ServerTest, GetStreamed2) {
  6927. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  6928. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6929. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6930. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6931. EXPECT_EQ(true, res->has_header("Content-Range"));
  6932. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  6933. EXPECT_EQ(std::string("ab"), res->body);
  6934. }
  6935. TEST_F(ServerTest, GetStreamed) {
  6936. auto res = cli_.Get("/streamed");
  6937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6938. EXPECT_EQ(StatusCode::OK_200, res->status);
  6939. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6940. EXPECT_EQ(std::string("aaabbb"), res->body);
  6941. }
  6942. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  6943. auto res = cli_.Get("/streamed-without-length",
  6944. Headers{make_range_header({{0, -1}})});
  6945. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6946. EXPECT_EQ(StatusCode::OK_200, res->status);
  6947. EXPECT_EQ(false, res->has_header("Content-Length"));
  6948. EXPECT_EQ(false, res->has_header("Content-Range"));
  6949. EXPECT_EQ(std::string("abcdefg"), res->body);
  6950. }
  6951. TEST_F(ServerTest, GetStreamedWithRange1) {
  6952. auto res =
  6953. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6954. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6955. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6956. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6957. EXPECT_EQ(true, res->has_header("Content-Range"));
  6958. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6959. EXPECT_EQ(std::string("def"), res->body);
  6960. }
  6961. TEST_F(ServerTest, GetStreamedWithRange2) {
  6962. auto res =
  6963. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6964. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6965. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6966. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6967. EXPECT_EQ(true, res->has_header("Content-Range"));
  6968. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6969. EXPECT_EQ(std::string("bcdefg"), res->body);
  6970. }
  6971. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6972. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6973. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6974. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6975. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6976. EXPECT_EQ(true, res->has_header("Content-Range"));
  6977. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6978. EXPECT_EQ(std::string("efg"), res->body);
  6979. }
  6980. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6981. // RFC 9110 14.1.2: a suffix-length longer than the representation selects
  6982. // the entire representation.
  6983. for (auto range : {"bytes=-8", "bytes=-9999"}) {
  6984. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", range}});
  6985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6986. EXPECT_EQ(StatusCode::PartialContent_206, res->status) << range;
  6987. EXPECT_EQ("7", res->get_header_value("Content-Length")) << range;
  6988. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range")) << range;
  6989. EXPECT_EQ(std::string("abcdefg"), res->body) << range;
  6990. }
  6991. }
  6992. TEST_F(ServerTest, GetStreamedWithRangeSuffixZero) {
  6993. auto res =
  6994. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-0"}});
  6995. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6996. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6997. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6998. EXPECT_EQ(false, res->has_header("Content-Range"));
  6999. EXPECT_EQ(0U, res->body.size());
  7000. }
  7001. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  7002. // Only a 206 is served as a partial representation. Under any other status
  7003. // `apply_ranges()` reported the full content length, so the body must match
  7004. // that header, and the content provider must never be asked for an offset
  7005. // outside the representation.
  7006. auto check = [&](int status, const char *range) {
  7007. auto path =
  7008. std::string("/streamed-with-range?status=") + std::to_string(status);
  7009. auto ctx = path + " Range: " + range;
  7010. auto res = cli_.Get(path, Headers{{"Range", range}});
  7011. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  7012. EXPECT_EQ(status, res->status) << ctx;
  7013. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  7014. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  7015. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  7016. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  7017. };
  7018. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  7019. check(403, "bytes=3-5");
  7020. // The offset is far past the representation.
  7021. check(403, "bytes=100000-100200");
  7022. // `first_pos` is still -1 here, and the bounds asserts in
  7023. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  7024. check(403, "bytes=-3");
  7025. // `apply_ranges()` makes no boundary for a non-206 response, so the
  7026. // multipart branch would have written one that is empty.
  7027. check(403, "bytes=1-2, 4-5");
  7028. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  7029. // covers the whole representation.
  7030. check(200, "bytes=3-5");
  7031. check(200, "bytes=1-2, 4-5");
  7032. }
  7033. TEST_F(ServerTest, GetStreamedWithRangeError) {
  7034. auto res =
  7035. cli_.Get("/streamed-with-range",
  7036. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  7037. "92233720368547758079223372036854775807"}});
  7038. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7039. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7040. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7041. EXPECT_EQ(false, res->has_header("Content-Range"));
  7042. EXPECT_EQ(0U, res->body.size());
  7043. }
  7044. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  7045. auto res = cli_.Get(
  7046. "/with-range",
  7047. Headers{{"Range",
  7048. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  7049. {"Accept-Encoding", ""}});
  7050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7051. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7052. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7053. EXPECT_EQ(true, res->has_header("Content-Range"));
  7054. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7055. EXPECT_EQ(std::string("abcdefg"), res->body);
  7056. }
  7057. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  7058. auto res = cli_.Get("/with-range", Headers{
  7059. {"Range", "bytes=0-"},
  7060. {"Accept-Encoding", ""},
  7061. });
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7064. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  7065. EXPECT_EQ(true, res->has_header("Content-Range"));
  7066. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  7067. EXPECT_EQ(std::string("abcdefg"), res->body);
  7068. }
  7069. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  7070. auto res = cli_.Get("/streamed-with-range",
  7071. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7072. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7073. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7074. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7075. EXPECT_EQ(false, res->has_header("Content-Range"));
  7076. EXPECT_EQ(267U, res->body.size());
  7077. // Check that both range contents are present
  7078. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  7079. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7080. // Check that Content-Range headers are present for both ranges
  7081. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  7082. std::string::npos);
  7083. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7084. std::string::npos);
  7085. }
  7086. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  7087. Ranges ranges;
  7088. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  7089. ranges.emplace_back(0, -1);
  7090. }
  7091. auto res = cli_.Get("/streamed-with-range?error",
  7092. Headers{{make_range_header(ranges)}});
  7093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7094. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7095. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7096. EXPECT_EQ(false, res->has_header("Content-Range"));
  7097. EXPECT_EQ(0U, res->body.size());
  7098. }
  7099. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  7100. auto res = cli_.Get("/streamed-with-range",
  7101. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  7102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7103. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7104. EXPECT_EQ(5U, res->body.size());
  7105. // Check that overlapping ranges are coalesced into a single range
  7106. EXPECT_EQ("bcdef", res->body);
  7107. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  7108. // Should be single range, not multipart
  7109. EXPECT_TRUE(res->has_header("Content-Range"));
  7110. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7111. }
  7112. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  7113. auto res = cli_.Get("/streamed-with-range",
  7114. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  7115. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7116. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7117. EXPECT_EQ(268U, res->body.size());
  7118. // Check that both range contents are present
  7119. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  7120. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  7121. // Check that Content-Range headers are present for both ranges
  7122. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  7123. std::string::npos);
  7124. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  7125. std::string::npos);
  7126. }
  7127. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  7128. auto res = cli_.Get("/streamed-with-range",
  7129. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  7130. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7131. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7132. EXPECT_EQ(269U, res->body.size());
  7133. // Check that both duplicate range contents are present
  7134. size_t first_abc = res->body.find("abc\r\n");
  7135. EXPECT_TRUE(first_abc != std::string::npos);
  7136. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  7137. EXPECT_TRUE(second_abc != std::string::npos);
  7138. // Check that Content-Range headers are present for both ranges
  7139. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  7140. EXPECT_TRUE(first_range != std::string::npos);
  7141. size_t second_range =
  7142. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  7143. EXPECT_TRUE(second_range != std::string::npos);
  7144. }
  7145. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  7146. auto res =
  7147. cli_.Get("/streamed-with-range?error",
  7148. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  7149. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7150. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7151. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7152. EXPECT_EQ(false, res->has_header("Content-Range"));
  7153. EXPECT_EQ(0U, res->body.size());
  7154. }
  7155. TEST_F(ServerTest, GetStreamedEndless) {
  7156. uint64_t offset = 0;
  7157. auto res = cli_.Get("/streamed-cancel",
  7158. [&](const char * /*data*/, uint64_t data_length) {
  7159. if (offset < 100) {
  7160. offset += data_length;
  7161. return true;
  7162. }
  7163. return false;
  7164. });
  7165. ASSERT_TRUE(!res);
  7166. EXPECT_EQ(Error::Canceled, res.error());
  7167. }
  7168. TEST_F(ServerTest, ClientStop) {
  7169. std::atomic_size_t count{4};
  7170. std::vector<std::thread> threads;
  7171. for (auto i = count.load(); i != 0; --i) {
  7172. threads.emplace_back([&]() {
  7173. auto res = cli_.Get("/streamed-cancel",
  7174. [&](const char *, uint64_t) { return true; });
  7175. --count;
  7176. ASSERT_TRUE(!res);
  7177. EXPECT_TRUE(res.error() == Error::Canceled ||
  7178. res.error() == Error::Read || res.error() == Error::Write);
  7179. });
  7180. }
  7181. std::this_thread::sleep_for(std::chrono::seconds(2));
  7182. while (count != 0) {
  7183. cli_.stop();
  7184. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  7185. }
  7186. for (auto &t : threads) {
  7187. t.join();
  7188. }
  7189. }
  7190. TEST_F(ServerTest, GetWithRange1) {
  7191. auto res = cli_.Get("/with-range", Headers{
  7192. make_range_header({{3, 5}}),
  7193. {"Accept-Encoding", ""},
  7194. });
  7195. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7196. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7197. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  7198. EXPECT_EQ(true, res->has_header("Content-Range"));
  7199. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  7200. EXPECT_EQ(std::string("def"), res->body);
  7201. }
  7202. TEST_F(ServerTest, GetWithRange2) {
  7203. auto res = cli_.Get("/with-range", Headers{
  7204. make_range_header({{1, -1}}),
  7205. {"Accept-Encoding", ""},
  7206. });
  7207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7208. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7209. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7210. EXPECT_EQ(true, res->has_header("Content-Range"));
  7211. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  7212. EXPECT_EQ(std::string("bcdefg"), res->body);
  7213. }
  7214. TEST_F(ServerTest, GetWithRange3) {
  7215. auto res = cli_.Get("/with-range", Headers{
  7216. make_range_header({{0, 0}}),
  7217. {"Accept-Encoding", ""},
  7218. });
  7219. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7220. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7221. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  7222. EXPECT_EQ(true, res->has_header("Content-Range"));
  7223. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  7224. EXPECT_EQ(std::string("a"), res->body);
  7225. }
  7226. TEST_F(ServerTest, GetWithRange4) {
  7227. auto res = cli_.Get("/with-range", Headers{
  7228. make_range_header({{-1, 2}}),
  7229. {"Accept-Encoding", ""},
  7230. });
  7231. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7232. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7233. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7234. EXPECT_EQ(true, res->has_header("Content-Range"));
  7235. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  7236. EXPECT_EQ(std::string("fg"), res->body);
  7237. }
  7238. TEST_F(ServerTest, GetWithRange5) {
  7239. auto res = cli_.Get("/with-range", Headers{
  7240. make_range_header({{0, 5}}),
  7241. {"Accept-Encoding", ""},
  7242. });
  7243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7244. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7245. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7246. EXPECT_EQ(true, res->has_header("Content-Range"));
  7247. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  7248. EXPECT_EQ(std::string("abcdef"), res->body);
  7249. }
  7250. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  7251. auto res =
  7252. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  7253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7254. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7255. }
  7256. TEST_F(ServerTest, GetWithRangeMultipart) {
  7257. auto res =
  7258. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7261. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  7262. EXPECT_EQ(false, res->has_header("Content-Range"));
  7263. EXPECT_EQ(267U, res->body.size());
  7264. }
  7265. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  7266. auto res = cli_.Get("/with-range",
  7267. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  7268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7269. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  7270. }
  7271. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  7272. auto res = cli_.Get("/with-range-customized-response",
  7273. Headers{{make_range_header({{1, 2}})}});
  7274. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7275. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7276. EXPECT_EQ(true, res->has_header("Content-Length"));
  7277. EXPECT_EQ(false, res->has_header("Content-Range"));
  7278. EXPECT_EQ(JSON_DATA, res->body);
  7279. }
  7280. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  7281. auto res = cli_.Get("/with-range-customized-response",
  7282. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  7283. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7284. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7285. EXPECT_EQ(true, res->has_header("Content-Length"));
  7286. EXPECT_EQ(false, res->has_header("Content-Range"));
  7287. EXPECT_EQ(JSON_DATA, res->body);
  7288. }
  7289. TEST_F(ServerTest, Issue1772) {
  7290. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  7291. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7292. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  7293. }
  7294. TEST_F(ServerTest, Issue609) {
  7295. auto res = cli_.Delete("/issue609");
  7296. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7297. EXPECT_EQ(StatusCode::OK_200, res->status);
  7298. EXPECT_EQ(std::string("ok"), res->body);
  7299. }
  7300. TEST_F(ServerTest, GetStreamedChunked) {
  7301. auto res = cli_.Get("/streamed-chunked");
  7302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7303. EXPECT_EQ(StatusCode::OK_200, res->status);
  7304. EXPECT_EQ(std::string("123456789"), res->body);
  7305. }
  7306. TEST_F(ServerTest, GetStreamedChunked2) {
  7307. auto res = cli_.Get("/streamed-chunked2");
  7308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7309. EXPECT_EQ(StatusCode::OK_200, res->status);
  7310. EXPECT_EQ(std::string("123456789"), res->body);
  7311. }
  7312. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  7313. auto res = cli_.Get("/streamed-chunked-with-trailer");
  7314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7315. EXPECT_EQ(StatusCode::OK_200, res->status);
  7316. EXPECT_EQ(std::string("123456789"), res->body);
  7317. EXPECT_TRUE(res->has_header("Trailer"));
  7318. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  7319. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  7320. // Trailers are now stored separately from headers (security fix)
  7321. EXPECT_EQ(2U, res->trailers.size());
  7322. EXPECT_TRUE(res->has_trailer("Dummy1"));
  7323. EXPECT_TRUE(res->has_trailer("Dummy2"));
  7324. EXPECT_FALSE(res->has_trailer("Dummy3"));
  7325. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  7326. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  7327. // Verify trailers are NOT in headers (security verification)
  7328. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  7329. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  7330. }
  7331. TEST_F(ServerTest, LargeChunkedPost) {
  7332. Request req;
  7333. req.method = "POST";
  7334. req.path = "/large-chunked";
  7335. std::string host_and_port;
  7336. host_and_port += HOST;
  7337. host_and_port += ":";
  7338. host_and_port += std::to_string(PORT);
  7339. req.headers.emplace("Host", host_and_port.c_str());
  7340. req.headers.emplace("Accept", "*/*");
  7341. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  7342. req.headers.emplace("Content-Type", "text/plain");
  7343. req.headers.emplace("Content-Length", "0");
  7344. req.headers.emplace("Transfer-Encoding", "chunked");
  7345. std::string long_string(30 * 1024u, 'a');
  7346. std::string chunk = "7800\r\n" + long_string + "\r\n";
  7347. // Attempt to make a large enough post to exceed OS buffers, to test that
  7348. // the server handles short reads if the full chunk data isn't available.
  7349. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  7350. auto res = std::make_shared<Response>();
  7351. auto error = Error::Success;
  7352. auto ret = cli_.send(req, *res, error);
  7353. ASSERT_TRUE(ret);
  7354. EXPECT_EQ(StatusCode::OK_200, res->status);
  7355. }
  7356. TEST_F(ServerTest, GetMethodRemoteAddr) {
  7357. auto res = cli_.Get("/remote_addr");
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::OK_200, res->status);
  7360. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7361. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  7362. }
  7363. TEST_F(ServerTest, GetMethodLocalAddr) {
  7364. auto res = cli_.Get("/local_addr");
  7365. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7366. EXPECT_EQ(StatusCode::OK_200, res->status);
  7367. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7368. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  7369. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  7370. }
  7371. TEST_F(ServerTest, HTTPResponseSplitting) {
  7372. auto res = cli_.Get("/http_response_splitting");
  7373. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7374. EXPECT_EQ(StatusCode::OK_200, res->status);
  7375. }
  7376. TEST_F(ServerTest, SlowRequest) {
  7377. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7378. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7379. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  7380. }
  7381. #if 0
  7382. TEST_F(ServerTest, SlowPost) {
  7383. char buffer[64 * 1024];
  7384. memset(buffer, 0x42, sizeof(buffer));
  7385. auto res = cli_.Post(
  7386. "/slowpost", 64 * 1024 * 1024,
  7387. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7388. auto ret = sink.write(buffer, sizeof(buffer));
  7389. EXPECT_TRUE(ret);
  7390. return true;
  7391. },
  7392. "text/plain");
  7393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7394. EXPECT_EQ(StatusCode::OK_200, res->status);
  7395. }
  7396. TEST_F(ServerTest, SlowPostFail) {
  7397. char buffer[64 * 1024];
  7398. memset(buffer, 0x42, sizeof(buffer));
  7399. cli_.set_write_timeout(std::chrono::seconds(0));
  7400. auto res = cli_.Post(
  7401. "/slowpost", 64 * 1024 * 1024,
  7402. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7403. sink.write(buffer, sizeof(buffer));
  7404. return true;
  7405. },
  7406. "text/plain");
  7407. ASSERT_TRUE(!res);
  7408. EXPECT_EQ(Error::Write, res.error());
  7409. }
  7410. #endif
  7411. TEST_F(ServerTest, Put) {
  7412. auto res = cli_.Put("/put", "PUT", "text/plain");
  7413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7414. EXPECT_EQ(StatusCode::OK_200, res->status);
  7415. EXPECT_EQ("PUT", res->body);
  7416. }
  7417. TEST_F(ServerTest, PutWithContentProvider) {
  7418. auto res = cli_.Put(
  7419. "/put", 3,
  7420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7421. sink.os << "PUT";
  7422. return true;
  7423. },
  7424. "text/plain");
  7425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7426. EXPECT_EQ(StatusCode::OK_200, res->status);
  7427. EXPECT_EQ("PUT", res->body);
  7428. }
  7429. TEST_F(ServerTest, PostWithContentProviderAbort) {
  7430. auto res = cli_.Post(
  7431. "/post", 42,
  7432. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7433. return false;
  7434. },
  7435. "text/plain");
  7436. ASSERT_TRUE(!res);
  7437. EXPECT_EQ(Error::Canceled, res.error());
  7438. }
  7439. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  7440. auto res = cli_.Put(
  7441. "/put",
  7442. [](size_t /*offset*/, DataSink &sink) {
  7443. sink.os << "PUT";
  7444. sink.done();
  7445. return true;
  7446. },
  7447. "text/plain");
  7448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7449. EXPECT_EQ(StatusCode::OK_200, res->status);
  7450. EXPECT_EQ("PUT", res->body);
  7451. }
  7452. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  7453. auto res = cli_.Post(
  7454. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7455. "text/plain");
  7456. ASSERT_TRUE(!res);
  7457. EXPECT_EQ(Error::Canceled, res.error());
  7458. }
  7459. TEST_F(ServerTest, PostLoopBack) {
  7460. std::string body;
  7461. auto res = cli_.Post(
  7462. "/post-loopback", 9,
  7463. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7464. EXPECT_EQ(9u, length);
  7465. sink.write("123", 3);
  7466. sink.write("456", 3);
  7467. sink.write("789", 3);
  7468. return true;
  7469. },
  7470. "text/plain",
  7471. [&body](const char *data, size_t data_length) {
  7472. body.append(data, data_length);
  7473. return true;
  7474. });
  7475. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7476. EXPECT_EQ(StatusCode::OK_200, res->status);
  7477. EXPECT_EQ("123456789", body);
  7478. }
  7479. TEST_F(ServerTest, PutLoopBack) {
  7480. std::string body;
  7481. auto res = cli_.Put(
  7482. "/put-loopback", 9,
  7483. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7484. EXPECT_EQ(9u, length);
  7485. sink.write("123", 3);
  7486. sink.write("456", 3);
  7487. sink.write("789", 3);
  7488. return true;
  7489. },
  7490. "text/plain",
  7491. [&body](const char *data, size_t data_length) {
  7492. body.append(data, data_length);
  7493. return true;
  7494. });
  7495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7496. EXPECT_EQ(StatusCode::OK_200, res->status);
  7497. EXPECT_EQ("123456789", body);
  7498. }
  7499. TEST_F(ServerTest, PatchLoopBack) {
  7500. std::string body;
  7501. auto res = cli_.Patch(
  7502. "/patch-loopback", 9,
  7503. [](size_t /*offset*/, size_t length, DataSink &sink) {
  7504. EXPECT_EQ(9u, length);
  7505. sink.write("123", 3);
  7506. sink.write("456", 3);
  7507. sink.write("789", 3);
  7508. return true;
  7509. },
  7510. "text/plain",
  7511. [&body](const char *data, size_t data_length) {
  7512. body.append(data, data_length);
  7513. return true;
  7514. });
  7515. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7516. EXPECT_EQ(StatusCode::OK_200, res->status);
  7517. EXPECT_EQ("123456789", body);
  7518. }
  7519. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  7520. std::string body;
  7521. auto res = cli_.Post(
  7522. "/post-loopback",
  7523. [](size_t /*offset*/, DataSink &sink) {
  7524. sink.write("123", 3);
  7525. sink.write("456", 3);
  7526. sink.write("789", 3);
  7527. sink.done();
  7528. return true;
  7529. },
  7530. "text/plain",
  7531. [&body](const char *data, size_t data_length) {
  7532. body.append(data, data_length);
  7533. return true;
  7534. });
  7535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7536. EXPECT_EQ(StatusCode::OK_200, res->status);
  7537. EXPECT_EQ("123456789", body);
  7538. }
  7539. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7540. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  7541. cli_.set_compress(true);
  7542. auto res = cli_.Put(
  7543. "/put", 3,
  7544. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7545. sink.os << "PUT";
  7546. return true;
  7547. },
  7548. "text/plain");
  7549. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7550. EXPECT_EQ(StatusCode::OK_200, res->status);
  7551. EXPECT_EQ("PUT", res->body);
  7552. }
  7553. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  7554. cli_.set_compress(true);
  7555. auto res = cli_.Post(
  7556. "/post", 42,
  7557. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  7558. return false;
  7559. },
  7560. "text/plain");
  7561. ASSERT_TRUE(!res);
  7562. EXPECT_EQ(Error::Canceled, res.error());
  7563. }
  7564. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  7565. cli_.set_compress(true);
  7566. auto res = cli_.Put(
  7567. "/put",
  7568. [](size_t /*offset*/, DataSink &sink) {
  7569. sink.os << "PUT";
  7570. sink.done();
  7571. return true;
  7572. },
  7573. "text/plain");
  7574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7575. EXPECT_EQ(StatusCode::OK_200, res->status);
  7576. EXPECT_EQ("PUT", res->body);
  7577. }
  7578. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  7579. cli_.set_compress(true);
  7580. auto res = cli_.Post(
  7581. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  7582. "text/plain");
  7583. ASSERT_TRUE(!res);
  7584. EXPECT_EQ(Error::Canceled, res.error());
  7585. }
  7586. TEST_F(ServerTest, PutLargeFileWithGzip) {
  7587. cli_.set_compress(true);
  7588. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7590. EXPECT_EQ(StatusCode::OK_200, res->status);
  7591. EXPECT_EQ(LARGE_DATA, res->body);
  7592. }
  7593. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  7594. #ifdef CPPHTTPLIB_SSL_ENABLED
  7595. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  7596. Client cli(s.c_str());
  7597. cli.enable_server_certificate_verification(false);
  7598. #else
  7599. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  7600. Client cli(s.c_str());
  7601. #endif
  7602. cli.set_compress(true);
  7603. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  7604. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7605. EXPECT_EQ(StatusCode::OK_200, res->status);
  7606. EXPECT_EQ(LARGE_DATA, res->body);
  7607. // The compressed size should be less than a 10th of the original. May vary
  7608. // depending on the zlib library.
  7609. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  7610. static_cast<uint64_t>(10 * 1024 * 1024));
  7611. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7612. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7613. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  7614. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  7615. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  7616. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  7617. #endif
  7618. }
  7619. TEST_F(ServerTest, PutContentWithDeflate) {
  7620. cli_.set_compress(false);
  7621. Headers headers;
  7622. headers.emplace("Content-Encoding", "deflate");
  7623. // PUT in deflate format:
  7624. auto res = cli_.Put("/put", headers,
  7625. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  7626. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7627. EXPECT_EQ(StatusCode::OK_200, res->status);
  7628. EXPECT_EQ("PUT", res->body);
  7629. }
  7630. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  7631. Headers headers;
  7632. headers.emplace("Accept-Encoding", "gzip, deflate");
  7633. auto res = cli_.Get("/streamed-chunked", headers);
  7634. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7635. EXPECT_EQ(StatusCode::OK_200, res->status);
  7636. EXPECT_EQ(std::string("123456789"), res->body);
  7637. }
  7638. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  7639. Headers headers;
  7640. headers.emplace("Accept-Encoding", "gzip, deflate");
  7641. auto res = cli_.Get("/streamed-chunked2", headers);
  7642. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7643. EXPECT_EQ(StatusCode::OK_200, res->status);
  7644. EXPECT_EQ(std::string("123456789"), res->body);
  7645. }
  7646. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  7647. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  7648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7649. EXPECT_EQ(StatusCode::OK_200, res->status);
  7650. }
  7651. TEST(GzipDecompressor, ChunkedDecompression) {
  7652. std::string data;
  7653. for (size_t i = 0; i < 32 * 1024; ++i) {
  7654. data.push_back(static_cast<char>('a' + i % 26));
  7655. }
  7656. std::string compressed_data;
  7657. {
  7658. httplib::detail::gzip_compressor compressor;
  7659. bool result = compressor.compress(
  7660. data.data(), data.size(),
  7661. /*last=*/true,
  7662. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  7663. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  7664. compressed_data_size);
  7665. return true;
  7666. });
  7667. ASSERT_TRUE(result);
  7668. }
  7669. std::string decompressed_data;
  7670. {
  7671. httplib::detail::gzip_decompressor decompressor;
  7672. // Chunk size is chosen specifically to have a decompressed chunk size equal
  7673. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  7674. size_t chunk_size = 130;
  7675. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  7676. chunk_begin += chunk_size) {
  7677. size_t current_chunk_size =
  7678. std::min(compressed_data.size() - chunk_begin, chunk_size);
  7679. bool result = decompressor.decompress(
  7680. compressed_data.data() + chunk_begin, current_chunk_size,
  7681. [&](const char *decompressed_data_chunk,
  7682. size_t decompressed_data_chunk_size) {
  7683. decompressed_data.insert(decompressed_data.size(),
  7684. decompressed_data_chunk,
  7685. decompressed_data_chunk_size);
  7686. return true;
  7687. });
  7688. ASSERT_TRUE(result);
  7689. }
  7690. }
  7691. ASSERT_EQ(data, decompressed_data);
  7692. }
  7693. TEST(GzipDecompressor, DeflateDecompression) {
  7694. std::string original_text = "Raw deflate without gzip";
  7695. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7696. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7697. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7698. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  7699. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7700. std::string decompressed_data;
  7701. {
  7702. httplib::detail::gzip_decompressor decompressor;
  7703. bool result = decompressor.decompress(
  7704. compressed_data.data(), compressed_data.size(),
  7705. [&](const char *decompressed_data_chunk,
  7706. size_t decompressed_data_chunk_size) {
  7707. decompressed_data.insert(decompressed_data.size(),
  7708. decompressed_data_chunk,
  7709. decompressed_data_chunk_size);
  7710. return true;
  7711. });
  7712. ASSERT_TRUE(result);
  7713. }
  7714. ASSERT_EQ(original_text, decompressed_data);
  7715. }
  7716. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  7717. std::string original_text = "Raw deflate without gzip";
  7718. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  7719. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  7720. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  7721. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  7722. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  7723. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  7724. std::string decompressed_data;
  7725. {
  7726. httplib::detail::gzip_decompressor decompressor;
  7727. bool result = decompressor.decompress(
  7728. compressed_data.data(), compressed_data.size(),
  7729. [&](const char *decompressed_data_chunk,
  7730. size_t decompressed_data_chunk_size) {
  7731. decompressed_data.insert(decompressed_data.size(),
  7732. decompressed_data_chunk,
  7733. decompressed_data_chunk_size);
  7734. return true;
  7735. });
  7736. ASSERT_TRUE(result);
  7737. }
  7738. ASSERT_EQ(original_text, decompressed_data);
  7739. }
  7740. #endif
  7741. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7742. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  7743. Headers headers;
  7744. headers.emplace("Accept-Encoding", "br");
  7745. auto res = cli_.Get("/streamed-chunked", headers);
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ(std::string("123456789"), res->body);
  7749. }
  7750. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  7751. Headers headers;
  7752. headers.emplace("Accept-Encoding", "br");
  7753. auto res = cli_.Get("/streamed-chunked2", headers);
  7754. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7755. EXPECT_EQ(StatusCode::OK_200, res->status);
  7756. EXPECT_EQ(std::string("123456789"), res->body);
  7757. }
  7758. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  7759. cli_.set_compress(true);
  7760. auto res = cli_.Put(
  7761. "/put", 3,
  7762. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  7763. sink.os << "PUT";
  7764. return true;
  7765. },
  7766. "text/plain");
  7767. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7768. EXPECT_EQ(StatusCode::OK_200, res->status);
  7769. EXPECT_EQ("PUT", res->body);
  7770. }
  7771. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  7772. cli_.set_compress(true);
  7773. auto res = cli_.Put(
  7774. "/put",
  7775. [](size_t /*offset*/, DataSink &sink) {
  7776. sink.os << "PUT";
  7777. sink.done();
  7778. return true;
  7779. },
  7780. "text/plain");
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. EXPECT_EQ("PUT", res->body);
  7784. }
  7785. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  7786. cli_.set_compress(true);
  7787. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  7788. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7789. EXPECT_EQ(StatusCode::OK_200, res->status);
  7790. EXPECT_EQ(LARGE_DATA, res->body);
  7791. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  7792. }
  7793. #endif
  7794. TEST_F(ServerTest, Patch) {
  7795. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  7796. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7797. EXPECT_EQ(StatusCode::OK_200, res->status);
  7798. EXPECT_EQ("PATCH", res->body);
  7799. }
  7800. TEST_F(ServerTest, Delete) {
  7801. auto res = cli_.Delete("/delete");
  7802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7803. EXPECT_EQ(StatusCode::OK_200, res->status);
  7804. EXPECT_EQ("DELETE", res->body);
  7805. }
  7806. TEST_F(ServerTest, DeleteContentReceiver) {
  7807. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  7808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7809. EXPECT_EQ(StatusCode::OK_200, res->status);
  7810. EXPECT_EQ("content", res->body);
  7811. }
  7812. TEST_F(ServerTest, Options) {
  7813. auto res = cli_.Options("*");
  7814. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7815. EXPECT_EQ(StatusCode::OK_200, res->status);
  7816. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  7817. EXPECT_TRUE(res->body.empty());
  7818. }
  7819. TEST_F(ServerTest, URL) {
  7820. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  7821. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7822. EXPECT_EQ(StatusCode::OK_200, res->status);
  7823. }
  7824. TEST_F(ServerTest, ArrayParam) {
  7825. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  7826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7827. EXPECT_EQ(StatusCode::OK_200, res->status);
  7828. }
  7829. TEST_F(ServerTest, ArrayParamValues) {
  7830. auto res =
  7831. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  7832. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7833. EXPECT_EQ(StatusCode::OK_200, res->status);
  7834. }
  7835. TEST_F(ServerTest, NoMultipleHeaders) {
  7836. Headers headers = {{"Content-Length", "5"}};
  7837. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  7838. "text/plain");
  7839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7840. EXPECT_EQ(StatusCode::OK_200, res->status);
  7841. }
  7842. TEST_F(ServerTest, PostContentReceiver) {
  7843. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7845. ASSERT_EQ(StatusCode::OK_200, res->status);
  7846. ASSERT_EQ("content", res->body);
  7847. }
  7848. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  7849. UploadFormDataItems items = {
  7850. {"text1", "text default", "", ""},
  7851. {"text2", "aωb", "", ""},
  7852. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7853. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7854. {"file3", "", "", "application/octet-stream"},
  7855. };
  7856. auto res = cli_.Post("/content_receiver", items);
  7857. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7858. EXPECT_EQ(StatusCode::OK_200, res->status);
  7859. }
  7860. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  7861. UploadFormDataItems items = {
  7862. {"text1", "text default", "", ""},
  7863. {"text2", "aωb", "", ""},
  7864. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  7865. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  7866. {"file3", "", "", "application/octet-stream"},
  7867. };
  7868. auto boundary = std::string("+++++");
  7869. std::string body;
  7870. for (const auto &item : items) {
  7871. body += "--" + boundary + "\r\n";
  7872. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  7873. if (!item.filename.empty()) {
  7874. body += "; filename=\"" + item.filename + "\"";
  7875. }
  7876. body += "\r\n";
  7877. if (!item.content_type.empty()) {
  7878. body += "Content-Type: " + item.content_type + "\r\n";
  7879. }
  7880. body += "\r\n";
  7881. body += item.content + "\r\n";
  7882. }
  7883. body += "--" + boundary + "--\r\n";
  7884. std::string content_type = "multipart/form-data; boundary=" + boundary;
  7885. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  7886. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7887. EXPECT_EQ(StatusCode::OK_200, res->status);
  7888. }
  7889. TEST(MultipartFormDataTest, FieldEscaping) {
  7890. Server svr;
  7891. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7892. const ContentReader &content_reader) {
  7893. ASSERT_TRUE(req.is_multipart_form_data());
  7894. std::vector<FormData> received;
  7895. content_reader(
  7896. [&](const FormData &file) {
  7897. received.push_back(file);
  7898. return true;
  7899. },
  7900. [&](const char *data, size_t data_length) {
  7901. received.back().content.append(data, data_length);
  7902. return true;
  7903. });
  7904. // '"', CR and LF in names and filenames are escaped following the
  7905. // WHATWG HTML standard, so each part still parses as a single part
  7906. // with no injected headers. Content types get CR/LF escaped too,
  7907. // while '"' (legal there, e.g. quoted charset) is preserved.
  7908. ASSERT_EQ(4U, received.size());
  7909. EXPECT_EQ("na%22me", received[0].name);
  7910. EXPECT_EQ("quoted name", received[0].content);
  7911. EXPECT_EQ("file", received[1].name);
  7912. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  7913. received[1].filename);
  7914. EXPECT_EQ("application/octet-stream", received[1].content_type);
  7915. EXPECT_EQ("injected", received[1].content);
  7916. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  7917. EXPECT_EQ("my%22file.txt", received[2].filename);
  7918. EXPECT_EQ("cr lf name", received[2].content);
  7919. EXPECT_EQ("typed", received[3].name);
  7920. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  7921. received[3].content_type);
  7922. EXPECT_EQ("typed content", received[3].content);
  7923. });
  7924. auto port = svr.bind_to_any_port("localhost");
  7925. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7926. auto se = detail::scope_exit([&] {
  7927. svr.stop();
  7928. t.join();
  7929. ASSERT_FALSE(svr.is_running());
  7930. });
  7931. svr.wait_until_ready();
  7932. Client cli("localhost", port);
  7933. UploadFormDataItems items = {
  7934. {"na\"me", "quoted name", "", ""},
  7935. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  7936. "application/octet-stream"},
  7937. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  7938. {"typed", "typed content", "",
  7939. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  7940. };
  7941. auto res = cli.Post("/post", items);
  7942. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7943. EXPECT_EQ(StatusCode::OK_200, res->status);
  7944. }
  7945. TEST(MultipartFormDataTest, PublicWriterAPI) {
  7946. const UploadFormDataItems items = {
  7947. {"name1", "Content 1", "", ""},
  7948. {"name2", "Content 2", "file2.txt", "text/plain"},
  7949. };
  7950. Server svr;
  7951. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  7952. const ContentReader &content_reader) {
  7953. ASSERT_TRUE(req.is_multipart_form_data());
  7954. std::vector<FormData> received;
  7955. content_reader(
  7956. [&](const FormData &file) {
  7957. received.push_back(file);
  7958. return true;
  7959. },
  7960. [&](const char *data, size_t data_length) {
  7961. received.back().content.append(data, data_length);
  7962. return true;
  7963. });
  7964. ASSERT_EQ(2U, received.size());
  7965. EXPECT_EQ("name1", received[0].name);
  7966. EXPECT_EQ("Content 1", received[0].content);
  7967. EXPECT_EQ("name2", received[1].name);
  7968. EXPECT_EQ("Content 2", received[1].content);
  7969. EXPECT_EQ("file2.txt", received[1].filename);
  7970. EXPECT_EQ("text/plain", received[1].content_type);
  7971. });
  7972. auto port = svr.bind_to_any_port("localhost");
  7973. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7974. auto se = detail::scope_exit([&] {
  7975. svr.stop();
  7976. t.join();
  7977. ASSERT_FALSE(svr.is_running());
  7978. });
  7979. svr.wait_until_ready();
  7980. Client cli("localhost", port);
  7981. // Whole-body serialization with a generated boundary
  7982. {
  7983. MultipartFormDataWriter writer;
  7984. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7985. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7986. writer.content_type());
  7987. auto body = writer.serialize(items);
  7988. EXPECT_EQ(body.size(), writer.content_length(items));
  7989. auto res = cli.Post("/post", body, writer.content_type());
  7990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7991. EXPECT_EQ(StatusCode::OK_200, res->status);
  7992. }
  7993. // Per-part framing with a custom boundary via a content provider
  7994. {
  7995. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7996. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7997. MultipartFormDataWriter writer("custom-boundary_123");
  7998. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7999. std::string body;
  8000. for (const auto &item : items) {
  8001. body += writer.item_begin(item);
  8002. body += item.content;
  8003. body += MultipartFormDataWriter::item_end();
  8004. }
  8005. body += writer.finish();
  8006. EXPECT_EQ(body.size(), writer.content_length(items));
  8007. auto res = cli.Post(
  8008. "/post", body.size(),
  8009. [&](size_t offset, size_t length, DataSink &sink) {
  8010. sink.write(body.data() + offset, length);
  8011. return true;
  8012. },
  8013. writer.content_type());
  8014. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8015. EXPECT_EQ(StatusCode::OK_200, res->status);
  8016. }
  8017. }
  8018. TEST_F(ServerTest, PostContentReceiverGzip) {
  8019. cli_.set_compress(true);
  8020. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  8021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8022. ASSERT_EQ(StatusCode::OK_200, res->status);
  8023. ASSERT_EQ("content", res->body);
  8024. }
  8025. TEST_F(ServerTest, PutContentReceiver) {
  8026. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  8027. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8028. ASSERT_EQ(StatusCode::OK_200, res->status);
  8029. ASSERT_EQ("content", res->body);
  8030. }
  8031. TEST_F(ServerTest, PatchContentReceiver) {
  8032. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  8033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8034. ASSERT_EQ(StatusCode::OK_200, res->status);
  8035. ASSERT_EQ("content", res->body);
  8036. }
  8037. template <typename ClientType>
  8038. void TestWithHeadersAndContentReceiver(
  8039. ClientType &cli,
  8040. std::function<Result(ClientType &, const std::string &, const Headers &,
  8041. const std::string &, const std::string &,
  8042. ContentReceiver, DownloadProgress)>
  8043. request_func) {
  8044. Headers headers;
  8045. headers.emplace("X-Custom-Header", "test-value");
  8046. std::string received_body;
  8047. auto res = request_func(
  8048. cli, "/content_receiver", headers, "content", "application/json",
  8049. [&](const char *data, size_t data_length) {
  8050. received_body.append(data, data_length);
  8051. return true;
  8052. },
  8053. nullptr);
  8054. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8055. EXPECT_EQ(StatusCode::OK_200, res->status);
  8056. EXPECT_EQ("content", received_body);
  8057. }
  8058. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  8059. #ifdef CPPHTTPLIB_SSL_ENABLED
  8060. using ClientT = SSLClient;
  8061. #else
  8062. using ClientT = Client;
  8063. #endif
  8064. TestWithHeadersAndContentReceiver<ClientT>(
  8065. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8066. const std::string &body, const std::string &content_type,
  8067. ContentReceiver receiver, DownloadProgress progress) {
  8068. return cli.Post(path, headers, body, content_type, receiver, progress);
  8069. });
  8070. }
  8071. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  8072. #ifdef CPPHTTPLIB_SSL_ENABLED
  8073. using ClientT = SSLClient;
  8074. #else
  8075. using ClientT = Client;
  8076. #endif
  8077. TestWithHeadersAndContentReceiver<ClientT>(
  8078. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8079. const std::string &body, const std::string &content_type,
  8080. ContentReceiver receiver, DownloadProgress progress) {
  8081. return cli.Put(path, headers, body, content_type, receiver, progress);
  8082. });
  8083. }
  8084. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  8085. #ifdef CPPHTTPLIB_SSL_ENABLED
  8086. using ClientT = SSLClient;
  8087. #else
  8088. using ClientT = Client;
  8089. #endif
  8090. TestWithHeadersAndContentReceiver<ClientT>(
  8091. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8092. const std::string &body, const std::string &content_type,
  8093. ContentReceiver receiver, DownloadProgress progress) {
  8094. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8095. });
  8096. }
  8097. template <typename ClientType>
  8098. void TestWithHeadersAndContentReceiverWithProgress(
  8099. ClientType &cli,
  8100. std::function<Result(ClientType &, const std::string &, const Headers &,
  8101. const std::string &, const std::string &,
  8102. ContentReceiver, DownloadProgress)>
  8103. request_func) {
  8104. Headers headers;
  8105. headers.emplace("X-Test-Header", "progress-test");
  8106. std::string received_body;
  8107. auto progress_called = false;
  8108. auto res = request_func(
  8109. cli, "/content_receiver", headers, "content", "text/plain",
  8110. [&](const char *data, size_t data_length) {
  8111. received_body.append(data, data_length);
  8112. return true;
  8113. },
  8114. [&](uint64_t /*current*/, uint64_t /*total*/) {
  8115. progress_called = true;
  8116. return true;
  8117. });
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("content", received_body);
  8121. EXPECT_TRUE(progress_called);
  8122. }
  8123. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  8124. #ifdef CPPHTTPLIB_SSL_ENABLED
  8125. using ClientT = SSLClient;
  8126. #else
  8127. using ClientT = Client;
  8128. #endif
  8129. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8130. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8131. const std::string &body, const std::string &content_type,
  8132. ContentReceiver receiver, DownloadProgress progress) {
  8133. return cli.Post(path, headers, body, content_type, receiver, progress);
  8134. });
  8135. }
  8136. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  8137. #ifdef CPPHTTPLIB_SSL_ENABLED
  8138. using ClientT = SSLClient;
  8139. #else
  8140. using ClientT = Client;
  8141. #endif
  8142. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8143. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8144. const std::string &body, const std::string &content_type,
  8145. ContentReceiver receiver, DownloadProgress progress) {
  8146. return cli.Put(path, headers, body, content_type, receiver, progress);
  8147. });
  8148. }
  8149. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  8150. #ifdef CPPHTTPLIB_SSL_ENABLED
  8151. using ClientT = SSLClient;
  8152. #else
  8153. using ClientT = Client;
  8154. #endif
  8155. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  8156. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8157. const std::string &body, const std::string &content_type,
  8158. ContentReceiver receiver, DownloadProgress progress) {
  8159. return cli.Patch(path, headers, body, content_type, receiver, progress);
  8160. });
  8161. }
  8162. template <typename ClientType>
  8163. void TestWithHeadersAndContentReceiverError(
  8164. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  8165. const Headers &, const std::string &,
  8166. const std::string &, ContentReceiver)>
  8167. request_func) {
  8168. Headers headers;
  8169. headers.emplace("X-Error-Test", "true");
  8170. std::string received_body;
  8171. auto receiver_failed = false;
  8172. auto res =
  8173. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  8174. [&](const char *data, size_t data_length) {
  8175. received_body.append(data, data_length);
  8176. receiver_failed = true;
  8177. return false;
  8178. });
  8179. ASSERT_FALSE(res);
  8180. EXPECT_TRUE(receiver_failed);
  8181. }
  8182. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  8183. #ifdef CPPHTTPLIB_SSL_ENABLED
  8184. using ClientT = SSLClient;
  8185. #else
  8186. using ClientT = Client;
  8187. #endif
  8188. TestWithHeadersAndContentReceiverError<ClientT>(
  8189. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8190. const std::string &body, const std::string &content_type,
  8191. ContentReceiver receiver) {
  8192. return cli.Post(path, headers, body, content_type, receiver);
  8193. });
  8194. }
  8195. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  8196. #ifdef CPPHTTPLIB_SSL_ENABLED
  8197. using ClientT = SSLClient;
  8198. #else
  8199. using ClientT = Client;
  8200. #endif
  8201. TestWithHeadersAndContentReceiverError<ClientT>(
  8202. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8203. const std::string &body, const std::string &content_type,
  8204. ContentReceiver receiver) {
  8205. return cli.Put(path, headers, body, content_type, receiver);
  8206. });
  8207. }
  8208. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  8209. #ifdef CPPHTTPLIB_SSL_ENABLED
  8210. using ClientT = SSLClient;
  8211. #else
  8212. using ClientT = Client;
  8213. #endif
  8214. TestWithHeadersAndContentReceiverError<ClientT>(
  8215. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  8216. const std::string &body, const std::string &content_type,
  8217. ContentReceiver receiver) {
  8218. return cli.Patch(path, headers, body, content_type, receiver);
  8219. });
  8220. }
  8221. TEST_F(ServerTest, PostQueryStringAndBody) {
  8222. auto res =
  8223. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  8224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8225. ASSERT_EQ(StatusCode::OK_200, res->status);
  8226. }
  8227. TEST_F(ServerTest, HTTP2Magic) {
  8228. Request req;
  8229. req.method = "PRI";
  8230. req.path = "*";
  8231. req.body = "SM";
  8232. auto res = std::make_shared<Response>();
  8233. auto error = Error::Success;
  8234. auto ret = cli_.send(req, *res, error);
  8235. ASSERT_TRUE(ret);
  8236. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8237. }
  8238. TEST_F(ServerTest, KeepAlive) {
  8239. auto res = cli_.Get("/hi");
  8240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8241. EXPECT_EQ(StatusCode::OK_200, res->status);
  8242. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8243. EXPECT_EQ("Hello World!", res->body);
  8244. res = cli_.Get("/hi");
  8245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8246. EXPECT_EQ(StatusCode::OK_200, res->status);
  8247. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8248. EXPECT_EQ("Hello World!", res->body);
  8249. res = cli_.Get("/hi");
  8250. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8251. EXPECT_EQ(StatusCode::OK_200, res->status);
  8252. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8253. EXPECT_EQ("Hello World!", res->body);
  8254. res = cli_.Get("/not-exist");
  8255. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8256. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8257. res = cli_.Post("/empty", "", "text/plain");
  8258. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8259. EXPECT_EQ(StatusCode::OK_200, res->status);
  8260. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8261. EXPECT_EQ("empty", res->body);
  8262. EXPECT_EQ("close", res->get_header_value("Connection"));
  8263. res = cli_.Post(
  8264. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  8265. "text/plain");
  8266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8267. EXPECT_EQ(StatusCode::OK_200, res->status);
  8268. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8269. EXPECT_EQ("empty", res->body);
  8270. cli_.set_keep_alive(false);
  8271. res = cli_.Get("/last-request");
  8272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8273. EXPECT_EQ(StatusCode::OK_200, res->status);
  8274. EXPECT_EQ("close", res->get_header_value("Connection"));
  8275. }
  8276. TEST_F(ServerTest, TooManyRedirect) {
  8277. cli_.set_follow_location(true);
  8278. auto res = cli_.Get("/redirect/0");
  8279. ASSERT_TRUE(!res);
  8280. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  8281. }
  8282. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  8283. Request req;
  8284. req.method = "FOOBAR";
  8285. req.path = "/hi";
  8286. cli_.set_keep_alive(true);
  8287. auto res = cli_.send(req);
  8288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8289. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8290. EXPECT_EQ("close", res->get_header_value("Connection"));
  8291. EXPECT_FALSE(cli_.is_socket_open());
  8292. }
  8293. TEST_F(ServerTest, CustomRouteReadsBody) {
  8294. const std::string xml =
  8295. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  8296. Request req;
  8297. req.method = "PROPFIND";
  8298. req.path = "/dav/dir";
  8299. req.set_header("Depth", "1");
  8300. req.body = xml;
  8301. auto res = cli_.send(req);
  8302. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8303. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8304. EXPECT_EQ(xml, res->body);
  8305. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  8306. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  8307. }
  8308. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  8309. Request req;
  8310. req.method = "PROPFIND";
  8311. req.path = "/dav/42";
  8312. auto res = cli_.send(req);
  8313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8314. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8315. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  8316. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  8317. }
  8318. TEST_F(ServerTest, CustomRouteRegexPattern) {
  8319. Request req;
  8320. req.method = "PROPFIND";
  8321. req.path = "/dav-re/123";
  8322. auto res = cli_.send(req);
  8323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8324. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8325. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  8326. }
  8327. TEST_F(ServerTest, CustomRouteWithoutBody) {
  8328. Request req;
  8329. req.method = "MKCOL";
  8330. req.path = "/dav-mkcol";
  8331. auto res = cli_.send(req);
  8332. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8333. EXPECT_EQ(StatusCode::Created_201, res->status);
  8334. }
  8335. TEST_F(ServerTest, CustomRouteWithContentReader) {
  8336. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  8337. Request req;
  8338. req.method = "REPORT";
  8339. req.path = "/dav-report";
  8340. req.body = xml;
  8341. auto res = cli_.send(req);
  8342. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8343. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8344. EXPECT_EQ(xml, res->body);
  8345. }
  8346. // A content reader route must fire even when the request carries no body,
  8347. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  8348. // Without that, a body-less PROPFIND-style request would fall through to 404.
  8349. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  8350. Request req;
  8351. req.method = "REPORT";
  8352. req.path = "/dav-report";
  8353. auto res = cli_.send(req);
  8354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8355. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8356. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  8357. }
  8358. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  8359. Request req;
  8360. req.method = "PROPFIND";
  8361. req.path = "/not-dav";
  8362. auto res = cli_.send(req);
  8363. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8364. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8365. }
  8366. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  8367. Request req;
  8368. req.method = "UNLOCK";
  8369. req.path = "/dav/dir";
  8370. cli_.set_keep_alive(true);
  8371. auto res = cli_.send(req);
  8372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8373. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  8374. EXPECT_EQ("close", res->get_header_value("Connection"));
  8375. EXPECT_FALSE(cli_.is_socket_open());
  8376. }
  8377. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  8378. // The mount point serves this path, but only for GET and HEAD.
  8379. auto get_res = cli_.Get("/dir/index.html");
  8380. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  8381. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  8382. Request req;
  8383. req.method = "PROPFIND";
  8384. req.path = "/dir/index.html";
  8385. auto res = cli_.send(req);
  8386. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8387. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  8388. }
  8389. TEST_F(ServerTest, CustomRouteKeepAlive) {
  8390. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8391. cli_.set_keep_alive(true);
  8392. for (auto i = 0; i < 2; i++) {
  8393. Request req;
  8394. req.method = "PROPFIND";
  8395. req.path = "/dav/dir";
  8396. req.body = xml;
  8397. auto res = cli_.send(req);
  8398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8399. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8400. EXPECT_EQ(xml, res->body);
  8401. EXPECT_TRUE(cli_.is_socket_open());
  8402. }
  8403. // A built-in method must still be served on the same connection.
  8404. cli_.set_keep_alive(false);
  8405. auto res = cli_.Get("/hi");
  8406. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8407. EXPECT_EQ(StatusCode::OK_200, res->status);
  8408. EXPECT_EQ("close", res->get_header_value("Connection"));
  8409. }
  8410. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  8411. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  8412. Request req;
  8413. req.method = "PROPFIND";
  8414. req.path = "/dav/dir";
  8415. req.set_header("Expect", "100-continue");
  8416. req.body = xml;
  8417. auto res = cli_.send(req);
  8418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8419. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  8420. EXPECT_EQ(xml, res->body);
  8421. }
  8422. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  8423. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8424. TEST_F(ServerTest, Gzip) {
  8425. Headers headers;
  8426. headers.emplace("Accept-Encoding", "gzip, deflate");
  8427. auto res = cli_.Get("/compress", headers);
  8428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8429. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8430. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8431. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8432. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8433. "7890123456789012345678901234567890",
  8434. res->body);
  8435. EXPECT_EQ(StatusCode::OK_200, res->status);
  8436. }
  8437. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  8438. Headers headers;
  8439. headers.emplace("Accept-Encoding", "gzip, deflate");
  8440. auto res = cli_.Get("/compress-with-charset", headers);
  8441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8442. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8443. EXPECT_EQ("application/json; charset=utf-8",
  8444. res->get_header_value("Content-Type"));
  8445. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8446. "7890123456789012345678901234567890",
  8447. res->body);
  8448. EXPECT_EQ(StatusCode::OK_200, res->status);
  8449. }
  8450. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  8451. Headers headers;
  8452. headers.emplace("Accept-Encoding", "");
  8453. auto res = cli_.Get("/compress", headers);
  8454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8455. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8456. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8457. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8458. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8459. "7890123456789012345678901234567890",
  8460. res->body);
  8461. EXPECT_EQ(StatusCode::OK_200, res->status);
  8462. }
  8463. TEST_F(ServerTest, GzipWithContentReceiver) {
  8464. Headers headers;
  8465. headers.emplace("Accept-Encoding", "gzip, deflate");
  8466. std::string body;
  8467. auto res =
  8468. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8469. EXPECT_EQ(100U, data_length);
  8470. body.append(data, data_length);
  8471. return true;
  8472. });
  8473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8474. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8475. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8476. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8477. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8478. "7890123456789012345678901234567890",
  8479. body);
  8480. EXPECT_EQ(StatusCode::OK_200, res->status);
  8481. }
  8482. TEST_F(ServerTest, GzipWithoutDecompressing) {
  8483. Headers headers;
  8484. headers.emplace("Accept-Encoding", "gzip, deflate");
  8485. cli_.set_decompress(false);
  8486. auto res = cli_.Get("/compress", headers);
  8487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8488. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8489. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8490. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  8491. EXPECT_EQ(33U, res->body.size());
  8492. EXPECT_EQ(StatusCode::OK_200, res->status);
  8493. }
  8494. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  8495. Headers headers;
  8496. headers.emplace("Accept-Encoding", "");
  8497. std::string body;
  8498. auto res =
  8499. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8500. EXPECT_EQ(100U, data_length);
  8501. body.append(data, data_length);
  8502. return true;
  8503. });
  8504. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8505. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8506. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8507. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8508. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8509. "7890123456789012345678901234567890",
  8510. body);
  8511. EXPECT_EQ(StatusCode::OK_200, res->status);
  8512. }
  8513. TEST_F(ServerTest, NoGzip) {
  8514. Headers headers;
  8515. headers.emplace("Accept-Encoding", "gzip, deflate");
  8516. auto res = cli_.Get("/nocompress", headers);
  8517. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8518. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8519. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8520. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8521. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8522. "7890123456789012345678901234567890",
  8523. res->body);
  8524. EXPECT_EQ(StatusCode::OK_200, res->status);
  8525. }
  8526. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  8527. Headers headers;
  8528. headers.emplace("Accept-Encoding", "gzip, deflate");
  8529. std::string body;
  8530. auto res = cli_.Get("/nocompress", headers,
  8531. [&](const char *data, size_t data_length) {
  8532. EXPECT_EQ(100U, data_length);
  8533. body.append(data, data_length);
  8534. return true;
  8535. });
  8536. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8537. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8538. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8539. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8540. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8541. "7890123456789012345678901234567890",
  8542. body);
  8543. EXPECT_EQ(StatusCode::OK_200, res->status);
  8544. }
  8545. TEST_F(ServerTest, MultipartFormDataGzip) {
  8546. UploadFormDataItems items = {
  8547. {"key1", "test", "", ""},
  8548. {"key2", "--abcdefg123", "", ""},
  8549. };
  8550. cli_.set_compress(true);
  8551. auto res = cli_.Post("/compress-multipart", items);
  8552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8553. EXPECT_EQ(StatusCode::OK_200, res->status);
  8554. }
  8555. #endif
  8556. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  8557. // Static file compression is opt-in, so these run their own server rather than
  8558. // flipping it on for the shared ServerTest fixture, which would silently
  8559. // rewrite what every other static file test is asserting.
  8560. class StaticFileCompressionTest : public ::testing::Test {
  8561. protected:
  8562. void TearDown() override {
  8563. if (t_.joinable()) {
  8564. svr_.stop();
  8565. t_.join();
  8566. }
  8567. }
  8568. int start(const std::function<void(Server &)> &configure = nullptr) {
  8569. // Serves the same tree as a directory of build-time compressed assets
  8570. // would be served: the mount point names the coding the files are already
  8571. // stored in. Registered before "/" so it is the one that matches.
  8572. svr_.set_mount_point("/pre-encoded", "./www",
  8573. {{"Content-Encoding", "gzip"}});
  8574. svr_.set_mount_point("/", "./www");
  8575. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  8576. res.set_file_content("./www/dir/index.html", "text/html");
  8577. });
  8578. svr_.Get("/pre-encoded-file-content",
  8579. [](const Request & /*req*/, Response &res) {
  8580. res.set_header("Content-Encoding", "gzip");
  8581. res.set_file_content("./www/dir/index.html", "text/html");
  8582. });
  8583. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  8584. res.set_content_provider(
  8585. 6, "text/plain",
  8586. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8587. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  8588. return true;
  8589. });
  8590. });
  8591. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  8592. res.set_content_provider(
  8593. 1000, "text/plain",
  8594. [](size_t offset, size_t /*length*/, DataSink &sink) {
  8595. if (offset < 100) {
  8596. std::string data(100, 'A');
  8597. sink.write(data.data(), data.size());
  8598. return true;
  8599. }
  8600. std::this_thread::sleep_for(std::chrono::seconds(2));
  8601. std::string data(900, 'B');
  8602. sink.write(data.data(), data.size());
  8603. return true;
  8604. });
  8605. });
  8606. if (configure) { configure(svr_); }
  8607. auto port = svr_.bind_to_any_port(HOST);
  8608. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  8609. svr_.wait_until_ready();
  8610. return port;
  8611. }
  8612. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  8613. // Every file under ./www except 1MB.txt is smaller than the default
  8614. // 1400-byte floor, so a test that needs a small file compressed has to lower
  8615. // it out of the way.
  8616. static void enable_without_floor(Server &svr) {
  8617. svr.set_static_file_compression(true);
  8618. svr.set_static_file_compression_min_length(0);
  8619. }
  8620. Server svr_;
  8621. std::thread t_;
  8622. };
  8623. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  8624. auto port = start();
  8625. Client cli(HOST, port);
  8626. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8627. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8628. EXPECT_EQ(StatusCode::OK_200, res->status);
  8629. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8630. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8631. EXPECT_EQ(1048576U, res->body.size());
  8632. }
  8633. TEST_F(StaticFileCompressionTest, MountPoint) {
  8634. auto port = start(enable);
  8635. Client cli(HOST, port);
  8636. cli.set_decompress(false);
  8637. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8638. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8639. EXPECT_EQ(StatusCode::OK_200, res->status);
  8640. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8641. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8642. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  8643. // The response stays self-delimiting: a length, not a chunked body.
  8644. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8645. EXPECT_EQ(std::to_string(res->body.size()),
  8646. res->get_header_value("Content-Length"));
  8647. EXPECT_LT(res->body.size(), 1048576U);
  8648. EXPECT_FALSE(res->body.empty());
  8649. }
  8650. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  8651. auto port = start(enable);
  8652. Client cli(HOST, port);
  8653. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8655. EXPECT_EQ(StatusCode::OK_200, res->status);
  8656. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8657. EXPECT_EQ(1048576U, res->body.size());
  8658. }
  8659. TEST_F(StaticFileCompressionTest, FileContent) {
  8660. auto port = start(enable_without_floor);
  8661. Client cli(HOST, port);
  8662. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  8663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8664. EXPECT_EQ(StatusCode::OK_200, res->status);
  8665. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  8666. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8667. EXPECT_EQ(104U, res->body.size());
  8668. }
  8669. // A handler that serves an already-encoded file names the coding itself. The
  8670. // file-backed path decided its coding from Accept-Encoding and the content
  8671. // type alone, so it compressed the stored bytes a second time and appended a
  8672. // second Content-Encoding field line.
  8673. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  8674. auto port = start(enable_without_floor);
  8675. Client cli(HOST, port);
  8676. cli.set_decompress(false);
  8677. auto res = cli.Get("/pre-encoded-file-content",
  8678. Headers{{"Accept-Encoding", "gzip"}});
  8679. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8680. EXPECT_EQ(StatusCode::OK_200, res->status);
  8681. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8682. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8683. // Vary belongs to a coding the server chose, and it chose none here.
  8684. EXPECT_FALSE(res->has_header("Vary"));
  8685. // The file travels exactly as it is stored on disk.
  8686. EXPECT_EQ(104U, res->body.size());
  8687. }
  8688. // The 1MB file clears the default floor, so this one runs the configuration a
  8689. // deployment would actually have.
  8690. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  8691. auto port = start(enable);
  8692. Client cli(HOST, port);
  8693. cli.set_decompress(false);
  8694. auto res =
  8695. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8696. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8697. EXPECT_EQ(StatusCode::OK_200, res->status);
  8698. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  8699. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8700. EXPECT_FALSE(res->has_header("Vary"));
  8701. EXPECT_EQ(1048576U, res->body.size());
  8702. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  8703. }
  8704. TEST_F(StaticFileCompressionTest, Head) {
  8705. auto port = start(enable);
  8706. Client cli(HOST, port);
  8707. cli.set_decompress(false);
  8708. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8709. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  8710. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8712. EXPECT_EQ(StatusCode::OK_200, res->status);
  8713. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8714. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  8715. // HEAD still reports the size a GET would return.
  8716. EXPECT_EQ(get->get_header_value("Content-Length"),
  8717. res->get_header_value("Content-Length"));
  8718. EXPECT_TRUE(res->body.empty());
  8719. }
  8720. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  8721. auto port = start(enable);
  8722. Client cli(HOST, port);
  8723. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  8724. {"Accept-Encoding", "gzip"}});
  8725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8726. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  8727. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8728. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  8729. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  8730. EXPECT_EQ("cd", res->body);
  8731. }
  8732. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  8733. auto port = start(enable);
  8734. Client cli(HOST, port);
  8735. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  8736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8737. EXPECT_EQ(StatusCode::OK_200, res->status);
  8738. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8739. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8740. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  8741. }
  8742. TEST_F(StaticFileCompressionTest, EmptyFile) {
  8743. auto port = start(enable);
  8744. Client cli(HOST, port);
  8745. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  8746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8747. EXPECT_EQ(StatusCode::OK_200, res->status);
  8748. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8749. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  8750. EXPECT_TRUE(res->body.empty());
  8751. }
  8752. TEST_F(StaticFileCompressionTest, MinLength) {
  8753. auto port = start(enable);
  8754. Client cli(HOST, port);
  8755. // 104 bytes, well under the default floor. Compressing it would add the
  8756. // gzip header and trailer to a body that already fits in one packet.
  8757. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8759. EXPECT_EQ(StatusCode::OK_200, res->status);
  8760. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8761. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  8762. }
  8763. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  8764. auto port = start([](Server &svr) {
  8765. svr.set_static_file_compression(true);
  8766. svr.set_static_file_compression_min_length(1);
  8767. });
  8768. Client cli(HOST, port);
  8769. cli.set_decompress(false);
  8770. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  8771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8772. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8773. // A 9-byte file comes back larger than it went in, because gzip's header and
  8774. // trailer outweigh anything deflate can save. That is the end of the range
  8775. // the floor exists to keep out.
  8776. EXPECT_GT(res->body.size(), 9U);
  8777. }
  8778. TEST_F(StaticFileCompressionTest, MaxLength) {
  8779. auto port = start([](Server &svr) {
  8780. svr.set_static_file_compression(true);
  8781. svr.set_static_file_compression_min_length(0);
  8782. svr.set_static_file_compression_max_length(1024);
  8783. });
  8784. Client cli(HOST, port);
  8785. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  8786. // defines `small` as a macro on Windows.
  8787. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  8788. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  8789. EXPECT_FALSE(over->has_header("Content-Encoding"));
  8790. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  8791. // Under it: compressed.
  8792. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8793. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  8794. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  8795. }
  8796. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  8797. auto port = start(enable_without_floor);
  8798. Client cli(HOST, port);
  8799. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  8800. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  8801. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  8802. auto identity_etag = identity->get_header_value("ETag");
  8803. ASSERT_FALSE(identity_etag.empty());
  8804. auto gzipped =
  8805. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  8806. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  8807. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  8808. auto gzip_etag = gzipped->get_header_value("ETag");
  8809. ASSERT_FALSE(gzip_etag.empty());
  8810. // Two representations, two validators.
  8811. EXPECT_NE(identity_etag, gzip_etag);
  8812. // Each one revalidates against the request that would produce it...
  8813. auto fresh =
  8814. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  8815. {"If-None-Match", gzip_etag}});
  8816. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  8817. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  8818. auto fresh_identity =
  8819. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  8820. {"If-None-Match", identity_etag}});
  8821. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  8822. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  8823. // ...and not against the other representation.
  8824. auto crossed =
  8825. cli.Get("/dir/index.html",
  8826. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  8827. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  8828. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  8829. }
  8830. // The opt-in covers responses the server reads off disk itself. A caller's own
  8831. // known-length provider keeps its Content-Length and, more importantly, keeps
  8832. // delivering incrementally: routing it through a compressor would hold every
  8833. // write back until zlib's window filled.
  8834. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  8835. auto port = start(enable);
  8836. Client cli(HOST, port);
  8837. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  8838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8839. EXPECT_EQ(StatusCode::OK_200, res->status);
  8840. EXPECT_FALSE(res->has_header("Content-Encoding"));
  8841. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  8842. EXPECT_EQ("aaabbb", res->body);
  8843. }
  8844. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  8845. auto port = start(enable);
  8846. Client cli(HOST, port);
  8847. cli.set_read_timeout(1, 0);
  8848. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  8849. Headers{{"Accept-Encoding", "gzip"}});
  8850. ASSERT_TRUE(handle.is_valid());
  8851. // The provider writes 100 bytes and then stalls for longer than the read
  8852. // timeout. Those first bytes have to arrive anyway: run the response through
  8853. // a compressor and zlib holds them until its window fills, so the read would
  8854. // come back empty instead.
  8855. char buf[256];
  8856. auto n = handle.read(buf, sizeof(buf));
  8857. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  8858. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  8859. }
  8860. #endif
  8861. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  8862. TEST_F(ServerTest, Brotli) {
  8863. Headers headers;
  8864. headers.emplace("Accept-Encoding", "br");
  8865. auto res = cli_.Get("/compress", headers);
  8866. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8867. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8868. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8869. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  8870. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8871. "7890123456789012345678901234567890",
  8872. res->body);
  8873. EXPECT_EQ(StatusCode::OK_200, res->status);
  8874. }
  8875. #endif
  8876. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  8877. TEST_F(ServerTest, Zstd) {
  8878. Headers headers;
  8879. headers.emplace("Accept-Encoding", "zstd");
  8880. auto res = cli_.Get("/compress", headers);
  8881. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8882. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8883. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8884. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8885. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8886. "7890123456789012345678901234567890",
  8887. res->body);
  8888. EXPECT_EQ(StatusCode::OK_200, res->status);
  8889. }
  8890. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  8891. Headers headers;
  8892. headers.emplace("Accept-Encoding", "");
  8893. auto res = cli_.Get("/compress", headers);
  8894. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8895. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8896. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8897. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8898. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8899. "7890123456789012345678901234567890",
  8900. res->body);
  8901. EXPECT_EQ(StatusCode::OK_200, res->status);
  8902. }
  8903. TEST_F(ServerTest, ZstdWithContentReceiver) {
  8904. Headers headers;
  8905. headers.emplace("Accept-Encoding", "zstd");
  8906. std::string body;
  8907. auto res =
  8908. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8909. EXPECT_EQ(100U, data_length);
  8910. body.append(data, data_length);
  8911. return true;
  8912. });
  8913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8914. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8915. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8916. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8917. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8918. "7890123456789012345678901234567890",
  8919. body);
  8920. EXPECT_EQ(StatusCode::OK_200, res->status);
  8921. }
  8922. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  8923. Headers headers;
  8924. headers.emplace("Accept-Encoding", "zstd");
  8925. cli_.set_decompress(false);
  8926. auto res = cli_.Get("/compress", headers);
  8927. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  8928. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  8929. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  8930. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  8931. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8932. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  8933. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8934. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  8935. EXPECT_EQ(StatusCode::OK_200, res->status);
  8936. ASSERT_EQ(26U, res->body.size());
  8937. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  8938. 0);
  8939. }
  8940. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  8941. Headers headers;
  8942. headers.emplace("Accept-Encoding", "");
  8943. std::string body;
  8944. auto res =
  8945. cli_.Get("/compress", headers, [&](const char *data, size_t data_length) {
  8946. EXPECT_EQ(100U, data_length);
  8947. body.append(data, data_length);
  8948. return true;
  8949. });
  8950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8951. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8952. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  8953. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8954. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8955. "7890123456789012345678901234567890",
  8956. body);
  8957. EXPECT_EQ(StatusCode::OK_200, res->status);
  8958. }
  8959. TEST_F(ServerTest, NoZstd) {
  8960. Headers headers;
  8961. headers.emplace("Accept-Encoding", "zstd");
  8962. auto res = cli_.Get("/nocompress", headers);
  8963. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8964. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8965. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8966. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8967. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8968. "7890123456789012345678901234567890",
  8969. res->body);
  8970. EXPECT_EQ(StatusCode::OK_200, res->status);
  8971. }
  8972. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8973. Headers headers;
  8974. headers.emplace("Accept-Encoding", "zstd");
  8975. std::string body;
  8976. auto res = cli_.Get("/nocompress", headers,
  8977. [&](const char *data, size_t data_length) {
  8978. EXPECT_EQ(100U, data_length);
  8979. body.append(data, data_length);
  8980. return true;
  8981. });
  8982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8983. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8984. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8985. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8986. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8987. "7890123456789012345678901234567890",
  8988. body);
  8989. EXPECT_EQ(StatusCode::OK_200, res->status);
  8990. }
  8991. // TODO: How to enable zstd ??
  8992. TEST_F(ServerTest, MultipartFormDataZstd) {
  8993. UploadFormDataItems items = {
  8994. {"key1", "test", "", ""},
  8995. {"key2", "--abcdefg123", "", ""},
  8996. };
  8997. Headers headers;
  8998. headers.emplace("Accept-Encoding", "zstd");
  8999. cli_.set_compress(true);
  9000. auto res = cli_.Post("/compress-multipart", headers, items);
  9001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9002. EXPECT_EQ(StatusCode::OK_200, res->status);
  9003. }
  9004. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  9005. Headers headers;
  9006. headers.emplace("Accept-Encoding", "zstd");
  9007. cli_.set_compress(true);
  9008. auto res = cli_.Put(
  9009. "/put", headers, 3,
  9010. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9011. sink.os << "PUT";
  9012. return true;
  9013. },
  9014. "text/plain");
  9015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9016. EXPECT_EQ(StatusCode::OK_200, res->status);
  9017. EXPECT_EQ("PUT", res->body);
  9018. }
  9019. // Pre-compression logging tests
  9020. TEST_F(ServerTest, PreCompressionLogging) {
  9021. // Test data for compression (matches the actual /compress endpoint content)
  9022. const std::string test_content =
  9023. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9024. "3456789012345678901234567890";
  9025. // Variables to capture logging data
  9026. std::string pre_compression_body;
  9027. std::string pre_compression_content_type;
  9028. std::string pre_compression_content_encoding;
  9029. std::string post_compression_body;
  9030. std::string post_compression_content_type;
  9031. std::string post_compression_content_encoding;
  9032. // Set up pre-compression logger
  9033. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  9034. const Response &res) {
  9035. pre_compression_body = res.body;
  9036. pre_compression_content_type = res.get_header_value("Content-Type");
  9037. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  9038. });
  9039. // Set up post-compression logger
  9040. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9041. post_compression_body = res.body;
  9042. post_compression_content_type = res.get_header_value("Content-Type");
  9043. post_compression_content_encoding =
  9044. res.get_header_value("Content-Encoding");
  9045. });
  9046. // Test with gzip compression
  9047. Headers headers;
  9048. headers.emplace("Accept-Encoding", "gzip");
  9049. auto res = cli_.Get("/compress", headers);
  9050. // Verify response was compressed
  9051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9052. EXPECT_EQ(StatusCode::OK_200, res->status);
  9053. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9054. // Verify pre-compression logger captured uncompressed content
  9055. EXPECT_EQ(test_content, pre_compression_body);
  9056. EXPECT_EQ("text/plain", pre_compression_content_type);
  9057. EXPECT_TRUE(pre_compression_content_encoding
  9058. .empty()); // No encoding header before compression
  9059. // Verify post-compression logger captured compressed content
  9060. EXPECT_NE(test_content,
  9061. post_compression_body); // Should be different after compression
  9062. EXPECT_EQ("text/plain", post_compression_content_type);
  9063. EXPECT_EQ("gzip", post_compression_content_encoding);
  9064. // Verify compressed content is smaller
  9065. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9066. }
  9067. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  9068. const std::string test_content =
  9069. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9070. "3456789012345678901234567890";
  9071. std::string pre_compression_body;
  9072. std::string post_compression_body;
  9073. svr_.set_pre_compression_logger(
  9074. [&](const Request & /*req*/, const Response &res) {
  9075. pre_compression_body = res.body;
  9076. });
  9077. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9078. post_compression_body = res.body;
  9079. });
  9080. Headers headers;
  9081. headers.emplace("Accept-Encoding", "br");
  9082. auto res = cli_.Get("/compress", headers);
  9083. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9084. EXPECT_EQ(StatusCode::OK_200, res->status);
  9085. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  9086. // Verify pre-compression content is uncompressed
  9087. EXPECT_EQ(test_content, pre_compression_body);
  9088. // Verify post-compression content is compressed
  9089. EXPECT_NE(test_content, post_compression_body);
  9090. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  9091. }
  9092. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  9093. const std::string test_content =
  9094. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9095. "3456789012345678901234567890";
  9096. std::string pre_compression_body;
  9097. std::string post_compression_body;
  9098. svr_.set_pre_compression_logger(
  9099. [&](const Request & /*req*/, const Response &res) {
  9100. pre_compression_body = res.body;
  9101. });
  9102. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9103. post_compression_body = res.body;
  9104. });
  9105. // Request without compression (use /nocompress endpoint)
  9106. Headers headers;
  9107. auto res = cli_.Get("/nocompress", headers);
  9108. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9109. EXPECT_EQ(StatusCode::OK_200, res->status);
  9110. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  9111. // Pre-compression logger should not be called when no compression is applied
  9112. EXPECT_TRUE(
  9113. pre_compression_body.empty()); // Pre-compression logger not called
  9114. EXPECT_EQ(
  9115. test_content,
  9116. post_compression_body); // Post-compression logger captures final content
  9117. }
  9118. TEST_F(ServerTest, LoggerSeesContentLength) {
  9119. size_t logged_content_length = 0;
  9120. std::string logged_content_length_header;
  9121. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  9122. logged_content_length = res.content_length_;
  9123. logged_content_length_header = res.get_header_value("Content-Length");
  9124. });
  9125. auto res = cli_.Get("/nocompress");
  9126. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9127. EXPECT_EQ(StatusCode::OK_200, res->status);
  9128. EXPECT_EQ(res->body.size(), logged_content_length);
  9129. EXPECT_EQ(std::to_string(logged_content_length),
  9130. logged_content_length_header);
  9131. }
  9132. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  9133. const std::string test_content =
  9134. "123456789012345678901234567890123456789012345678901234567890123456789012"
  9135. "3456789012345678901234567890";
  9136. std::string pre_compression_body;
  9137. bool pre_logger_called = false;
  9138. // Set only pre-compression logger
  9139. svr_.set_pre_compression_logger(
  9140. [&](const Request & /*req*/, const Response &res) {
  9141. pre_compression_body = res.body;
  9142. pre_logger_called = true;
  9143. });
  9144. Headers headers;
  9145. headers.emplace("Accept-Encoding", "gzip");
  9146. auto res = cli_.Get("/compress", headers);
  9147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9148. EXPECT_EQ(StatusCode::OK_200, res->status);
  9149. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  9150. // Verify pre-compression logger was called
  9151. EXPECT_TRUE(pre_logger_called);
  9152. EXPECT_EQ(test_content, pre_compression_body);
  9153. }
  9154. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  9155. {
  9156. // Test with Expect: 100-continue header - success case
  9157. // Server returns 100 Continue, client sends body, server returns 200 OK
  9158. Request req;
  9159. req.method = "POST";
  9160. req.path = "/post-large";
  9161. req.set_header("Expect", "100-continue");
  9162. req.body = LARGE_DATA;
  9163. Response res;
  9164. auto error = Error::Success;
  9165. cli_.set_keep_alive(true);
  9166. auto ret = cli_.send(req, res, error);
  9167. EXPECT_TRUE(ret);
  9168. EXPECT_EQ(StatusCode::OK_200, res.status);
  9169. EXPECT_EQ(LARGE_DATA, res.body);
  9170. }
  9171. {
  9172. // Test with Expect: 100-continue header - error case
  9173. // Client should not send the body when server returns an error
  9174. Request req;
  9175. req.method = "POST";
  9176. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  9177. req.set_header("Expect", "100-continue");
  9178. req.body = LARGE_DATA;
  9179. Response res;
  9180. auto error = Error::Success;
  9181. auto start = std::chrono::high_resolution_clock::now();
  9182. cli_.set_keep_alive(true);
  9183. auto ret = cli_.send(req, res, error);
  9184. auto end = std::chrono::high_resolution_clock::now();
  9185. auto elapsed =
  9186. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9187. .count();
  9188. // With Expect: 100-continue, request completes successfully but with error
  9189. EXPECT_TRUE(ret);
  9190. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  9191. EXPECT_EQ("close", res.get_header_value("Connection"));
  9192. EXPECT_FALSE(cli_.is_socket_open());
  9193. EXPECT_LE(elapsed, 2000);
  9194. }
  9195. {
  9196. // Send an extra GET request to ensure error recovery without hanging
  9197. Request req;
  9198. req.method = "GET";
  9199. req.path = "/hi";
  9200. auto start = std::chrono::high_resolution_clock::now();
  9201. auto res = cli_.send(req);
  9202. auto end = std::chrono::high_resolution_clock::now();
  9203. auto elapsed =
  9204. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  9205. .count();
  9206. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9207. EXPECT_EQ(StatusCode::OK_200, res->status);
  9208. EXPECT_EQ("Hello World!", res->body);
  9209. EXPECT_LE(elapsed, 500);
  9210. }
  9211. }
  9212. TEST(ZstdDecompressor, ChunkedDecompression) {
  9213. std::string data;
  9214. for (size_t i = 0; i < 32 * 1024; ++i) {
  9215. data.push_back(static_cast<char>('a' + i % 26));
  9216. }
  9217. std::string compressed_data;
  9218. {
  9219. httplib::detail::zstd_compressor compressor;
  9220. bool result = compressor.compress(
  9221. data.data(), data.size(),
  9222. /*last=*/true,
  9223. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  9224. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  9225. compressed_data_size);
  9226. return true;
  9227. });
  9228. ASSERT_TRUE(result);
  9229. }
  9230. std::string decompressed_data;
  9231. {
  9232. httplib::detail::zstd_decompressor decompressor;
  9233. // Chunk size is chosen specifically to have a decompressed chunk size equal
  9234. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  9235. size_t chunk_size = 130;
  9236. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  9237. chunk_begin += chunk_size) {
  9238. size_t current_chunk_size =
  9239. std::min(compressed_data.size() - chunk_begin, chunk_size);
  9240. bool result = decompressor.decompress(
  9241. compressed_data.data() + chunk_begin, current_chunk_size,
  9242. [&](const char *decompressed_data_chunk,
  9243. size_t decompressed_data_chunk_size) {
  9244. decompressed_data.insert(decompressed_data.size(),
  9245. decompressed_data_chunk,
  9246. decompressed_data_chunk_size);
  9247. return true;
  9248. });
  9249. ASSERT_TRUE(result);
  9250. }
  9251. }
  9252. ASSERT_EQ(data, decompressed_data);
  9253. }
  9254. TEST(ZstdDecompressor, Decompress) {
  9255. std::string original_text = "Compressed with ZSTD";
  9256. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  9257. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  9258. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  9259. 0x20, 0x5a, 0x53, 0x54, 0x44};
  9260. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  9261. std::string decompressed_data;
  9262. {
  9263. httplib::detail::zstd_decompressor decompressor;
  9264. bool result = decompressor.decompress(
  9265. compressed_data.data(), compressed_data.size(),
  9266. [&](const char *decompressed_data_chunk,
  9267. size_t decompressed_data_chunk_size) {
  9268. decompressed_data.insert(decompressed_data.size(),
  9269. decompressed_data_chunk,
  9270. decompressed_data_chunk_size);
  9271. return true;
  9272. });
  9273. ASSERT_TRUE(result);
  9274. }
  9275. ASSERT_EQ(original_text, decompressed_data);
  9276. }
  9277. #endif
  9278. // Sends a raw request to a server listening at HOST:PORT, writing it in
  9279. // separate chunks so that the server sees each part in its own read(). Used to
  9280. // place a read boundary at a specific offset of a request body.
  9281. static bool send_request_in_parts(time_t read_timeout_sec,
  9282. const std::vector<std::string> &parts,
  9283. std::string *resp = nullptr,
  9284. int port = PORT) {
  9285. auto error = Error::Success;
  9286. auto client_sock = detail::create_client_socket(
  9287. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9288. /*connection_timeout_sec=*/5, 0,
  9289. /*read_timeout_sec=*/5, 0,
  9290. /*write_timeout_sec=*/5, 0, std::string(), error);
  9291. if (client_sock == INVALID_SOCKET) { return false; }
  9292. auto ret = detail::process_client_socket(
  9293. client_sock, read_timeout_sec, 0, 0, 0, 0,
  9294. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  9295. for (size_t i = 0; i < parts.size(); i++) {
  9296. const auto &part = parts[i];
  9297. if (part.size() !=
  9298. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  9299. return false;
  9300. }
  9301. if (i + 1 < parts.size()) {
  9302. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9303. }
  9304. }
  9305. char buf[512];
  9306. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  9307. while (line_reader.getline()) {
  9308. if (resp) { *resp += line_reader.ptr(); }
  9309. }
  9310. return true;
  9311. });
  9312. detail::close_socket(client_sock);
  9313. return ret;
  9314. }
  9315. // Sends a raw request to a server listening at HOST:PORT.
  9316. static bool send_request(time_t read_timeout_sec, const std::string &req,
  9317. std::string *resp = nullptr, int port = PORT) {
  9318. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  9319. }
  9320. #ifdef CPPHTTPLIB_SSL_ENABLED
  9321. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeHandshake) {
  9322. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9323. ASSERT_TRUE(svr.is_valid());
  9324. svr.set_read_timeout(1, 0);
  9325. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9326. auto se = detail::scope_exit([&] {
  9327. svr.stop();
  9328. t.join();
  9329. ASSERT_FALSE(svr.is_running());
  9330. });
  9331. svr.wait_until_ready();
  9332. // The start of a TLS record, then the rest of it a byte every 100 ms, which
  9333. // keeps each wait well within the read timeout. The server gives up a
  9334. // second in, so the bytes sent after that fail.
  9335. std::vector<std::string> parts{std::string("\x16\x03\x01\x00\xff", 5)};
  9336. parts.resize(26, std::string(1, '\0'));
  9337. EXPECT_FALSE(send_request_in_parts(5, parts));
  9338. }
  9339. #endif
  9340. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9341. // send_request_in_parts() over TLS, each part in a TLS record of its own.
  9342. static bool send_ssl_request_in_parts(time_t read_timeout_sec,
  9343. const std::vector<std::string> &parts,
  9344. std::string *resp = nullptr,
  9345. int port = PORT) {
  9346. auto error = Error::Success;
  9347. auto sock = detail::create_client_socket(
  9348. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  9349. /*connection_timeout_sec=*/5, 0, read_timeout_sec, 0,
  9350. /*write_timeout_sec=*/5, 0, std::string(), error);
  9351. if (sock == INVALID_SOCKET) { return false; }
  9352. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  9353. auto ctx = SSL_CTX_new(TLS_client_method());
  9354. auto ssl = SSL_new(ctx);
  9355. auto ssl_se = detail::scope_exit([&] {
  9356. SSL_free(ssl);
  9357. SSL_CTX_free(ctx);
  9358. });
  9359. SSL_set_fd(ssl, static_cast<int>(sock));
  9360. if (SSL_connect(ssl) != 1) { return false; }
  9361. for (size_t i = 0; i < parts.size(); i++) {
  9362. const auto &part = parts[i];
  9363. if (SSL_write(ssl, part.data(), static_cast<int>(part.size())) !=
  9364. static_cast<int>(part.size())) {
  9365. return false;
  9366. }
  9367. if (i + 1 < parts.size()) {
  9368. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9369. }
  9370. }
  9371. char buf[512];
  9372. int n;
  9373. while ((n = SSL_read(ssl, buf, sizeof(buf))) > 0) {
  9374. if (resp) { resp->append(buf, static_cast<size_t>(n)); }
  9375. }
  9376. return true;
  9377. }
  9378. #endif
  9379. // The request line, then a header value a byte at a time.
  9380. static std::vector<std::string> slow_request_head_parts() {
  9381. std::vector<std::string> parts{"GET / HTTP/1.1\r\nHost: x\r\nX-Slow: "};
  9382. parts.resize(26, "a");
  9383. parts.emplace_back("\r\n\r\n");
  9384. return parts;
  9385. }
  9386. // `send` takes 2.5 seconds over slow_request_head_parts(), each wait well
  9387. // within the one-second read timeout. The server gives up a second in, before
  9388. // the head is complete.
  9389. static void
  9390. expect_slow_request_head_dropped(Server &svr,
  9391. const std::function<std::string()> &send) {
  9392. std::atomic<bool> handled(false);
  9393. svr.Get("/", [&](const Request &, Response &res) {
  9394. handled = true;
  9395. res.set_content("ok", "text/plain");
  9396. });
  9397. svr.set_read_timeout(1, 0);
  9398. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  9399. auto se = detail::scope_exit([&] {
  9400. svr.stop();
  9401. t.join();
  9402. ASSERT_FALSE(svr.is_running());
  9403. });
  9404. svr.wait_until_ready();
  9405. auto resp = send();
  9406. EXPECT_FALSE(handled);
  9407. EXPECT_EQ(std::string::npos, resp.find("200 OK"));
  9408. }
  9409. TEST(ServerRequestParsingTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9410. Server svr;
  9411. expect_slow_request_head_dropped(svr, [] {
  9412. std::string resp;
  9413. send_request_in_parts(5, slow_request_head_parts(), &resp);
  9414. return resp;
  9415. });
  9416. }
  9417. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  9418. TEST(SSLClientServerTest, ReadTimeoutBoundsTheWholeRequestHead) {
  9419. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9420. ASSERT_TRUE(svr.is_valid());
  9421. expect_slow_request_head_dropped(svr, [] {
  9422. std::string resp;
  9423. send_ssl_request_in_parts(5, slow_request_head_parts(), &resp);
  9424. return resp;
  9425. });
  9426. }
  9427. #endif
  9428. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  9429. Server svr;
  9430. std::string header_value;
  9431. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  9432. header_value = req.get_header_value("foo");
  9433. res.set_content("ok", "text/plain");
  9434. });
  9435. thread t = thread([&] { svr.listen(HOST, PORT); });
  9436. auto se = detail::scope_exit([&] {
  9437. svr.stop();
  9438. t.join();
  9439. ASSERT_FALSE(svr.is_running());
  9440. });
  9441. svr.wait_until_ready();
  9442. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  9443. // like characters are not treated the same - use vertical tab and escape.
  9444. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  9445. "foo: \t \v bar \x1B\t \r\n"
  9446. "Connection: close\r\n"
  9447. "\r\n";
  9448. std::string res;
  9449. ASSERT_TRUE(send_request(5, req, &res));
  9450. EXPECT_EQ(header_value, "");
  9451. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  9452. }
  9453. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  9454. Server svr;
  9455. std::string received;
  9456. svr.Get("/order", [&](const Request &req, Response &res) {
  9457. received = entries_to_string(req.headers);
  9458. res.set_content("ok", "text/plain");
  9459. });
  9460. auto port = svr.bind_to_any_port(HOST);
  9461. thread t = thread([&] { svr.listen_after_bind(); });
  9462. auto se = detail::scope_exit([&] {
  9463. svr.stop();
  9464. t.join();
  9465. ASSERT_FALSE(svr.is_running());
  9466. });
  9467. svr.wait_until_ready();
  9468. const std::string req = "GET /order HTTP/1.1\r\n"
  9469. "Host: localhost\r\n"
  9470. "X-First: 1\r\n"
  9471. "X-Dup: a\r\n"
  9472. "X-Second: 2\r\n"
  9473. "X-Dup: b\r\n"
  9474. "Connection: close\r\n"
  9475. "\r\n";
  9476. std::string res;
  9477. ASSERT_TRUE(send_request(5, req, &res, port));
  9478. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9479. EXPECT_EQ(
  9480. "Host=localhost X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ",
  9481. received);
  9482. }
  9483. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  9484. Server svr;
  9485. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  9486. res.set_header("Set-Cookie", "first=1");
  9487. res.set_header("X-Between", "y");
  9488. res.set_header("Set-Cookie", "second=2");
  9489. res.set_content("ok", "text/plain");
  9490. });
  9491. auto port = svr.bind_to_any_port(HOST);
  9492. thread t = thread([&] { svr.listen_after_bind(); });
  9493. auto se = detail::scope_exit([&] {
  9494. svr.stop();
  9495. t.join();
  9496. ASSERT_FALSE(svr.is_running());
  9497. });
  9498. svr.wait_until_ready();
  9499. Client cli(HOST, port);
  9500. auto res = cli.Get("/cookies");
  9501. ASSERT_TRUE(res);
  9502. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  9503. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  9504. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  9505. }
  9506. // A stream may send a byte at a time with a small extension on each chunk,
  9507. // however long it runs
  9508. TEST(ChunkOverheadTest, AcceptsSmallOverheadOnEveryChunk) {
  9509. Server svr;
  9510. svr.Post("/count", [](const Request &req, Response &res) {
  9511. res.set_content(std::to_string(req.body.size()), "text/plain");
  9512. });
  9513. auto port = svr.bind_to_any_port(HOST);
  9514. ASSERT_LT(0, port);
  9515. thread t = thread([&] { svr.listen_after_bind(); });
  9516. auto se = detail::scope_exit([&] {
  9517. svr.stop();
  9518. t.join();
  9519. ASSERT_FALSE(svr.is_running());
  9520. });
  9521. svr.wait_until_ready();
  9522. std::string req = std::string("POST /count HTTP/1.1\r\nHost: ") + HOST +
  9523. "\r\nTransfer-Encoding: chunked\r\n"
  9524. "Connection: close\r\n\r\n";
  9525. for (auto i = 0; i < 4096; i++) {
  9526. req += "1;a=b\r\nx\r\n";
  9527. }
  9528. req += "0\r\n\r\n";
  9529. std::string res;
  9530. ASSERT_TRUE(send_request(5, req, &res, port));
  9531. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n"));
  9532. EXPECT_EQ("4096", res.substr(res.size() - 4));
  9533. }
  9534. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  9535. Server svr;
  9536. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  9537. auto i = new int(0);
  9538. res.set_header("Trailer", "X-Safe, X-Reflected");
  9539. res.set_chunked_content_provider(
  9540. "text/plain",
  9541. [i](size_t /*offset*/, DataSink &sink) {
  9542. if (*i == 0) {
  9543. sink.os << "body";
  9544. } else {
  9545. Headers trailer;
  9546. // A valid trailer that must survive.
  9547. trailer.emplace("X-Safe", "safe");
  9548. // Attacker-controlled value carrying CR/LF (response splitting).
  9549. trailer.emplace("X-Reflected",
  9550. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9551. // Attacker-controlled name carrying CR/LF.
  9552. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9553. sink.done_with_trailer(trailer);
  9554. }
  9555. (*i)++;
  9556. return true;
  9557. },
  9558. [i](bool /*success*/) { delete i; });
  9559. });
  9560. thread t = thread([&] { svr.listen(HOST, PORT); });
  9561. auto se = detail::scope_exit([&] {
  9562. svr.stop();
  9563. t.join();
  9564. ASSERT_FALSE(svr.is_running());
  9565. });
  9566. svr.wait_until_ready();
  9567. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  9568. "Host: " + HOST +
  9569. "\r\n"
  9570. "Connection: close\r\n"
  9571. "\r\n";
  9572. std::string res;
  9573. ASSERT_TRUE(send_request(5, req, &res));
  9574. // The injected fields must not appear anywhere in the raw response.
  9575. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9576. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9577. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9578. // Invalid trailers are dropped entirely, matching set_header().
  9579. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9580. // The valid trailer still passes through.
  9581. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9582. }
  9583. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  9584. // A custom header writer gets only the fields the default one writes
  9585. auto verbatim_writer = [](Stream &strm, Headers &hdrs) -> ssize_t {
  9586. std::string s;
  9587. for (const auto &h : hdrs) {
  9588. s += h.first + ": " + h.second + "\r\n";
  9589. }
  9590. s += "\r\n";
  9591. return strm.write(s.data(), s.size());
  9592. };
  9593. for (auto custom_writer : {false, true}) {
  9594. SCOPED_TRACE(custom_writer ? "custom header writer" : "default writer");
  9595. Server svr;
  9596. if (custom_writer) { svr.set_header_writer(verbatim_writer); }
  9597. svr.set_post_routing_handler([](const Request &, Response &res) {
  9598. res.headers.emplace("X-Late", "late\r\nInjected-Late: pwned");
  9599. });
  9600. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  9601. // res.headers is a public field an application can populate directly,
  9602. // bypassing set_header()'s validation (e.g. reflecting a request value).
  9603. // A valid header that must survive.
  9604. res.headers.emplace("X-Safe", "safe");
  9605. // Attacker-controlled value carrying CR/LF (response splitting).
  9606. res.headers.emplace("X-Reflected",
  9607. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  9608. // Attacker-controlled name carrying CR/LF.
  9609. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  9610. res.set_content("body", "text/plain");
  9611. });
  9612. thread t = thread([&] { svr.listen(HOST, PORT); });
  9613. auto se = detail::scope_exit([&] {
  9614. svr.stop();
  9615. t.join();
  9616. ASSERT_FALSE(svr.is_running());
  9617. });
  9618. svr.wait_until_ready();
  9619. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  9620. "Host: " + HOST +
  9621. "\r\n"
  9622. "Connection: close\r\n"
  9623. "\r\n";
  9624. std::string res;
  9625. ASSERT_TRUE(send_request(5, req, &res));
  9626. // The injected fields must not appear anywhere in the raw response.
  9627. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  9628. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  9629. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  9630. EXPECT_EQ(std::string::npos, res.find("Injected-Late"));
  9631. // Invalid headers are dropped entirely, matching set_header().
  9632. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  9633. // The valid header still passes through.
  9634. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  9635. }
  9636. }
  9637. // Forward declaration: in split builds split.py strips `inline` and moves the
  9638. // definition into httplib.cc, so detail::write_request_line is not visible from
  9639. // the public httplib.h. Re-declaring it here lets the tests link against the
  9640. // symbol in both header-only and split builds.
  9641. namespace httplib {
  9642. namespace detail {
  9643. ssize_t write_request_line(Stream &strm, const std::string &method,
  9644. const std::string &path);
  9645. } // namespace detail
  9646. } // namespace httplib
  9647. TEST(RequestLineInjectionTest, RejectsInvalidCharsInTarget) {
  9648. // A well-formed target is written verbatim.
  9649. {
  9650. detail::BufferStream strm;
  9651. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  9652. EXPECT_GT(n, 0);
  9653. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  9654. }
  9655. // A target carrying CR/LF, SP or other control octets must be rejected
  9656. // before anything reaches the wire, otherwise it splits the request line and
  9657. // injects a header or a whole request.
  9658. const std::string evil_targets[] = {
  9659. "/a\r\nInjected: pwned",
  9660. "/a\rInjected",
  9661. "/a\nInjected",
  9662. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  9663. "/a b",
  9664. "/a\tb",
  9665. "/a\x7f",
  9666. };
  9667. for (const auto &evil : evil_targets) {
  9668. detail::BufferStream strm;
  9669. auto n = detail::write_request_line(strm, "GET", evil);
  9670. EXPECT_LT(n, 0);
  9671. EXPECT_TRUE(strm.get_buffer().empty());
  9672. }
  9673. }
  9674. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  9675. // End-to-end counterpart to RejectsInvalidCharsInTarget. With path encoding
  9676. // disabled the client transmits the target verbatim, so a CR/LF-bearing
  9677. // target reaches write_request. The client must fail cleanly with
  9678. // Error::Write instead of putting a request-line-less, header-injecting
  9679. // request on the wire.
  9680. Server svr;
  9681. svr.Get("/a", [](const Request &, Response &res) {
  9682. res.set_content("ok", "text/plain");
  9683. });
  9684. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. thread.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. });
  9690. svr.wait_until_ready();
  9691. {
  9692. Client cli(HOST, PORT);
  9693. cli.set_path_encode(false);
  9694. // The request is rejected before anything is written, so the connection
  9695. // stays silent and the subsequent response read would otherwise block for
  9696. // the full default read timeout. Shorten it -- the assertion is on the
  9697. // error, not the timeout.
  9698. cli.set_read_timeout(1, 0);
  9699. auto res = cli.Get("/a\r\nInjected: pwned");
  9700. EXPECT_FALSE(res);
  9701. EXPECT_EQ(Error::Write, res.error());
  9702. }
  9703. }
  9704. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  9705. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  9706. // including extension methods.
  9707. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  9708. for (const auto &method : good_methods) {
  9709. detail::BufferStream strm;
  9710. auto n = detail::write_request_line(strm, method, "/");
  9711. EXPECT_GT(n, 0);
  9712. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  9713. }
  9714. // A method carrying CR/LF would split the request line and smuggle a whole
  9715. // request ahead of the real one. A space or an empty method corrupts the
  9716. // request line. All must be rejected before anything reaches the wire.
  9717. const std::string evil_methods[] = {
  9718. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9719. "GET\r\nInjected: pwned",
  9720. "GET\r",
  9721. "GET\n",
  9722. "GE T",
  9723. "",
  9724. };
  9725. for (const auto &evil : evil_methods) {
  9726. detail::BufferStream strm;
  9727. auto n = detail::write_request_line(strm, evil, "/");
  9728. EXPECT_LT(n, 0);
  9729. EXPECT_TRUE(strm.get_buffer().empty());
  9730. }
  9731. }
  9732. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  9733. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  9734. // through Client::send must fail with Error::Write and no request, neither
  9735. // the smuggled one nor the real one, may reach the server.
  9736. Server svr;
  9737. std::atomic<int> request_count(0);
  9738. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  9739. request_count++;
  9740. res.status = StatusCode::OK_200;
  9741. return Server::HandlerResponse::Handled;
  9742. });
  9743. auto port = svr.bind_to_any_port(HOST);
  9744. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  9745. auto se = detail::scope_exit([&] {
  9746. svr.stop();
  9747. thread.join();
  9748. ASSERT_FALSE(svr.is_running());
  9749. });
  9750. svr.wait_until_ready();
  9751. {
  9752. Client cli(HOST, port);
  9753. const std::string evil_methods[] = {
  9754. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  9755. "GE T",
  9756. "",
  9757. };
  9758. for (const auto &evil : evil_methods) {
  9759. Request req;
  9760. req.method = evil;
  9761. req.path = "/";
  9762. auto res = cli.send(req);
  9763. EXPECT_FALSE(res);
  9764. EXPECT_EQ(Error::Write, res.error());
  9765. }
  9766. auto handle =
  9767. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  9768. EXPECT_FALSE(handle.is_valid());
  9769. EXPECT_EQ(Error::Write, handle.error);
  9770. // A valid request on the same client still goes through.
  9771. auto res = cli.Get("/");
  9772. ASSERT_TRUE(res);
  9773. EXPECT_EQ(StatusCode::OK_200, res->status);
  9774. }
  9775. EXPECT_EQ(1, request_count.load());
  9776. }
  9777. // Sends a raw request and verifies that there isn't a crash or exception.
  9778. static void test_raw_request(const std::string &req,
  9779. std::string *out = nullptr) {
  9780. Server svr;
  9781. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9782. res.set_content("ok", "text/plain");
  9783. });
  9784. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  9785. res.set_content("ok", "text/plain");
  9786. });
  9787. svr.Get("/header_field_value_check",
  9788. [&](const Request & /*req*/, Response &res) {
  9789. res.set_content("ok", "text/plain");
  9790. });
  9791. svr.CustomRoute("PROPFIND", "/dav",
  9792. [&](const Request & /*req*/, Response &res) {
  9793. res.status = StatusCode::MultiStatus_207;
  9794. });
  9795. // Server read timeout must be longer than the client read timeout for the
  9796. // bug to reproduce, probably to force the server to process a request
  9797. // without a trailing blank line.
  9798. const time_t client_read_timeout_sec = 1;
  9799. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  9800. bool listen_thread_ok = false;
  9801. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  9802. auto se = detail::scope_exit([&] {
  9803. svr.stop();
  9804. t.join();
  9805. ASSERT_FALSE(svr.is_running());
  9806. EXPECT_TRUE(listen_thread_ok);
  9807. });
  9808. svr.wait_until_ready();
  9809. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  9810. }
  9811. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  9812. // A certain header line causes an exception if the header property is parsed
  9813. // naively with a single regex. This occurs with libc++ but not libstdc++.
  9814. test_raw_request(
  9815. "GET /hi HTTP/1.1\r\n"
  9816. " : "
  9817. " "
  9818. " ");
  9819. }
  9820. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  9821. // A certain header line causes an exception if the header property *name* is
  9822. // parsed with a regular expression starting with "(.+?):" - this is a non-
  9823. // greedy matcher and requires backtracking when there are a lot of ":"
  9824. // characters.
  9825. // This occurs with libc++ but not libstdc++.
  9826. test_raw_request(
  9827. "GET /hi HTTP/1.1\r\n"
  9828. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  9829. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9830. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  9831. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  9832. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  9833. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  9834. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  9835. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  9836. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9837. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9838. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  9839. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9840. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  9841. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  9842. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  9843. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  9844. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  9845. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  9846. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  9847. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  9848. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  9849. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  9850. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  9851. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  9852. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  9853. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  9854. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  9855. "&&&%%%");
  9856. }
  9857. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  9858. // Make sure this doesn't crash the server.
  9859. // In a previous version of the header line regex, the "\r" rendered the line
  9860. // unparsable and the regex engine repeatedly backtracked, trying to look for
  9861. // a new position where the leading white space ended and the field value
  9862. // began.
  9863. // The crash occurs with libc++ but not libstdc++.
  9864. test_raw_request("GET /hi HTTP/1.1\r\n"
  9865. "a:" +
  9866. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  9867. "\r\n"
  9868. "\r\n");
  9869. }
  9870. TEST(ServerRequestParsingTest, StrictRequestLine) {
  9871. const char *rejected[] = {
  9872. // RFC 9112 §3: one SP between the parts, and nothing else
  9873. "GET /hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9874. "GET\t/hi HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9875. "GET /hi\tHTTP/1.1\r\nHost: localhost\r\n\r\n",
  9876. "GET /hi HTTP/1.1 \r\nHost: localhost\r\n\r\n",
  9877. // A request-target has no fragment
  9878. "GET /hi#x HTTP/1.1\r\nHost: localhost\r\n\r\n",
  9879. // An HTTP/1.1 request needs a Host
  9880. "GET /hi HTTP/1.1\r\n\r\n",
  9881. };
  9882. for (auto request : rejected) {
  9883. std::string out;
  9884. test_raw_request(request, &out);
  9885. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << request;
  9886. }
  9887. std::string out;
  9888. test_raw_request("GET /hi HTTP/1.0\r\n\r\n", &out);
  9889. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9890. }
  9891. TEST(ServerRequestParsingTest, AmbiguousTransferEncodingClosesConnection) {
  9892. // RFC 9112 §6.1
  9893. const char *requests[] = {
  9894. "PUT /put_hi HTTP/1.1\r\n"
  9895. "Host: localhost\r\n"
  9896. "Content-Length: 0\r\n"
  9897. "Transfer-Encoding: chunked\r\n"
  9898. "\r\n"
  9899. "0\r\n\r\n",
  9900. "PUT /put_hi HTTP/1.0\r\n"
  9901. "Connection: keep-alive\r\n"
  9902. "Transfer-Encoding: chunked\r\n"
  9903. "\r\n"
  9904. "0\r\n\r\n",
  9905. };
  9906. for (auto request : requests) {
  9907. std::string out;
  9908. test_raw_request(request, &out);
  9909. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15)) << request;
  9910. EXPECT_NE(std::string::npos, out.find("Connection: close")) << request;
  9911. }
  9912. }
  9913. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  9914. std::string out;
  9915. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9916. "Content-Type: text/plain\r\n"
  9917. "Transfer-Encoding: chunked\r\n"
  9918. "\r\n"
  9919. "nothex\r\n",
  9920. &out);
  9921. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9922. }
  9923. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  9924. std::string out;
  9925. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9926. "Content-Type: text/plain\r\n"
  9927. "Transfer-Encoding: chunked\r\n"
  9928. "\r\n"
  9929. "3\r\n"
  9930. "xyz\r\n"
  9931. "NaN\r\n",
  9932. &out);
  9933. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9934. }
  9935. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  9936. std::string out;
  9937. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  9938. "Content-Type: text/plain\r\n"
  9939. "Transfer-Encoding: chunked\r\n"
  9940. "\r\n"
  9941. // Length is too large for 64 bits.
  9942. "1ffffffffffffffff\r\n"
  9943. "xyz\r\n",
  9944. &out);
  9945. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9946. }
  9947. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  9948. test_raw_request("GET /hi HTTP/1.1\r\n"
  9949. "Content-Type: text/plain\r\n\r");
  9950. }
  9951. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  9952. std::string out;
  9953. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  9954. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9955. }
  9956. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  9957. for (auto target : {"/h\ri", "/h\x7fi"}) {
  9958. std::string out;
  9959. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  9960. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  9961. }
  9962. }
  9963. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  9964. std::string out;
  9965. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  9966. "Host: localhost\r\n"
  9967. "Connection: close\r\n\r\n",
  9968. &out);
  9969. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  9970. }
  9971. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  9972. Server svr;
  9973. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  9974. EXPECT_TRUE(!req.remote_addr.empty());
  9975. });
  9976. thread t = thread([&] { svr.listen(HOST, PORT); });
  9977. auto se = detail::scope_exit([&] {
  9978. svr.stop();
  9979. t.join();
  9980. ASSERT_FALSE(svr.is_running());
  9981. });
  9982. svr.wait_until_ready();
  9983. // Send an invalid request line to trigger Bad Request
  9984. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  9985. std::string out;
  9986. ASSERT_TRUE(send_request(5, bad_req, &out));
  9987. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  9988. }
  9989. // A custom method with neither Content-Length nor Transfer-Encoding must be
  9990. // answered right away rather than blocking on a read that waits for EOF.
  9991. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  9992. std::string out;
  9993. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  9994. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  9995. }
  9996. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  9997. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  9998. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  9999. for (const auto *method : methods) {
  10000. Server svr;
  10001. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10002. EXPECT_FALSE(svr.is_valid()) << method;
  10003. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  10004. }
  10005. }
  10006. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  10007. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  10008. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  10009. for (const auto *method : methods) {
  10010. Server svr;
  10011. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10012. EXPECT_FALSE(svr.is_valid()) << method;
  10013. }
  10014. }
  10015. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  10016. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  10017. "COPY", "MOVE", "LOCK",
  10018. "UNLOCK", "REPORT", "SUBSCRIBE"};
  10019. Server svr;
  10020. for (const auto *method : methods) {
  10021. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  10022. }
  10023. EXPECT_TRUE(svr.is_valid());
  10024. }
  10025. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  10026. Server svr;
  10027. svr.CustomRoute("POST", "/x",
  10028. [](const Request &, Response &, const ContentReader &) {});
  10029. EXPECT_FALSE(svr.is_valid());
  10030. }
  10031. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  10032. Server svr;
  10033. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  10034. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  10035. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  10036. EXPECT_FALSE(svr.is_valid());
  10037. }
  10038. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  10039. Server svr;
  10040. auto captured = Error::Success;
  10041. svr.set_error_logger(
  10042. [&](const Error &err, const Request * /*req*/) { captured = err; });
  10043. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  10044. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  10045. }
  10046. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  10047. std::string out;
  10048. std::string request(
  10049. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  10050. test_raw_request(request, &out);
  10051. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10052. }
  10053. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  10054. std::string out;
  10055. std::string request(
  10056. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  10057. test_raw_request(request, &out);
  10058. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10059. }
  10060. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  10061. std::string out;
  10062. std::string request(
  10063. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  10064. test_raw_request(request, &out);
  10065. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  10066. }
  10067. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  10068. std::string out;
  10069. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  10070. "Host: localhost\r\n"
  10071. "Test: \r\n\r\n",
  10072. &out);
  10073. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  10074. }
  10075. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  10076. Server svr;
  10077. std::string x_custom;
  10078. std::string cookie;
  10079. std::string xff;
  10080. std::string x_unicode;
  10081. std::string x_iis;
  10082. svr.Get("/check", [&](const Request &req, Response &res) {
  10083. x_custom = req.get_header_value("X-Custom");
  10084. cookie = req.get_header_value("Cookie");
  10085. xff = req.get_header_value("X-Forwarded-For");
  10086. x_unicode = req.get_header_value("X-Unicode");
  10087. x_iis = req.get_header_value("X-IIS");
  10088. res.set_content("ok", "text/plain");
  10089. });
  10090. thread t = thread([&] { svr.listen(HOST, PORT); });
  10091. auto se = detail::scope_exit([&] {
  10092. svr.stop();
  10093. t.join();
  10094. ASSERT_FALSE(svr.is_running());
  10095. });
  10096. svr.wait_until_ready();
  10097. const std::string req = "GET /check HTTP/1.1\r\n"
  10098. "Host: localhost\r\n"
  10099. "X-Custom: a%0D%0AInjected: b\r\n"
  10100. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  10101. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  10102. "X-Unicode: %E3%81%82\r\n"
  10103. "X-IIS: %u00E9\r\n"
  10104. "Connection: close\r\n"
  10105. "\r\n";
  10106. std::string res;
  10107. ASSERT_TRUE(send_request(5, req, &res));
  10108. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10109. // Every value must be returned verbatim (wire form), with no decoding.
  10110. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  10111. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  10112. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  10113. EXPECT_EQ("%E3%81%82", x_unicode);
  10114. EXPECT_EQ("%u00E9", x_iis);
  10115. }
  10116. // Applications that previously relied on automatic percent-decoding can
  10117. // reproduce the old behavior by explicitly calling decode_path_component()
  10118. // or, for RFC 3986 conformance, decode_uri_component().
  10119. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  10120. Server svr;
  10121. std::string decoded;
  10122. svr.Get("/check", [&](const Request &req, Response &res) {
  10123. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  10124. res.set_content("ok", "text/plain");
  10125. });
  10126. thread t = thread([&] { svr.listen(HOST, PORT); });
  10127. auto se = detail::scope_exit([&] {
  10128. svr.stop();
  10129. t.join();
  10130. ASSERT_FALSE(svr.is_running());
  10131. });
  10132. svr.wait_until_ready();
  10133. const std::string req = "GET /check HTTP/1.1\r\n"
  10134. "Host: localhost\r\n"
  10135. "X-Custom: hello%20world\r\n"
  10136. "Connection: close\r\n"
  10137. "\r\n";
  10138. std::string res;
  10139. ASSERT_TRUE(send_request(5, req, &res));
  10140. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10141. EXPECT_EQ("hello world", decoded);
  10142. }
  10143. // Regression test for #2033. Browsers send Referer values that include
  10144. // percent-encoded characters such as %0A inside the URL. Decoding the
  10145. // header value would either trip the post-decode CR/LF/NUL guard (the
  10146. // original bug, returning 400) or, after that guard was relaxed, silently
  10147. // store a literal LF — both unacceptable. The wire form must round-trip.
  10148. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  10149. Server svr;
  10150. std::string referer;
  10151. svr.Get("/check", [&](const Request &req, Response &res) {
  10152. referer = req.get_header_value("Referer");
  10153. res.set_content("ok", "text/plain");
  10154. });
  10155. thread t = thread([&] { svr.listen(HOST, PORT); });
  10156. auto se = detail::scope_exit([&] {
  10157. svr.stop();
  10158. t.join();
  10159. ASSERT_FALSE(svr.is_running());
  10160. });
  10161. svr.wait_until_ready();
  10162. const std::string req = "GET /check HTTP/1.1\r\n"
  10163. "Host: localhost\r\n"
  10164. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  10165. "Connection: close\r\n"
  10166. "\r\n";
  10167. std::string res;
  10168. ASSERT_TRUE(send_request(5, req, &res));
  10169. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  10170. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  10171. }
  10172. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  10173. Server svr;
  10174. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  10175. res.set_header("Cache-Control", "no-cache");
  10176. res.set_chunked_content_provider(
  10177. "text/event-stream", [](size_t offset, DataSink &sink) {
  10178. std::string s = "data:";
  10179. s += std::to_string(offset);
  10180. s += "\n\n";
  10181. auto ret = sink.write(s.data(), s.size());
  10182. EXPECT_TRUE(ret);
  10183. std::this_thread::sleep_for(std::chrono::seconds(1));
  10184. return true;
  10185. });
  10186. });
  10187. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10188. svr.wait_until_ready();
  10189. Client client(HOST, PORT);
  10190. const Headers headers = {{"Accept", "text/event-stream"}};
  10191. auto get_thread = std::thread([&client, &headers]() {
  10192. auto res = client.Get(
  10193. "/events", headers,
  10194. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  10195. });
  10196. auto se = detail::scope_exit([&] {
  10197. svr.stop();
  10198. get_thread.join();
  10199. listen_thread.join();
  10200. ASSERT_FALSE(svr.is_running());
  10201. });
  10202. // Give GET time to get a few messages.
  10203. std::this_thread::sleep_for(std::chrono::seconds(2));
  10204. }
  10205. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  10206. httplib::Server svr;
  10207. svr.Post("/hi",
  10208. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  10209. res.status = StatusCode::OK_200;
  10210. });
  10211. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10212. svr.wait_until_ready();
  10213. Client cli(HOST, PORT);
  10214. auto res = cli.Post("/hi", "data", "text/plain");
  10215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10216. EXPECT_EQ(StatusCode::OK_200, res->status);
  10217. svr.stop();
  10218. thread.join();
  10219. ASSERT_FALSE(svr.is_running());
  10220. res = cli.Post("/hi", "data", "text/plain");
  10221. ASSERT_FALSE(res);
  10222. }
  10223. TEST(ServerStopTest, ListenFailure) {
  10224. Server svr;
  10225. auto t = thread([&]() {
  10226. auto ret = svr.listen("????", PORT);
  10227. EXPECT_FALSE(ret);
  10228. });
  10229. svr.wait_until_ready();
  10230. svr.stop();
  10231. t.join();
  10232. }
  10233. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  10234. TEST(ServerStopTest, Decommision) {
  10235. Server svr;
  10236. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  10237. for (int i = 0; i < 4; i++) {
  10238. auto is_even = !(i % 2);
  10239. std::thread t{[&] {
  10240. try {
  10241. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  10242. if (is_even) {
  10243. throw std::runtime_error("Some thing that happens to go wrong.");
  10244. }
  10245. svr.listen(HOST, PORT);
  10246. } catch (...) { svr.decommission(); }
  10247. }};
  10248. svr.wait_until_ready();
  10249. // Server is up
  10250. {
  10251. Client cli(HOST, PORT);
  10252. auto res = cli.Get("/hi");
  10253. if (is_even) {
  10254. EXPECT_FALSE(res);
  10255. } else {
  10256. EXPECT_TRUE(res);
  10257. EXPECT_EQ("hi...", res->body);
  10258. }
  10259. }
  10260. svr.stop();
  10261. t.join();
  10262. // Server is down...
  10263. {
  10264. Client cli(HOST, PORT);
  10265. auto res = cli.Get("/hi");
  10266. EXPECT_FALSE(res);
  10267. }
  10268. }
  10269. }
  10270. #endif
  10271. // Helper function for string body upload progress tests
  10272. template <typename SetupHandler, typename ClientCall>
  10273. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  10274. ClientCall &&client_call,
  10275. const string &body) {
  10276. Server svr;
  10277. setup_handler(svr);
  10278. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10279. auto se = detail::scope_exit([&] {
  10280. svr.stop();
  10281. t.join();
  10282. });
  10283. svr.wait_until_ready();
  10284. Client cli(HOST, PORT);
  10285. vector<uint64_t> progress_values;
  10286. bool progress_called = false;
  10287. auto res =
  10288. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10289. progress_values.push_back(current);
  10290. progress_called = true;
  10291. return true;
  10292. });
  10293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10294. EXPECT_EQ(200, res->status);
  10295. EXPECT_TRUE(progress_called);
  10296. }
  10297. TEST(UploadProgressTest, PostStringBodyBasic) {
  10298. TestStringBodyUploadProgress(
  10299. [](Server &svr) {
  10300. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10301. res.set_content("received", "text/plain");
  10302. });
  10303. },
  10304. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10305. return cli.Post("/test", body, "text/plain", progress_callback);
  10306. },
  10307. "test data for upload progress");
  10308. }
  10309. TEST(UploadProgressTest, PutStringBodyBasic) {
  10310. TestStringBodyUploadProgress(
  10311. [](Server &svr) {
  10312. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  10313. res.set_content("put received", "text/plain");
  10314. });
  10315. },
  10316. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10317. return cli.Put("/test", body, "text/plain", progress_callback);
  10318. },
  10319. "put test data for upload progress");
  10320. }
  10321. TEST(UploadProgressTest, PatchStringBodyBasic) {
  10322. TestStringBodyUploadProgress(
  10323. [](Server &svr) {
  10324. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  10325. res.set_content("patch received", "text/plain");
  10326. });
  10327. },
  10328. [](Client &cli, const string &body, UploadProgress progress_callback) {
  10329. return cli.Patch("/test", body, "text/plain", progress_callback);
  10330. },
  10331. "patch test data for upload progress");
  10332. }
  10333. // Helper function for content provider upload progress tests
  10334. template <typename SetupHandler, typename ClientCall>
  10335. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  10336. ClientCall &&client_call) {
  10337. Server svr;
  10338. setup_handler(svr);
  10339. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10340. auto se = detail::scope_exit([&] {
  10341. svr.stop();
  10342. t.join();
  10343. });
  10344. svr.wait_until_ready();
  10345. Client cli(HOST, PORT);
  10346. vector<uint64_t> progress_values;
  10347. auto res =
  10348. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  10349. progress_values.push_back(current);
  10350. return true;
  10351. });
  10352. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10353. EXPECT_EQ(200, res->status);
  10354. EXPECT_FALSE(progress_values.empty());
  10355. }
  10356. TEST(UploadProgressTest, PostContentProviderProgress) {
  10357. TestContentProviderUploadProgress(
  10358. [](Server &svr) {
  10359. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  10360. res.set_content("provider received", "text/plain");
  10361. });
  10362. },
  10363. [](Client &cli, UploadProgress progress_callback) {
  10364. return cli.Post(
  10365. "/test", 9,
  10366. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  10367. sink.os << "test data";
  10368. return true;
  10369. },
  10370. "text/plain", progress_callback);
  10371. });
  10372. }
  10373. // Helper function for multipart upload progress tests
  10374. template <typename SetupHandler, typename ClientCall>
  10375. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  10376. ClientCall &&client_call,
  10377. const string &endpoint) {
  10378. Server svr;
  10379. setup_handler(svr);
  10380. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10381. auto se = detail::scope_exit([&] {
  10382. svr.stop();
  10383. t.join();
  10384. });
  10385. svr.wait_until_ready();
  10386. Client cli(HOST, PORT);
  10387. vector<uint64_t> progress_values;
  10388. UploadFormDataItems items = {
  10389. {"field1", "value1", "", ""},
  10390. {"field2", "longer value for progress tracking test", "", ""},
  10391. {"file1", "file content data for upload progress", "test.txt",
  10392. "text/plain"}};
  10393. auto res = client_call(cli, endpoint, items,
  10394. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10395. progress_values.push_back(current);
  10396. return true;
  10397. });
  10398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10399. EXPECT_EQ(200, res->status);
  10400. EXPECT_FALSE(progress_values.empty());
  10401. }
  10402. TEST(UploadProgressTest, PostMultipartProgress) {
  10403. TestMultipartUploadProgress(
  10404. [](Server &svr) {
  10405. svr.Post("/multipart", [](const Request &req, Response &res) {
  10406. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  10407. res.set_content("multipart received", "text/plain");
  10408. });
  10409. },
  10410. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  10411. UploadProgress progress_callback) {
  10412. return cli.Post(endpoint, items, progress_callback);
  10413. },
  10414. "/multipart");
  10415. }
  10416. // Helper function for basic download progress tests
  10417. template <typename SetupHandler, typename ClientCall>
  10418. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  10419. ClientCall &&client_call, const string &endpoint,
  10420. size_t expected_content_size) {
  10421. Server svr;
  10422. setup_handler(svr);
  10423. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10424. auto se = detail::scope_exit([&] {
  10425. svr.stop();
  10426. t.join();
  10427. });
  10428. svr.wait_until_ready();
  10429. Client cli(HOST, PORT);
  10430. vector<uint64_t> progress_values;
  10431. auto res = client_call(cli, endpoint,
  10432. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10433. progress_values.push_back(current);
  10434. return true;
  10435. });
  10436. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10437. EXPECT_EQ(200, res->status);
  10438. EXPECT_FALSE(progress_values.empty());
  10439. EXPECT_EQ(expected_content_size, res->body.size());
  10440. }
  10441. TEST(DownloadProgressTest, GetBasic) {
  10442. TestBasicDownloadProgress(
  10443. [](Server &svr) {
  10444. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  10445. string content(1000, 'D');
  10446. res.set_content(content, "text/plain");
  10447. });
  10448. },
  10449. [](Client &cli, const string &endpoint,
  10450. DownloadProgress progress_callback) {
  10451. return cli.Get(endpoint, progress_callback);
  10452. },
  10453. "/download", 1000u);
  10454. }
  10455. // Helper function for content receiver download progress tests
  10456. template <typename SetupHandler, typename ClientCall>
  10457. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  10458. ClientCall &&client_call,
  10459. const string &endpoint,
  10460. size_t expected_content_size) {
  10461. Server svr;
  10462. setup_handler(svr);
  10463. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10464. auto se = detail::scope_exit([&] {
  10465. svr.stop();
  10466. t.join();
  10467. });
  10468. svr.wait_until_ready();
  10469. Client cli(HOST, PORT);
  10470. vector<uint64_t> progress_values;
  10471. string received_body;
  10472. auto res = client_call(
  10473. cli, endpoint,
  10474. [&](const char *data, size_t data_length) -> bool {
  10475. received_body.append(data, data_length);
  10476. return true;
  10477. },
  10478. [&](uint64_t current, uint64_t /*total*/) -> bool {
  10479. progress_values.push_back(current);
  10480. return true;
  10481. });
  10482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10483. EXPECT_EQ(200, res->status);
  10484. EXPECT_FALSE(progress_values.empty());
  10485. EXPECT_EQ(expected_content_size, received_body.size());
  10486. EXPECT_TRUE(res->body.empty());
  10487. }
  10488. TEST(DownloadProgressTest, GetWithContentReceiver) {
  10489. TestContentReceiverDownloadProgress(
  10490. [](Server &svr) {
  10491. svr.Get("/download-receiver",
  10492. [](const Request & /*req*/, Response &res) {
  10493. string content(2000, 'R');
  10494. res.set_content(content, "text/plain");
  10495. });
  10496. },
  10497. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  10498. DownloadProgress progress_callback) {
  10499. return cli.Get(endpoint, content_receiver, progress_callback);
  10500. },
  10501. "/download-receiver", 2000u);
  10502. }
  10503. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  10504. // A provider reaching a pass with nothing to hand over - an empty buffer
  10505. // popped off a queue, say - must not be taken to mean the body is finished.
  10506. // It used to end the loop with the terminating chunk unwritten while the
  10507. // server still considered the response complete, so the peer waited for an
  10508. // end that never arrived.
  10509. Server svr;
  10510. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10511. auto step = std::make_shared<int>(0);
  10512. res.set_chunked_content_provider("text/plain",
  10513. [step](size_t /*offset*/, DataSink &sink) {
  10514. switch ((*step)++) {
  10515. case 0: sink.write("", 0); break;
  10516. case 1: sink.write("hello", 5); break;
  10517. default: sink.done(); break;
  10518. }
  10519. return true;
  10520. });
  10521. });
  10522. auto port = svr.bind_to_any_port(HOST);
  10523. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10524. auto listen_se = detail::scope_exit([&] {
  10525. svr.stop();
  10526. listen_thread.join();
  10527. ASSERT_FALSE(svr.is_running());
  10528. });
  10529. svr.wait_until_ready();
  10530. Client cli(HOST, port);
  10531. // Without the fix the body is never terminated, so bound the wait rather
  10532. // than letting the test hang on the default read timeout.
  10533. cli.set_read_timeout(5, 0);
  10534. auto res = cli.Get("/stream");
  10535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10536. EXPECT_EQ(StatusCode::OK_200, res->status);
  10537. EXPECT_EQ("hello", res->body);
  10538. }
  10539. TEST(StreamingTest, NoContentLengthStreaming) {
  10540. Server svr;
  10541. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  10542. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  10543. if (offset < 6) {
  10544. sink.os << (offset < 3 ? "a" : "b");
  10545. } else {
  10546. sink.done();
  10547. }
  10548. return true;
  10549. });
  10550. });
  10551. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10552. auto listen_se = detail::scope_exit([&] {
  10553. svr.stop();
  10554. listen_thread.join();
  10555. ASSERT_FALSE(svr.is_running());
  10556. });
  10557. svr.wait_until_ready();
  10558. Client client(HOST, PORT);
  10559. auto get_thread = std::thread([&client]() {
  10560. std::string s;
  10561. auto res =
  10562. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  10563. s += std::string(data, len);
  10564. return true;
  10565. });
  10566. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10567. EXPECT_EQ(StatusCode::OK_200, res->status);
  10568. EXPECT_EQ("aaabbb", s);
  10569. });
  10570. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  10571. // Give GET time to get a few messages.
  10572. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10573. }
  10574. TEST(MountTest, Unmount) {
  10575. Server svr;
  10576. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10577. auto se = detail::scope_exit([&] {
  10578. svr.stop();
  10579. listen_thread.join();
  10580. ASSERT_FALSE(svr.is_running());
  10581. });
  10582. svr.wait_until_ready();
  10583. Client cli("localhost", PORT);
  10584. svr.set_mount_point("/mount2", "./www2");
  10585. auto res = cli.Get("/");
  10586. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10587. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10588. res = cli.Get("/mount2/dir/test.html");
  10589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10590. EXPECT_EQ(StatusCode::OK_200, res->status);
  10591. svr.set_mount_point("/", "./www");
  10592. res = cli.Get("/dir/");
  10593. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10594. EXPECT_EQ(StatusCode::OK_200, res->status);
  10595. svr.remove_mount_point("/");
  10596. res = cli.Get("/dir/");
  10597. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10598. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10599. svr.remove_mount_point("/mount2");
  10600. res = cli.Get("/mount2/dir/test.html");
  10601. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10602. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10603. }
  10604. TEST(MountTest, MissingFileFallsThroughToHandlers) {
  10605. Server svr;
  10606. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10607. svr.Get("/api/hello", [](const Request &, Response &res) {
  10608. res.set_content("api", "text/plain");
  10609. });
  10610. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10611. auto se = detail::scope_exit([&] {
  10612. svr.stop();
  10613. listen_thread.join();
  10614. ASSERT_FALSE(svr.is_running());
  10615. });
  10616. svr.wait_until_ready();
  10617. Client cli(HOST, PORT);
  10618. auto res = cli.Get("/dir/test.html");
  10619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10620. EXPECT_EQ(StatusCode::OK_200, res->status);
  10621. res = cli.Get("/api/hello");
  10622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10623. EXPECT_EQ(StatusCode::OK_200, res->status);
  10624. EXPECT_EQ("api", res->body);
  10625. }
  10626. TEST(MountTest, PathSegmentBoundary) {
  10627. Server svr;
  10628. svr.set_mount_point("/mount2", "./www2");
  10629. svr.set_mount_point("/", "./www");
  10630. auto port = svr.bind_to_any_port(HOST);
  10631. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10632. auto se = detail::scope_exit([&] {
  10633. svr.stop();
  10634. listen_thread.join();
  10635. ASSERT_FALSE(svr.is_running());
  10636. });
  10637. svr.wait_until_ready();
  10638. Client cli(HOST, port);
  10639. auto res = cli.Get("/mount2/dir/test.html");
  10640. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10641. EXPECT_EQ(StatusCode::OK_200, res->status);
  10642. // "/mount2" must not match part-way through a path segment.
  10643. res = cli.Get("/mount2dir/test.html");
  10644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10645. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10646. // A mount point ending in '/' keeps matching every path below it.
  10647. res = cli.Get("/dir/test.html");
  10648. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10649. EXPECT_EQ(StatusCode::OK_200, res->status);
  10650. }
  10651. TEST(MountTest, Redicect) {
  10652. Server svr;
  10653. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10654. auto se = detail::scope_exit([&] {
  10655. svr.stop();
  10656. listen_thread.join();
  10657. ASSERT_FALSE(svr.is_running());
  10658. });
  10659. svr.set_mount_point("/", "./www");
  10660. svr.wait_until_ready();
  10661. Client cli("localhost", PORT);
  10662. auto res = cli.Get("/dir/");
  10663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10664. EXPECT_EQ(StatusCode::OK_200, res->status);
  10665. res = cli.Get("/dir");
  10666. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10667. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  10668. res = cli.Get("/file");
  10669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10670. EXPECT_EQ(StatusCode::OK_200, res->status);
  10671. res = cli.Get("/file/");
  10672. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10673. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10674. cli.set_follow_location(true);
  10675. res = cli.Get("/dir");
  10676. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10677. EXPECT_EQ(StatusCode::OK_200, res->status);
  10678. }
  10679. TEST(MountTest, MultibytesPathName) {
  10680. Server svr;
  10681. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10682. auto se = detail::scope_exit([&] {
  10683. svr.stop();
  10684. listen_thread.join();
  10685. ASSERT_FALSE(svr.is_running());
  10686. });
  10687. svr.set_mount_point("/", "./www");
  10688. svr.wait_until_ready();
  10689. Client cli("localhost", PORT);
  10690. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  10691. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10692. EXPECT_EQ(StatusCode::OK_200, res->status);
  10693. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  10694. }
  10695. // A mount point serves no path with an empty segment or one ending in '.' or
  10696. // a space, so a guard in the pre-routing handler sees the path of every file
  10697. // that is served
  10698. TEST(MountTest, AliasedPathDoesNotPassPreRoutingGuard) {
  10699. Server svr;
  10700. ASSERT_TRUE(svr.set_mount_point("/", "./www"));
  10701. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  10702. if (req.path == "/dir/test.html") {
  10703. res.status = StatusCode::Unauthorized_401;
  10704. return Server::HandlerResponse::Handled;
  10705. }
  10706. return Server::HandlerResponse::Unhandled;
  10707. });
  10708. auto port = svr.bind_to_any_port(HOST);
  10709. ASSERT_LT(0, port);
  10710. thread t = thread([&] { svr.listen_after_bind(); });
  10711. auto se = detail::scope_exit([&] {
  10712. svr.stop();
  10713. t.join();
  10714. ASSERT_FALSE(svr.is_running());
  10715. });
  10716. svr.wait_until_ready();
  10717. Client cli(HOST, port);
  10718. for (auto path :
  10719. {"/./dir/test.html", "/dir/./test.html", "//dir/test.html",
  10720. "/dir//test.html", "/dir/../dir/test.html", "/%2e/dir/test.html",
  10721. "/dir/test.html.", "/dir/test.html%20"}) {
  10722. SCOPED_TRACE(path);
  10723. auto res = cli.Get(path);
  10724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10725. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10726. }
  10727. }
  10728. TEST(UserDefinedMIMETypeMappingTest, IgnoresCaseAndLeadingDot) {
  10729. Server svr;
  10730. svr.set_mount_point("/", "./www");
  10731. svr.set_file_extension_and_mimetype_mapping(".abcde", "text/abcde");
  10732. svr.set_file_extension_and_mimetype_mapping("HTML", "text/x-html");
  10733. auto port = svr.bind_to_any_port(HOST);
  10734. ASSERT_GT(port, 0);
  10735. thread t = thread([&] { svr.listen_after_bind(); });
  10736. auto se = detail::scope_exit([&] {
  10737. svr.stop();
  10738. t.join();
  10739. ASSERT_FALSE(svr.is_running());
  10740. });
  10741. svr.wait_until_ready();
  10742. Client cli(HOST, port);
  10743. auto res = cli.Get("/dir/test.abcde");
  10744. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10745. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  10746. res = cli.Get("/dir/test.html");
  10747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10748. EXPECT_EQ("text/x-html", res->get_header_value("Content-Type"));
  10749. }
  10750. #ifdef _WIN32
  10751. // Issue #2435: mmap::open() must succeed even when another handle holds
  10752. // the file open for writing (e.g. an active log file).
  10753. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  10754. const char *path = "mmap_concurrent_writer_test.txt";
  10755. const char *content = "hello";
  10756. {
  10757. std::ofstream f(path, std::ios::binary);
  10758. f.write(content, static_cast<std::streamsize>(strlen(content)));
  10759. }
  10760. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10761. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  10762. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  10763. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  10764. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  10765. detail::mmap m(path);
  10766. ASSERT_TRUE(m.is_open());
  10767. EXPECT_EQ(strlen(content), m.size());
  10768. char buf[8];
  10769. ASSERT_EQ(strlen(content), m.read(0, buf, sizeof(buf)));
  10770. EXPECT_EQ(0, std::memcmp(content, buf, strlen(content)));
  10771. }
  10772. #endif
  10773. #ifndef _WIN32
  10774. // A directory or a device has no size to serve.
  10775. TEST(MmapTest, OnlyRegularFilesAreOpened) {
  10776. const char *path = "./mmap_not_regular_test_dir";
  10777. ASSERT_EQ(0, ::mkdir(path, 0755));
  10778. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  10779. for (auto p : {path, "/dev/null"}) {
  10780. detail::mmap m(p);
  10781. EXPECT_FALSE(m.is_open()) << p;
  10782. EXPECT_EQ(0U, m.size()) << p;
  10783. }
  10784. Server svr;
  10785. svr.Get("/null", [](const Request & /*req*/, Response &res) {
  10786. res.set_file_content("/dev/null");
  10787. });
  10788. auto port = svr.bind_to_any_port(HOST);
  10789. thread t = thread([&] { svr.listen_after_bind(); });
  10790. auto se = detail::scope_exit([&] {
  10791. svr.stop();
  10792. t.join();
  10793. });
  10794. svr.wait_until_ready();
  10795. auto res = Client(HOST, port).Get("/null");
  10796. ASSERT_TRUE(res);
  10797. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  10798. }
  10799. #endif
  10800. #ifdef __linux__
  10801. // Nothing of the file stays mapped, where a truncation would raise SIGBUS.
  10802. TEST(MmapTest, FileIsNotMapped) {
  10803. const char *path = "mmap_not_mapped_test.txt";
  10804. {
  10805. std::ofstream f(path, std::ios::binary);
  10806. f << "hello";
  10807. }
  10808. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  10809. detail::mmap m(path);
  10810. ASSERT_TRUE(m.is_open());
  10811. std::ifstream maps("/proc/self/maps");
  10812. std::string mappings((std::istreambuf_iterator<char>(maps)),
  10813. std::istreambuf_iterator<char>());
  10814. EXPECT_EQ(std::string::npos, mappings.find(path));
  10815. }
  10816. #endif
  10817. TEST(KeepAliveTest, ReadTimeout) {
  10818. Server svr;
  10819. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10820. std::this_thread::sleep_for(std::chrono::seconds(2));
  10821. res.set_content("a", "text/plain");
  10822. });
  10823. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10824. res.set_content("b", "text/plain");
  10825. });
  10826. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10827. auto se = detail::scope_exit([&] {
  10828. svr.stop();
  10829. listen_thread.join();
  10830. ASSERT_FALSE(svr.is_running());
  10831. });
  10832. svr.wait_until_ready();
  10833. Client cli("localhost", PORT);
  10834. cli.set_keep_alive(true);
  10835. cli.set_read_timeout(std::chrono::seconds(1));
  10836. auto resa = cli.Get("/a");
  10837. ASSERT_FALSE(resa);
  10838. EXPECT_EQ(Error::Read, resa.error());
  10839. auto resb = cli.Get("/b");
  10840. ASSERT_TRUE(resb);
  10841. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10842. EXPECT_EQ("b", resb->body);
  10843. }
  10844. TEST(KeepAliveTest, MaxCount) {
  10845. size_t keep_alive_max_count = 3;
  10846. Server svr;
  10847. svr.set_keep_alive_max_count(keep_alive_max_count);
  10848. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10849. res.set_content("Hello World!", "text/plain");
  10850. });
  10851. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10852. auto se = detail::scope_exit([&] {
  10853. svr.stop();
  10854. listen_thread.join();
  10855. ASSERT_FALSE(svr.is_running());
  10856. });
  10857. svr.wait_until_ready();
  10858. Client cli(HOST, PORT);
  10859. cli.set_keep_alive(true);
  10860. for (size_t i = 0; i < 5; i++) {
  10861. auto result = cli.Get("/hi");
  10862. ASSERT_TRUE(result);
  10863. EXPECT_EQ(StatusCode::OK_200, result->status);
  10864. if (i == keep_alive_max_count - 1) {
  10865. EXPECT_EQ("close", result->get_header_value("Connection"));
  10866. } else {
  10867. EXPECT_FALSE(result->has_header("Connection"));
  10868. }
  10869. }
  10870. }
  10871. // A client may pipeline its requests (RFC 9112 9.3.2), so reading one request
  10872. // can pull the next one into the server's buffer. The server must serve it
  10873. // without waiting for the socket to become readable again. The keep-alive
  10874. // timeout outlasts the client's read timeout, so a request left waiting for it
  10875. // shows up as a missing response.
  10876. static void serve_pipelining_routes(Server &svr,
  10877. const std::function<void(int)> &client) {
  10878. svr.set_keep_alive_timeout(5);
  10879. svr.Get("/hi/(\\d+)", [](const Request &req, Response &res) {
  10880. res.set_content("hi " + req.matches[1].str(), "text/plain");
  10881. });
  10882. svr.Post("/echo", [](const Request &req, Response &res) {
  10883. res.set_content("echo " + req.body, "text/plain");
  10884. });
  10885. auto port = svr.bind_to_any_port(HOST);
  10886. thread t = thread([&] { svr.listen_after_bind(); });
  10887. auto se = detail::scope_exit([&] {
  10888. svr.stop();
  10889. t.join();
  10890. });
  10891. svr.wait_until_ready();
  10892. client(port);
  10893. }
  10894. static std::string
  10895. send_pipelined_requests(const std::vector<std::string> &parts) {
  10896. Server svr;
  10897. std::string res;
  10898. serve_pipelining_routes(svr, [&](int port) {
  10899. EXPECT_TRUE(send_request_in_parts(2, parts, &res, port));
  10900. });
  10901. return res;
  10902. }
  10903. static void expect_in_order(const std::string &res,
  10904. const std::vector<std::string> &bodies) {
  10905. size_t pos = 0;
  10906. for (const auto &body : bodies) {
  10907. pos = res.find(body, pos);
  10908. ASSERT_NE(std::string::npos, pos) << "missing or out of order: " << body;
  10909. pos += body.size();
  10910. }
  10911. }
  10912. TEST(KeepAliveTest, PipelinedRequests) {
  10913. auto res = send_pipelined_requests(
  10914. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10915. "POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10916. "Content-Length: 4\r\n\r\nbody"
  10917. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10918. expect_in_order(res, {"hi 1", "echo body", "hi 3"});
  10919. }
  10920. // The second request starts in the server's buffer and ends on the socket.
  10921. TEST(KeepAliveTest, PipelinedRequestSplitAcrossReads) {
  10922. auto res =
  10923. send_pipelined_requests({"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10924. "GET /hi/2 HTTP/1.1\r\nHo",
  10925. "st: localhost\r\nConnection: close\r\n\r\n"});
  10926. expect_in_order(res, {"hi 1", "hi 2"});
  10927. }
  10928. // RFC 9112 2.2: an empty line before the request-line is ignored, so an extra
  10929. // CRLF after a body does not turn into a 400 for the next request.
  10930. TEST(KeepAliveTest, EmptyLineBeforeRequestLineIsIgnored) {
  10931. auto res = send_pipelined_requests(
  10932. {"POST /echo HTTP/1.1\r\nHost: localhost\r\n"
  10933. "Content-Length: 4\r\n\r\nbody\r\n"
  10934. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"});
  10935. EXPECT_EQ(std::string::npos, res.find("400 Bad Request"));
  10936. expect_in_order(res, {"echo body", "hi 2"});
  10937. }
  10938. // Where an unparsable request ends is unknown, so what follows it in the buffer
  10939. // must not be served as the next request.
  10940. TEST(KeepAliveTest, PipelinedRequestAfterInvalidRequestIsNotServed) {
  10941. auto res = send_pipelined_requests(
  10942. {"INVALID REQUEST LINE\r\n\r\n"
  10943. "GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"});
  10944. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  10945. EXPECT_EQ(std::string::npos, res.find("hi 1"));
  10946. }
  10947. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  10948. // Over TLS, the next request is held by the TLS library as already decrypted
  10949. // data rather than on the socket.
  10950. TEST(KeepAliveTest, SSLPipelinedRequests) {
  10951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10952. std::string res;
  10953. serve_pipelining_routes(svr, [&](int port) {
  10954. // One part, so all three requests arrive in one TLS record
  10955. EXPECT_TRUE(send_ssl_request_in_parts(
  10956. 2,
  10957. {"GET /hi/1 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10958. "GET /hi/2 HTTP/1.1\r\nHost: localhost\r\n\r\n"
  10959. "GET /hi/3 HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n"},
  10960. &res, port));
  10961. });
  10962. expect_in_order(res, {"hi 1", "hi 2", "hi 3"});
  10963. }
  10964. #endif
  10965. TEST(KeepAliveTest, Issue1041) {
  10966. Server svr;
  10967. svr.set_keep_alive_timeout(3);
  10968. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  10969. res.set_content("Hello World!", "text/plain");
  10970. });
  10971. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10972. auto se = detail::scope_exit([&] {
  10973. svr.stop();
  10974. listen_thread.join();
  10975. ASSERT_FALSE(svr.is_running());
  10976. });
  10977. svr.wait_until_ready();
  10978. Client cli(HOST, PORT);
  10979. cli.set_keep_alive(true);
  10980. auto result = cli.Get("/hi");
  10981. ASSERT_TRUE(result);
  10982. EXPECT_EQ(StatusCode::OK_200, result->status);
  10983. std::this_thread::sleep_for(std::chrono::seconds(5));
  10984. result = cli.Get("/hi");
  10985. ASSERT_TRUE(result);
  10986. EXPECT_EQ(StatusCode::OK_200, result->status);
  10987. }
  10988. TEST(KeepAliveTest, MaxCountZeroSetsNoLimit) {
  10989. Server svr;
  10990. svr.set_keep_alive_max_count(0);
  10991. std::set<int> remote_ports;
  10992. svr.Get("/hi", [&](const Request &req, Response &res) {
  10993. remote_ports.insert(req.remote_port);
  10994. res.set_content("hi", "text/plain");
  10995. });
  10996. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  10997. auto se = detail::scope_exit([&] {
  10998. svr.stop();
  10999. listen_thread.join();
  11000. ASSERT_FALSE(svr.is_running());
  11001. });
  11002. svr.wait_until_ready();
  11003. Client cli(HOST, PORT);
  11004. cli.set_keep_alive(true);
  11005. for (int i = 0; i < 3; i++) {
  11006. auto res = cli.Get("/hi");
  11007. ASSERT_TRUE(res);
  11008. EXPECT_EQ("timeout=5", res->get_header_value("Keep-Alive"));
  11009. }
  11010. // All three over one connection
  11011. EXPECT_EQ(1u, remote_ports.size());
  11012. }
  11013. TEST(KeepAliveTest, Issue1959) {
  11014. Server svr;
  11015. svr.set_keep_alive_timeout(5);
  11016. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11017. res.set_content("a", "text/plain");
  11018. });
  11019. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11020. auto se = detail::scope_exit([&] {
  11021. if (!svr.is_running()) return;
  11022. svr.stop();
  11023. listen_thread.join();
  11024. ASSERT_FALSE(svr.is_running());
  11025. });
  11026. svr.wait_until_ready();
  11027. Client cli("localhost", PORT);
  11028. cli.set_keep_alive(true);
  11029. using namespace std::chrono;
  11030. auto start = steady_clock::now();
  11031. cli.Get("/a");
  11032. svr.stop();
  11033. listen_thread.join();
  11034. auto end = steady_clock::now();
  11035. auto elapsed = duration_cast<milliseconds>(end - start).count();
  11036. EXPECT_LT(elapsed, 5000);
  11037. }
  11038. #ifdef CPPHTTPLIB_SSL_ENABLED
  11039. TEST(KeepAliveTest, SSLClientReconnection) {
  11040. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11041. ASSERT_TRUE(svr.is_valid());
  11042. svr.set_keep_alive_timeout(1);
  11043. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  11044. res.set_content("Hello World!", "text/plain");
  11045. });
  11046. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11047. auto se = detail::scope_exit([&] {
  11048. svr.stop();
  11049. listen_thread.join();
  11050. ASSERT_FALSE(svr.is_running());
  11051. });
  11052. svr.wait_until_ready();
  11053. SSLClient cli(HOST, PORT);
  11054. cli.enable_server_certificate_verification(false);
  11055. cli.set_keep_alive(true);
  11056. auto result = cli.Get("/hi");
  11057. ASSERT_TRUE(result);
  11058. EXPECT_EQ(StatusCode::OK_200, result->status);
  11059. result = cli.Get("/hi");
  11060. ASSERT_TRUE(result);
  11061. EXPECT_EQ(StatusCode::OK_200, result->status);
  11062. std::this_thread::sleep_for(std::chrono::seconds(2));
  11063. // Recoonect
  11064. result = cli.Get("/hi");
  11065. ASSERT_TRUE(result);
  11066. EXPECT_EQ(StatusCode::OK_200, result->status);
  11067. result = cli.Get("/hi");
  11068. ASSERT_TRUE(result);
  11069. EXPECT_EQ(StatusCode::OK_200, result->status);
  11070. }
  11071. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  11072. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11073. ASSERT_TRUE(svr.is_valid());
  11074. svr.set_keep_alive_timeout(1);
  11075. std::string content = "reconnect";
  11076. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  11077. res.set_content("Hello World!", "text/plain");
  11078. });
  11079. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11080. auto se = detail::scope_exit([&] {
  11081. svr.stop();
  11082. listen_thread.join();
  11083. ASSERT_FALSE(svr.is_running());
  11084. });
  11085. svr.wait_until_ready();
  11086. SSLClient cli(HOST, PORT);
  11087. cli.enable_server_certificate_verification(false);
  11088. cli.set_keep_alive(true);
  11089. auto result = cli.Post(
  11090. "/hi", content.size(),
  11091. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11092. sink.write(content.c_str(), content.size());
  11093. return true;
  11094. },
  11095. "text/plain");
  11096. ASSERT_TRUE(result);
  11097. EXPECT_EQ(200, result->status);
  11098. std::this_thread::sleep_for(std::chrono::seconds(2));
  11099. // Recoonect
  11100. result = cli.Post(
  11101. "/hi", content.size(),
  11102. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11103. sink.write(content.c_str(), content.size());
  11104. return true;
  11105. },
  11106. "text/plain");
  11107. ASSERT_TRUE(result);
  11108. EXPECT_EQ(200, result->status);
  11109. result = cli.Post(
  11110. "/hi", content.size(),
  11111. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11112. sink.write(content.c_str(), content.size());
  11113. return true;
  11114. },
  11115. "text/plain");
  11116. ASSERT_TRUE(result);
  11117. EXPECT_EQ(200, result->status);
  11118. }
  11119. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  11120. using namespace httplib::tls;
  11121. {
  11122. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11123. ASSERT_TRUE(svr.is_valid());
  11124. svr.Get("/sni", [&](const Request &req, Response &res) {
  11125. std::string expected = req.sni();
  11126. EXPECT_EQ(expected, req.get_param_value("expected"));
  11127. res.set_content("ok", "text/plain");
  11128. });
  11129. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  11130. auto se = detail::scope_exit([&] {
  11131. svr.stop();
  11132. listen_thread.join();
  11133. ASSERT_FALSE(svr.is_running());
  11134. });
  11135. svr.wait_until_ready();
  11136. {
  11137. SSLClient cli("localhost", PORT);
  11138. cli.enable_server_certificate_verification(false);
  11139. auto res = cli.Get("/sni?expected=localhost");
  11140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11141. }
  11142. {
  11143. SSLClient cli("::1", PORT);
  11144. cli.enable_server_certificate_verification(false);
  11145. auto res = cli.Get("/sni?expected=");
  11146. // NOTE: This may fail if the server is listening on IPv4 only
  11147. // (e.g., when localhost resolves to 127.0.0.1 only)
  11148. if (res) {
  11149. EXPECT_EQ(StatusCode::OK_200, res->status);
  11150. } else {
  11151. EXPECT_EQ(Error::Connection, res.error());
  11152. }
  11153. }
  11154. }
  11155. }
  11156. // The SNI of a failed handshake does not reach the next connection that the
  11157. // same worker thread serves
  11158. TEST(SNI_AutoDetectionTest, FailedHandshakeLeavesNoSNI) {
  11159. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11160. ASSERT_TRUE(svr.is_valid());
  11161. svr.new_task_queue = [] { return new ThreadPool(1); };
  11162. svr.Get("/sni", [](const Request &req, Response &res) {
  11163. res.set_content(req.sni(), "text/plain");
  11164. });
  11165. auto port = svr.bind_to_any_port("127.0.0.1");
  11166. ASSERT_LT(0, port);
  11167. thread t = thread([&] { svr.listen_after_bind(); });
  11168. auto se = detail::scope_exit([&] {
  11169. svr.stop();
  11170. t.join();
  11171. ASSERT_FALSE(svr.is_running());
  11172. });
  11173. svr.wait_until_ready();
  11174. {
  11175. // Sends SNI, then rejects the server certificate, which the CA did not sign
  11176. SSLClient cli("localhost", port);
  11177. cli.set_hostname_addr_map({{"localhost", "127.0.0.1"}});
  11178. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  11179. auto res = cli.Get("/sni");
  11180. ASSERT_FALSE(res);
  11181. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11182. }
  11183. // An IP host sends no SNI (RFC 6066)
  11184. SSLClient cli("127.0.0.1", port);
  11185. cli.enable_server_certificate_verification(false);
  11186. auto res = cli.Get("/sni");
  11187. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11188. EXPECT_EQ("", res->body);
  11189. }
  11190. #endif
  11191. TEST(ClientProblemDetectionTest, ContentProvider) {
  11192. Server svr;
  11193. size_t content_length = 1024 * 1024;
  11194. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  11195. res.set_content_provider(
  11196. content_length, "text/plain",
  11197. [&](size_t offset, size_t length, DataSink &sink) {
  11198. auto out_len = std::min(length, static_cast<size_t>(1024));
  11199. std::string out(out_len, '@');
  11200. sink.write(out.data(), out_len);
  11201. return offset < 4096;
  11202. },
  11203. [](bool success) { ASSERT_FALSE(success); });
  11204. });
  11205. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  11206. res.set_content_provider(
  11207. 0, "text/plain",
  11208. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  11209. EXPECT_TRUE(false);
  11210. return true;
  11211. },
  11212. [](bool success) { ASSERT_FALSE(success); });
  11213. });
  11214. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11215. auto se = detail::scope_exit([&] {
  11216. svr.stop();
  11217. listen_thread.join();
  11218. ASSERT_FALSE(svr.is_running());
  11219. });
  11220. svr.wait_until_ready();
  11221. Client cli("localhost", PORT);
  11222. {
  11223. auto res = cli.Get("/hi", [&](const char * /*data*/,
  11224. size_t /*data_length*/) { return false; });
  11225. ASSERT_FALSE(res);
  11226. }
  11227. {
  11228. auto res = cli.Get("/empty", [&](const char * /*data*/,
  11229. size_t /*data_length*/) { return false; });
  11230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11231. }
  11232. }
  11233. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  11234. // A provider that reports success without writing anything and without
  11235. // calling done() used to be handed the same offset and length again on every
  11236. // pass, so it spun for as long as the peer stayed connected.
  11237. Server svr;
  11238. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11239. res.set_content("ok", "text/plain");
  11240. });
  11241. auto port = svr.bind_to_any_port(HOST);
  11242. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  11243. auto se = detail::scope_exit([&] {
  11244. svr.stop();
  11245. listen_thread.join();
  11246. ASSERT_FALSE(svr.is_running());
  11247. });
  11248. svr.wait_until_ready();
  11249. std::atomic<int> call_count{0};
  11250. Client cli(HOST, port);
  11251. auto res = cli.Post(
  11252. "/", 1024,
  11253. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  11254. // Give up after enough passes to show the spin, so that losing the
  11255. // check below fails this test instead of hanging it.
  11256. return ++call_count < 100;
  11257. },
  11258. "text/plain");
  11259. ASSERT_FALSE(res);
  11260. EXPECT_EQ(Error::Write, res.error());
  11261. EXPECT_EQ(1, call_count.load());
  11262. }
  11263. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  11264. // A writer only has to assign `write`. The other three used to be left as
  11265. // empty std::functions, so a provider calling one threw
  11266. // std::bad_function_call out of the thread running it and took the whole
  11267. // process down.
  11268. DataSink sink;
  11269. std::string written;
  11270. sink.write = [&](const char *data, size_t data_len) {
  11271. written.append(data, data_len);
  11272. return true;
  11273. };
  11274. EXPECT_TRUE(sink.is_writable());
  11275. sink.done();
  11276. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11277. EXPECT_TRUE(written.empty());
  11278. }
  11279. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  11280. // A sink that cannot carry trailers still has to finish.
  11281. DataSink sink;
  11282. auto done_count = 0;
  11283. sink.done = [&]() { done_count++; };
  11284. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  11285. EXPECT_EQ(1, done_count);
  11286. }
  11287. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  11288. Server svr;
  11289. const std::string body(4096, 'x');
  11290. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11291. res.set_content_provider(body.size(), "text/plain",
  11292. [&](size_t offset, size_t length, DataSink &sink) {
  11293. sink.write(body.data() + offset, length);
  11294. sink.done();
  11295. return true;
  11296. });
  11297. });
  11298. auto port = svr.bind_to_any_port(HOST);
  11299. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11300. auto se = detail::scope_exit([&] {
  11301. svr.stop();
  11302. listen_thread.join();
  11303. ASSERT_FALSE(svr.is_running());
  11304. });
  11305. svr.wait_until_ready();
  11306. Client cli(HOST, port);
  11307. auto res = cli.Get("/");
  11308. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11309. EXPECT_EQ(StatusCode::OK_200, res->status);
  11310. EXPECT_EQ(body, res->body);
  11311. }
  11312. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  11313. Server svr;
  11314. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11315. res.set_content_provider(
  11316. 1024, "text/plain",
  11317. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11318. sink.write("hello", 5);
  11319. sink.done(); // short of the 1024 bytes the response promised
  11320. return true;
  11321. });
  11322. });
  11323. auto port = svr.bind_to_any_port(HOST);
  11324. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11325. auto se = detail::scope_exit([&] {
  11326. svr.stop();
  11327. listen_thread.join();
  11328. ASSERT_FALSE(svr.is_running());
  11329. });
  11330. svr.wait_until_ready();
  11331. Client cli(HOST, port);
  11332. cli.set_read_timeout(5, 0);
  11333. // The response is short of its Content-Length, so the client cannot read a
  11334. // complete body. What matters is that this returns at all: a no-op done()
  11335. // would leave the writer looping over a provider that never makes progress.
  11336. auto res = cli.Get("/");
  11337. EXPECT_FALSE(res);
  11338. }
  11339. // Read as the next response by a peer that sees it after a framed body.
  11340. static const std::string smuggled_response =
  11341. "HTTP/1.1 200 OK\r\nContent-Length: 8\r\n\r\nSMUGGLED";
  11342. TEST(DataSinkTest, LengthFramedProviderCannotWritePastTheLength) {
  11343. Server svr;
  11344. svr.Get("/", [](const Request & /*req*/, Response &res) {
  11345. res.set_content_provider(
  11346. 5, "text/plain",
  11347. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11348. auto data = "AAAAA" + smuggled_response;
  11349. sink.write(data.data(), data.size());
  11350. return true;
  11351. });
  11352. });
  11353. thread t = thread([&] { svr.listen(HOST, PORT); });
  11354. auto se = detail::scope_exit([&] {
  11355. svr.stop();
  11356. t.join();
  11357. ASSERT_FALSE(svr.is_running());
  11358. });
  11359. svr.wait_until_ready();
  11360. std::string resp;
  11361. ASSERT_TRUE(send_request(1, "GET / HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11362. EXPECT_EQ("AAAAA", resp.substr(resp.find("\r\n\r\n") + 4));
  11363. resp.clear();
  11364. ASSERT_TRUE(send_request(
  11365. 1, "GET / HTTP/1.1\r\nHost: x\r\nRange: bytes=0-1\r\n\r\n", &resp));
  11366. EXPECT_EQ("AA", resp.substr(resp.find("\r\n\r\n") + 4));
  11367. }
  11368. TEST(NoContentTest, BodyIsNotSent) {
  11369. Server svr;
  11370. svr.Get("/204", [](const Request & /*req*/, Response &res) {
  11371. res.status = StatusCode::NoContent_204;
  11372. res.set_content(smuggled_response, "text/plain");
  11373. });
  11374. svr.Get("/304", [](const Request & /*req*/, Response &res) {
  11375. res.status = StatusCode::NotModified_304;
  11376. res.set_chunked_content_provider(
  11377. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  11378. sink.write(smuggled_response.data(), smuggled_response.size());
  11379. sink.done();
  11380. return true;
  11381. });
  11382. });
  11383. thread t = thread([&] { svr.listen(HOST, PORT); });
  11384. auto se = detail::scope_exit([&] {
  11385. svr.stop();
  11386. t.join();
  11387. ASSERT_FALSE(svr.is_running());
  11388. });
  11389. svr.wait_until_ready();
  11390. for (auto path : {"/204", "/304"}) {
  11391. std::string resp;
  11392. ASSERT_TRUE(send_request(
  11393. 1, std::string("GET ") + path + " HTTP/1.1\r\nHost: x\r\n\r\n", &resp));
  11394. EXPECT_EQ(resp.size(), resp.find("\r\n\r\n") + 4) << path;
  11395. EXPECT_EQ(std::string::npos, resp.find("Content-Length")) << path;
  11396. EXPECT_EQ(std::string::npos, resp.find("Transfer-Encoding")) << path;
  11397. }
  11398. }
  11399. TEST(DataSinkTest, RequestProviderCannotWritePastTheLength) {
  11400. Server svr;
  11401. std::atomic<bool> smuggled(false);
  11402. svr.Post("/", [](const Request & /*req*/, Response &res) {
  11403. res.set_content("ok", "text/plain");
  11404. });
  11405. svr.Get("/smuggled", [&](const Request & /*req*/, Response & /*res*/) {
  11406. smuggled = true;
  11407. });
  11408. auto port = svr.bind_to_any_port(HOST);
  11409. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11410. auto se = detail::scope_exit([&] {
  11411. svr.stop();
  11412. listen_thread.join();
  11413. ASSERT_FALSE(svr.is_running());
  11414. });
  11415. svr.wait_until_ready();
  11416. // What follows the body would be read as the next request.
  11417. Client cli(HOST, port);
  11418. auto res = cli.Post(
  11419. "/", 5,
  11420. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11421. std::string data = "helloGET /smuggled HTTP/1.1\r\nHost: x\r\n\r\n";
  11422. sink.write(data.data(), data.size());
  11423. return true;
  11424. },
  11425. "text/plain");
  11426. ASSERT_FALSE(res);
  11427. EXPECT_EQ(Error::Write, res.error());
  11428. EXPECT_FALSE(smuggled);
  11429. }
  11430. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  11431. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  11432. // The compressed path builds the whole body before connecting, so this
  11433. // fails client-side and never reaches a server.
  11434. Client cli(HOST, PORT);
  11435. cli.set_compress(true);
  11436. auto res = cli.Post(
  11437. "/", 1024,
  11438. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  11439. sink.write("hello", 5);
  11440. sink.done(); // short of the 1024 bytes the request announced
  11441. return true;
  11442. },
  11443. "text/plain");
  11444. ASSERT_FALSE(res);
  11445. EXPECT_EQ(Error::Write, res.error());
  11446. }
  11447. #endif
  11448. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  11449. Server svr;
  11450. svr.set_error_handler([](Request const &, Response &res) -> void {
  11451. res.set_chunked_content_provider(
  11452. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11453. sink.os << "hello";
  11454. sink.os << "world";
  11455. sink.done();
  11456. return true;
  11457. });
  11458. });
  11459. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11460. auto se = detail::scope_exit([&] {
  11461. svr.stop();
  11462. listen_thread.join();
  11463. ASSERT_FALSE(svr.is_running());
  11464. });
  11465. svr.wait_until_ready();
  11466. Client cli("localhost", PORT);
  11467. auto res = cli.Get("/");
  11468. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11469. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11470. EXPECT_EQ("helloworld", res->body);
  11471. }
  11472. // A body set after a content provider must replace it, not be sent through it.
  11473. TEST(ResponseContentSourceTest, FileRequestHandlerCanReplaceFile) {
  11474. Server svr;
  11475. svr.set_mount_point("/", "./www");
  11476. svr.set_file_request_handler([](const Request &req, Response &res) {
  11477. if (req.path == "/dir/test.html") {
  11478. res.status = StatusCode::Forbidden_403;
  11479. res.set_content(std::string(5000, 'D'), "text/plain");
  11480. } else if (req.path == "/file") {
  11481. res.status = StatusCode::Forbidden_403;
  11482. res.body = "Denied";
  11483. }
  11484. });
  11485. auto port = svr.bind_to_any_port(HOST);
  11486. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11487. auto se = detail::scope_exit([&] {
  11488. svr.stop();
  11489. t.join();
  11490. ASSERT_FALSE(svr.is_running());
  11491. });
  11492. svr.wait_until_ready();
  11493. Client cli(HOST, port);
  11494. {
  11495. auto res = cli.Get("/dir/test.html");
  11496. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11497. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11498. EXPECT_EQ(std::string(5000, 'D'), res->body);
  11499. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  11500. }
  11501. {
  11502. auto res = cli.Get("/file");
  11503. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11504. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  11505. EXPECT_EQ("Denied", res->body);
  11506. }
  11507. {
  11508. auto res = cli.Get("/dir/index.html");
  11509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11510. EXPECT_EQ(StatusCode::OK_200, res->status);
  11511. EXPECT_EQ(0U, res->body.find("<html>"));
  11512. }
  11513. }
  11514. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  11515. TEST(ResponseContentSourceTest, ErrorAndExceptionHandlersReplaceProvider) {
  11516. Server svr;
  11517. std::vector<bool> released;
  11518. std::mutex released_mutex;
  11519. auto releaser = [&](bool success) {
  11520. std::lock_guard<std::mutex> guard(released_mutex);
  11521. released.push_back(success);
  11522. };
  11523. auto provider = [](size_t offset, size_t length, DataSink &sink) {
  11524. return sink.write(&"hello"[offset], length);
  11525. };
  11526. svr.Get("/sized", [&](const Request &, Response &res) {
  11527. res.status = StatusCode::NotFound_404;
  11528. res.set_content_provider(5, "text/plain", provider, releaser);
  11529. });
  11530. svr.Get("/chunked", [&](const Request &, Response &res) {
  11531. res.status = StatusCode::ServiceUnavailable_503;
  11532. res.set_chunked_content_provider(
  11533. "text/plain",
  11534. [](size_t, DataSink &sink) {
  11535. sink.os << "chunk";
  11536. sink.done();
  11537. return true;
  11538. },
  11539. releaser);
  11540. });
  11541. svr.Get("/throw", [&](const Request &, Response &res) -> void {
  11542. res.set_content_provider(5, "text/plain", provider, releaser);
  11543. throw std::runtime_error("after the provider");
  11544. });
  11545. svr.set_error_handler([](const Request &req, Response &res) {
  11546. // Leave the exception handler's content to it.
  11547. if (req.path == "/throw") { return Server::HandlerResponse::Unhandled; }
  11548. res.set_content(std::string(1000, 'E'), "text/html");
  11549. return Server::HandlerResponse::Handled;
  11550. });
  11551. svr.set_exception_handler(
  11552. [](const Request &, Response &res, std::exception_ptr) {
  11553. res.status = StatusCode::InternalServerError_500;
  11554. res.set_content(std::string(1000, 'X'), "text/html");
  11555. });
  11556. auto port = svr.bind_to_any_port(HOST);
  11557. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11558. auto se = detail::scope_exit([&] {
  11559. svr.stop();
  11560. t.join();
  11561. ASSERT_FALSE(svr.is_running());
  11562. });
  11563. svr.wait_until_ready();
  11564. Client cli(HOST, port);
  11565. {
  11566. auto res = cli.Get("/sized");
  11567. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11568. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  11569. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11570. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  11571. }
  11572. {
  11573. auto res = cli.Get("/chunked");
  11574. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11575. EXPECT_EQ(StatusCode::ServiceUnavailable_503, res->status);
  11576. EXPECT_EQ(std::string(1000, 'E'), res->body);
  11577. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  11578. }
  11579. {
  11580. auto res = cli.Get("/throw");
  11581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11582. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  11583. EXPECT_EQ(std::string(1000, 'X'), res->body);
  11584. }
  11585. std::lock_guard<std::mutex> guard(released_mutex);
  11586. EXPECT_EQ((std::vector<bool>{false, false, false}), released);
  11587. }
  11588. #endif
  11589. TEST(ResponseContentSourceTest, LastContentSetterWins) {
  11590. Server svr;
  11591. auto abc = [](size_t offset, size_t length, DataSink &sink) {
  11592. return sink.write(&"abc"[offset], length);
  11593. };
  11594. svr.Get("/file-then-body", [](const Request &, Response &res) {
  11595. res.set_file_content("./www/dir/test.html");
  11596. res.set_content("body", "text/plain");
  11597. });
  11598. svr.Get("/body-then-file", [](const Request &, Response &res) {
  11599. res.set_content(std::string(100, 'B'), "text/plain");
  11600. res.set_file_content("./www/dir/test.html");
  11601. });
  11602. svr.Get("/body-then-provider", [&](const Request &, Response &res) {
  11603. res.set_content(std::string(100, 'B'), "text/plain");
  11604. res.set_content_provider(3, "text/x-provider", abc);
  11605. });
  11606. svr.Get("/provider-then-body", [&](const Request &, Response &res) {
  11607. res.set_content_provider(3, "text/x-provider", abc);
  11608. res.set_content(std::string(100, 'B'), "text/plain");
  11609. });
  11610. svr.Get("/provider-then-file", [&](const Request &, Response &res) {
  11611. res.set_content_provider(3, "text/x-provider", abc);
  11612. res.set_file_content("./www/dir/test.html", "text/x-file");
  11613. });
  11614. svr.Get("/file-then-header", [](const Request &, Response &res) {
  11615. res.set_file_content("./www/dir/test.html");
  11616. res.set_header("Content-Type", "text/x-handler");
  11617. });
  11618. svr.Get("/provider-then-direct-body", [&](const Request &, Response &res) {
  11619. res.set_content_provider(3, "text/plain", abc);
  11620. res.body = "direct";
  11621. });
  11622. svr.Get("/file-then-direct-body", [](const Request &, Response &res) {
  11623. res.set_file_content("./www/dir/test.html");
  11624. res.body = "direct";
  11625. });
  11626. auto port = svr.bind_to_any_port(HOST);
  11627. auto t = std::thread([&]() { svr.listen_after_bind(); });
  11628. auto se = detail::scope_exit([&] {
  11629. svr.stop();
  11630. t.join();
  11631. ASSERT_FALSE(svr.is_running());
  11632. });
  11633. svr.wait_until_ready();
  11634. Client cli(HOST, port);
  11635. auto expect_body = [&](const char *path, const std::string &body,
  11636. const std::string &type) {
  11637. // Uncompressed, so Content-Length can be compared with the body.
  11638. auto res = cli.Get(path, Headers{{"Accept-Encoding", ""}});
  11639. ASSERT_TRUE(res) << path << " Error: " << to_string(res.error());
  11640. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  11641. EXPECT_EQ(body, res->body) << path;
  11642. EXPECT_EQ(std::to_string(body.size()),
  11643. res->get_header_value("Content-Length"))
  11644. << path;
  11645. EXPECT_EQ(1u, res->get_header_value_count("Content-Type")) << path;
  11646. EXPECT_EQ(type, res->get_header_value("Content-Type")) << path;
  11647. };
  11648. expect_body("/file-then-body", "body", "text/plain");
  11649. expect_body("/body-then-file", "test.html", "text/html");
  11650. expect_body("/body-then-provider", "abc", "text/x-provider");
  11651. expect_body("/provider-then-body", std::string(100, 'B'), "text/plain");
  11652. expect_body("/provider-then-file", "test.html", "text/x-file");
  11653. expect_body("/file-then-header", "test.html", "text/x-handler");
  11654. expect_body("/provider-then-direct-body", "direct", "text/plain");
  11655. expect_body("/file-then-direct-body", "direct", "text/plain");
  11656. // Ranges are checked against the body, not the dropped provider.
  11657. {
  11658. auto res = cli.Get("/provider-then-direct-body",
  11659. Headers{{make_range_header({{1, 2}})}});
  11660. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11661. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11662. EXPECT_EQ("ir", res->body);
  11663. }
  11664. {
  11665. auto res = cli.Get("/file-then-direct-body",
  11666. Headers{{make_range_header({{7, 8}})}});
  11667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11668. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  11669. }
  11670. }
  11671. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  11672. TEST(FileContentTest, TruncatedWhileServedEndsTheResponse) {
  11673. const char *path = "./truncated_while_served.txt";
  11674. const size_t size = 32 * 1024 * 1024;
  11675. {
  11676. std::ofstream f(path, std::ios::binary);
  11677. f << std::string(size, 'x');
  11678. }
  11679. auto se_file = detail::scope_exit([&] { std::remove(path); });
  11680. // Over TLS, where the bytes are encrypted in this process rather than
  11681. // copied by send().
  11682. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11683. svr.Get("/file", [&](const Request &, Response &res) {
  11684. res.set_file_content(path, "text/plain");
  11685. });
  11686. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  11687. auto se = detail::scope_exit([&] {
  11688. svr.stop();
  11689. thread.join();
  11690. ASSERT_FALSE(svr.is_running());
  11691. });
  11692. svr.wait_until_ready();
  11693. // The file shrinks once the first bytes are in, as a rewrite in place
  11694. // would, and reading the mapping past its new end used to raise SIGBUS.
  11695. SSLClient cli(HOST, PORT);
  11696. cli.enable_server_certificate_verification(false);
  11697. size_t received = 0;
  11698. auto res = cli.Get("/file", [&](const char *, size_t len) {
  11699. if (received == 0) { EXPECT_EQ(0, ::truncate(path, 0)); }
  11700. received += len;
  11701. return true;
  11702. });
  11703. EXPECT_FALSE(res);
  11704. EXPECT_LT(received, size);
  11705. }
  11706. #endif
  11707. // Forward declaration (see the base64_encode note).
  11708. namespace httplib {
  11709. namespace detail {
  11710. void set_file_content_provider(Response &res, const std::shared_ptr<mmap> &m,
  11711. const std::string &content_type,
  11712. EncodingType encoding);
  11713. } // namespace detail
  11714. } // namespace httplib
  11715. TEST(ResponseContentSourceTest, FileContentProviderStaysWithinFile) {
  11716. auto mm = std::make_shared<detail::mmap>("./www/dir/test.html");
  11717. ASSERT_TRUE(mm->is_open());
  11718. Response res;
  11719. detail::set_file_content_provider(res, mm, "text/html",
  11720. detail::EncodingType::None);
  11721. std::string out;
  11722. DataSink sink;
  11723. sink.write = [&](const char *d, size_t l) {
  11724. out.append(d, l);
  11725. return true;
  11726. };
  11727. EXPECT_TRUE(res.content_provider_(0, mm->size() + 4096, sink));
  11728. EXPECT_EQ("test.html", out);
  11729. EXPECT_FALSE(res.content_provider_(mm->size(), 1, sink));
  11730. EXPECT_EQ("test.html", out);
  11731. }
  11732. TEST(LongPollingTest, ClientCloseDetection) {
  11733. Server svr;
  11734. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11735. res.set_chunked_content_provider(
  11736. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11737. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11738. sink.os << "hello";
  11739. auto count = 10;
  11740. while (count > 0 && sink.is_writable()) {
  11741. this_thread::sleep_for(chrono::milliseconds(10));
  11742. count--;
  11743. }
  11744. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  11745. return true;
  11746. });
  11747. });
  11748. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11749. auto se = detail::scope_exit([&] {
  11750. svr.stop();
  11751. listen_thread.join();
  11752. ASSERT_FALSE(svr.is_running());
  11753. });
  11754. svr.wait_until_ready();
  11755. Client cli("localhost", PORT);
  11756. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11757. EXPECT_EQ("hello", string(data, data_length));
  11758. return false; // close the socket immediately.
  11759. });
  11760. ASSERT_FALSE(res);
  11761. }
  11762. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  11763. Server svr;
  11764. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  11765. res.set_chunked_content_provider(
  11766. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  11767. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  11768. sink.os << "hello";
  11769. EXPECT_TRUE(sink.os.good());
  11770. // Wait for the client to close the connection
  11771. auto count = 10;
  11772. while (count > 0 && sink.is_writable()) {
  11773. this_thread::sleep_for(chrono::milliseconds(10));
  11774. count--;
  11775. }
  11776. // After client disconnect, write repeatedly until the socket
  11777. // write actually fails (small writes may be absorbed by the
  11778. // kernel buffer)
  11779. std::string chunk(1024, 'x');
  11780. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  11781. sink.os << chunk;
  11782. }
  11783. EXPECT_TRUE(sink.os.fail());
  11784. return true;
  11785. });
  11786. });
  11787. auto port = svr.bind_to_any_port("localhost");
  11788. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11789. auto se = detail::scope_exit([&] {
  11790. svr.stop();
  11791. listen_thread.join();
  11792. ASSERT_FALSE(svr.is_running());
  11793. });
  11794. svr.wait_until_ready();
  11795. Client cli("localhost", port);
  11796. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  11797. EXPECT_EQ("hello", string(data, data_length));
  11798. return false; // close the socket immediately.
  11799. });
  11800. ASSERT_FALSE(res);
  11801. }
  11802. TEST(GetWithParametersTest, GetWithParameters) {
  11803. Server svr;
  11804. svr.Get("/", [&](const Request &req, Response &) {
  11805. EXPECT_EQ("world", req.get_param_value("hello"));
  11806. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11807. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11808. });
  11809. svr.Get("/params", [&](const Request &req, Response &) {
  11810. EXPECT_EQ("world", req.get_param_value("hello"));
  11811. EXPECT_EQ("world2", req.get_param_value("hello2"));
  11812. EXPECT_EQ("world3", req.get_param_value("hello3"));
  11813. });
  11814. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  11815. EXPECT_EQ("resource-id", req.matches[1]);
  11816. EXPECT_EQ("foo", req.get_param_value("param1"));
  11817. EXPECT_EQ("bar", req.get_param_value("param2"));
  11818. });
  11819. svr.Get("/users/:id", [&](const Request &req, Response &) {
  11820. EXPECT_EQ("user-id", req.path_params.at("id"));
  11821. EXPECT_EQ("foo", req.get_param_value("param1"));
  11822. EXPECT_EQ("bar", req.get_param_value("param2"));
  11823. });
  11824. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  11825. auto se = detail::scope_exit([&] {
  11826. svr.stop();
  11827. listen_thread.join();
  11828. ASSERT_FALSE(svr.is_running());
  11829. });
  11830. svr.wait_until_ready();
  11831. {
  11832. Client cli(HOST, PORT);
  11833. Params params;
  11834. params.emplace("hello", "world");
  11835. params.emplace("hello2", "world2");
  11836. params.emplace("hello3", "world3");
  11837. auto res = cli.Get("/", params, Headers{});
  11838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11839. EXPECT_EQ(StatusCode::OK_200, res->status);
  11840. }
  11841. {
  11842. Client cli(HOST, PORT);
  11843. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  11844. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11845. EXPECT_EQ(StatusCode::OK_200, res->status);
  11846. }
  11847. {
  11848. Client cli(HOST, PORT);
  11849. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  11850. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11851. EXPECT_EQ(StatusCode::OK_200, res->status);
  11852. }
  11853. {
  11854. Client cli(HOST, PORT);
  11855. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  11856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11857. EXPECT_EQ(StatusCode::OK_200, res->status);
  11858. }
  11859. }
  11860. TEST(GetWithParametersTest, GetWithParameters2) {
  11861. Server svr;
  11862. svr.Get("/", [&](const Request &req, Response &res) {
  11863. auto text = req.get_param_value("hello");
  11864. res.set_content(text, "text/plain");
  11865. });
  11866. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11867. auto se = detail::scope_exit([&] {
  11868. svr.stop();
  11869. listen_thread.join();
  11870. ASSERT_FALSE(svr.is_running());
  11871. });
  11872. svr.wait_until_ready();
  11873. Client cli("localhost", PORT);
  11874. Params params;
  11875. params.emplace("hello", "world");
  11876. std::string body;
  11877. auto res = cli.Get("/", params, Headers{},
  11878. [&](const char *data, size_t data_length) {
  11879. body.append(data, data_length);
  11880. return true;
  11881. });
  11882. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11883. EXPECT_EQ(StatusCode::OK_200, res->status);
  11884. EXPECT_EQ("world", body);
  11885. }
  11886. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  11887. Server svr;
  11888. svr.Get("/search", [&](const Request &req, Response &res) {
  11889. auto q = req.get_param_value("q");
  11890. res.set_content(q, "text/plain");
  11891. });
  11892. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11893. auto se = detail::scope_exit([&] {
  11894. svr.stop();
  11895. listen_thread.join();
  11896. ASSERT_FALSE(svr.is_running());
  11897. });
  11898. svr.wait_until_ready();
  11899. Client cli("localhost", PORT);
  11900. // Verify that Get(path, params) works without requiring Headers argument
  11901. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  11902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11903. EXPECT_EQ(StatusCode::OK_200, res->status);
  11904. EXPECT_EQ("cpp-httplib", res->body);
  11905. }
  11906. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  11907. auto host = "httpbingo.org";
  11908. auto path = std::string{"/range/32"};
  11909. #ifdef CPPHTTPLIB_SSL_ENABLED
  11910. SSLClient cli(host);
  11911. #else
  11912. Client cli(host);
  11913. #endif
  11914. cli.set_default_headers({make_range_header({{1, 10}})});
  11915. cli.set_connection_timeout(5);
  11916. {
  11917. auto res = cli.Get(path);
  11918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11919. EXPECT_EQ("bcdefghijk", res->body);
  11920. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11921. }
  11922. {
  11923. auto res = cli.Get(path);
  11924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11925. EXPECT_EQ("bcdefghijk", res->body);
  11926. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  11927. }
  11928. }
  11929. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  11930. Server svr;
  11931. svr.set_default_headers({{"Hello", "World"}});
  11932. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  11933. res.set_content("ok", "text/plain");
  11934. });
  11935. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11936. auto se = detail::scope_exit([&] {
  11937. svr.stop();
  11938. listen_thread.join();
  11939. ASSERT_FALSE(svr.is_running());
  11940. });
  11941. svr.wait_until_ready();
  11942. Client cli("localhost", PORT);
  11943. auto res = cli.Get("/");
  11944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11945. EXPECT_EQ(StatusCode::OK_200, res->status);
  11946. EXPECT_EQ("ok", res->body);
  11947. EXPECT_EQ("World", res->get_header_value("Hello"));
  11948. }
  11949. #ifdef CPPHTTPLIB_SSL_ENABLED
  11950. TEST(KeepAliveTest, ReadTimeoutSSL) {
  11951. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11952. ASSERT_TRUE(svr.is_valid());
  11953. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  11954. std::this_thread::sleep_for(std::chrono::seconds(2));
  11955. res.set_content("a", "text/plain");
  11956. });
  11957. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  11958. res.set_content("b", "text/plain");
  11959. });
  11960. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  11961. auto se = detail::scope_exit([&] {
  11962. svr.stop();
  11963. listen_thread.join();
  11964. ASSERT_FALSE(svr.is_running());
  11965. });
  11966. svr.wait_until_ready();
  11967. SSLClient cli("localhost", PORT);
  11968. cli.enable_server_certificate_verification(false);
  11969. cli.set_keep_alive(true);
  11970. cli.set_read_timeout(std::chrono::seconds(1));
  11971. auto resa = cli.Get("/a");
  11972. ASSERT_TRUE(!resa);
  11973. EXPECT_EQ(Error::Read, resa.error());
  11974. auto resb = cli.Get("/b");
  11975. ASSERT_TRUE(resb);
  11976. EXPECT_EQ(StatusCode::OK_200, resb->status);
  11977. EXPECT_EQ("b", resb->body);
  11978. }
  11979. // Closing an idle keep-alive connection sends close_notify and returns. The
  11980. // server must not wait for the client's close_notify: an idle client never
  11981. // sends one, so the worker would be held until the read timeout expires, and
  11982. // stop() would wait for it.
  11983. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  11984. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  11985. ASSERT_TRUE(svr.is_valid());
  11986. svr.set_keep_alive_timeout(1);
  11987. svr.set_read_timeout(10, 0);
  11988. svr.Get("/", [](const Request &, Response &res) {
  11989. res.set_content("ok", "text/plain");
  11990. });
  11991. auto port = svr.bind_to_any_port(HOST);
  11992. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  11993. auto se = detail::scope_exit([&] {
  11994. if (listen_thread.joinable()) {
  11995. svr.stop();
  11996. listen_thread.join();
  11997. }
  11998. });
  11999. svr.wait_until_ready();
  12000. SSLClient cli(HOST, port);
  12001. cli.enable_server_certificate_verification(false);
  12002. cli.set_keep_alive(true);
  12003. auto res = cli.Get("/");
  12004. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12005. EXPECT_EQ(StatusCode::OK_200, res->status);
  12006. // Stay idle past the keep-alive timeout so the server closes the connection.
  12007. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  12008. auto start = std::chrono::steady_clock::now();
  12009. svr.stop();
  12010. listen_thread.join();
  12011. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  12012. std::chrono::steady_clock::now() - start)
  12013. .count();
  12014. EXPECT_LT(elapsed, 3000);
  12015. }
  12016. #endif
  12017. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  12018. protected:
  12019. ServerTestWithAI_PASSIVE()
  12020. : cli_(HOST, PORT)
  12021. #ifdef CPPHTTPLIB_SSL_ENABLED
  12022. ,
  12023. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12024. #endif
  12025. {
  12026. #ifdef CPPHTTPLIB_SSL_ENABLED
  12027. cli_.enable_server_certificate_verification(false);
  12028. #endif
  12029. }
  12030. virtual void SetUp() {
  12031. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  12032. res.set_content("Hello World!", "text/plain");
  12033. });
  12034. t_ = thread(
  12035. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  12036. svr_.wait_until_ready();
  12037. }
  12038. virtual void TearDown() {
  12039. svr_.stop();
  12040. t_.join();
  12041. }
  12042. #ifdef CPPHTTPLIB_SSL_ENABLED
  12043. SSLClient cli_;
  12044. SSLServer svr_;
  12045. #else
  12046. Client cli_;
  12047. Server svr_;
  12048. #endif
  12049. thread t_;
  12050. };
  12051. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  12052. auto res = cli_.Get("/hi");
  12053. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12054. EXPECT_EQ(StatusCode::OK_200, res->status);
  12055. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  12056. EXPECT_EQ("Hello World!", res->body);
  12057. }
  12058. class ServerUpDownTest : public ::testing::Test {
  12059. protected:
  12060. ServerUpDownTest() : cli_(HOST, PORT) {}
  12061. virtual void SetUp() {
  12062. t_ = thread([&]() {
  12063. svr_.bind_to_any_port(HOST);
  12064. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  12065. ASSERT_TRUE(svr_.listen_after_bind());
  12066. });
  12067. svr_.wait_until_ready();
  12068. }
  12069. virtual void TearDown() {
  12070. svr_.stop();
  12071. t_.join();
  12072. }
  12073. Client cli_;
  12074. Server svr_;
  12075. thread t_;
  12076. };
  12077. TEST_F(ServerUpDownTest, QuickStartStop) {
  12078. // Should not crash, especially when run with
  12079. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  12080. }
  12081. class PayloadMaxLengthTest : public ::testing::Test {
  12082. protected:
  12083. PayloadMaxLengthTest()
  12084. : cli_(HOST, PORT)
  12085. #ifdef CPPHTTPLIB_SSL_ENABLED
  12086. ,
  12087. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12088. #endif
  12089. {
  12090. #ifdef CPPHTTPLIB_SSL_ENABLED
  12091. cli_.enable_server_certificate_verification(false);
  12092. #endif
  12093. }
  12094. virtual void SetUp() {
  12095. svr_.set_payload_max_length(8);
  12096. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12097. res.set_content("test", "text/plain");
  12098. });
  12099. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12100. svr_.wait_until_ready();
  12101. }
  12102. virtual void TearDown() {
  12103. svr_.stop();
  12104. t_.join();
  12105. }
  12106. #ifdef CPPHTTPLIB_SSL_ENABLED
  12107. SSLClient cli_;
  12108. SSLServer svr_;
  12109. #else
  12110. Client cli_;
  12111. Server svr_;
  12112. #endif
  12113. thread t_;
  12114. };
  12115. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  12116. auto res = cli_.Post("/test", "123456789", "text/plain");
  12117. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12118. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12119. res = cli_.Post("/test", "12345678", "text/plain");
  12120. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12121. EXPECT_EQ(StatusCode::OK_200, res->status);
  12122. }
  12123. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  12124. // Test chunked encoding with payload exceeding the 8-byte limit
  12125. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  12126. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  12127. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12128. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12129. }
  12130. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  12131. // Test chunked encoding with payload within the 8-byte limit
  12132. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  12133. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  12134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12135. EXPECT_EQ(StatusCode::OK_200, res->status);
  12136. }
  12137. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  12138. // Test using send_request to send chunked data exceeding payload limit
  12139. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  12140. "Host: " +
  12141. std::string(HOST) + ":" + std::to_string(PORT) +
  12142. "\r\n"
  12143. "Transfer-Encoding: chunked\r\n"
  12144. "Connection: close\r\n"
  12145. "\r\n"
  12146. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  12147. "0123456789\r\n"
  12148. "0\r\n" // End chunk
  12149. "\r\n";
  12150. std::string response;
  12151. bool result = send_request(1, chunked_request, &response);
  12152. if (!result) {
  12153. // If send_request fails, it might be because the server closed the
  12154. // connection due to payload limit enforcement, which is acceptable
  12155. SUCCEED()
  12156. << "Server rejected oversized chunked request (connection closed)";
  12157. } else {
  12158. // If we got a response, check if it's an error response or connection was
  12159. // closed early Short response length indicates connection was closed due to
  12160. // payload limit
  12161. if (response.length() <= 10) {
  12162. SUCCEED() << "Server closed connection for oversized chunked request";
  12163. } else {
  12164. // Check for error status codes
  12165. EXPECT_TRUE(response.find("413") != std::string::npos ||
  12166. response.find("Payload Too Large") != std::string::npos ||
  12167. response.find("400") != std::string::npos);
  12168. }
  12169. }
  12170. }
  12171. class LargePayloadMaxLengthTest : public ::testing::Test {
  12172. protected:
  12173. LargePayloadMaxLengthTest()
  12174. : cli_(HOST, PORT)
  12175. #ifdef CPPHTTPLIB_SSL_ENABLED
  12176. ,
  12177. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  12178. #endif
  12179. {
  12180. #ifdef CPPHTTPLIB_SSL_ENABLED
  12181. cli_.enable_server_certificate_verification(false);
  12182. #endif
  12183. }
  12184. virtual void SetUp() {
  12185. // Set 10MB payload limit
  12186. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  12187. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  12188. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  12189. res.set_content("Large payload test", "text/plain");
  12190. });
  12191. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  12192. svr_.wait_until_ready();
  12193. }
  12194. virtual void TearDown() {
  12195. svr_.stop();
  12196. t_.join();
  12197. }
  12198. #ifdef CPPHTTPLIB_SSL_ENABLED
  12199. SSLClient cli_;
  12200. SSLServer svr_;
  12201. #else
  12202. Client cli_;
  12203. Server svr_;
  12204. #endif
  12205. thread t_;
  12206. };
  12207. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  12208. // Test chunked encoding with payload within 10MB limit
  12209. std::string medium_payload(5 * 1024 * 1024,
  12210. 'A'); // 5MB payload, within 10MB limit
  12211. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  12212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12213. EXPECT_EQ(StatusCode::OK_200, res->status);
  12214. }
  12215. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  12216. // Test chunked encoding with payload exceeding 10MB limit
  12217. std::string large_payload(12 * 1024 * 1024,
  12218. 'B'); // 12MB payload, exceeds 10MB limit
  12219. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  12220. // Server may either return 413 or close the connection
  12221. if (res) {
  12222. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12223. } else {
  12224. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  12225. }
  12226. }
  12227. TEST(ClientPayloadTest, DoesNotReserveTheClaimedLength) {
  12228. Server svr;
  12229. svr.Get("/", [](const Request &, Response &res) {
  12230. // Claims the most the client accepts, far more than it sends, then drops
  12231. // the connection.
  12232. res.set_content_provider(std::string().max_size(), "text/plain",
  12233. [](size_t, size_t, DataSink &sink) {
  12234. sink.write("abc", 3);
  12235. return false;
  12236. });
  12237. });
  12238. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12239. auto se = detail::scope_exit([&] {
  12240. svr.stop();
  12241. thread.join();
  12242. ASSERT_FALSE(svr.is_running());
  12243. });
  12244. svr.wait_until_ready();
  12245. Client cli(HOST, PORT);
  12246. cli.set_payload_max_length(0);
  12247. EXPECT_FALSE(cli.Get("/"));
  12248. }
  12249. // A response body over the limit is reported as ExceedMaxPayloadSize, as the
  12250. // Stream API does, not as a plain read failure
  12251. TEST(ClientPayloadTest, OverLimitIsExceedMaxPayloadSize) {
  12252. Server svr;
  12253. svr.Get("/big", [](const Request &, Response &res) {
  12254. res.set_content(std::string(100000, 'b'), "text/plain");
  12255. });
  12256. auto port = svr.bind_to_any_port(HOST);
  12257. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12258. auto se = detail::scope_exit([&] {
  12259. svr.stop();
  12260. thread.join();
  12261. });
  12262. svr.wait_until_ready();
  12263. Client cli(HOST, port);
  12264. cli.set_payload_max_length(1000);
  12265. auto res = cli.Get("/big", Headers{{"Accept-Encoding", ""}});
  12266. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12267. res = cli.Get("/big", Headers{{"Accept-Encoding", ""}},
  12268. [](const char *, size_t) { return true; });
  12269. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12270. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12271. // Small on the wire, over the limit once decompressed
  12272. res = cli.Get("/big", Headers{{"Accept-Encoding", "gzip"}});
  12273. EXPECT_EQ(Error::ExceedMaxPayloadSize, res.error());
  12274. #endif
  12275. }
  12276. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12277. // `payload_max_length` is not enforced on decompressed body in ContentReader
  12278. // path.
  12279. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  12280. Server svr;
  12281. const size_t LIMIT = 64 * 1024; // 64KB
  12282. svr.set_payload_max_length(LIMIT);
  12283. size_t total = 0;
  12284. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  12285. const ContentReader &content_reader) {
  12286. content_reader([&](const char * /*data*/, size_t len) {
  12287. total += len;
  12288. return true;
  12289. });
  12290. res.status = 200;
  12291. res.set_content("stream_ok", "text/plain");
  12292. });
  12293. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  12294. auto se = detail::scope_exit([&] {
  12295. svr.stop();
  12296. thread.join();
  12297. ASSERT_FALSE(svr.is_running());
  12298. });
  12299. svr.wait_until_ready();
  12300. // Prepare 256KB raw data and gzip-compress it
  12301. std::string raw(256 * 1024, 'A');
  12302. std::string gz;
  12303. {
  12304. z_stream zs{};
  12305. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  12306. Z_DEFAULT_STRATEGY);
  12307. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  12308. zs.avail_in = static_cast<uInt>(raw.size());
  12309. char outbuf[4096];
  12310. int ret;
  12311. do {
  12312. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  12313. zs.avail_out = sizeof(outbuf);
  12314. ret = deflate(&zs, Z_FINISH);
  12315. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  12316. } while (ret != Z_STREAM_END);
  12317. deflateEnd(&zs);
  12318. }
  12319. Client cli(HOST, PORT);
  12320. cli.set_connection_timeout(std::chrono::seconds(5));
  12321. Headers headers = {{"Content-Encoding", "gzip"}};
  12322. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  12323. "application/octet-stream");
  12324. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12325. // Server must reject oversized decompressed payloads with 413.
  12326. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  12327. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  12328. EXPECT_LE(total, LIMIT);
  12329. }
  12330. #endif
  12331. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  12332. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  12333. // the payload must be passed through untouched instead of being rejected.
  12334. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  12335. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12336. Server svr;
  12337. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  12338. res.set_content(body, "image/jpeg");
  12339. res.set_header("Content-Encoding", "UTF-8");
  12340. });
  12341. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  12342. res.set_content(body, "image/jpeg");
  12343. res.set_header("Content-Encoding", "identity");
  12344. });
  12345. svr.Post("/echo", [](const Request &req, Response &res) {
  12346. res.set_content(req.body, "image/jpeg");
  12347. });
  12348. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12349. auto se = detail::scope_exit([&] {
  12350. svr.stop();
  12351. t.join();
  12352. ASSERT_FALSE(svr.is_running());
  12353. });
  12354. svr.wait_until_ready();
  12355. Client cli(HOST, PORT);
  12356. {
  12357. auto res = cli.Get("/image");
  12358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12359. EXPECT_EQ(StatusCode::OK_200, res->status);
  12360. EXPECT_EQ(body, res->body);
  12361. }
  12362. {
  12363. auto res = cli.Get("/identity");
  12364. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12365. EXPECT_EQ(StatusCode::OK_200, res->status);
  12366. EXPECT_EQ(body, res->body);
  12367. }
  12368. {
  12369. // The same applies to a request body reaching the server.
  12370. Headers headers = {{"Content-Encoding", "UTF-8"}};
  12371. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  12372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12373. EXPECT_EQ(StatusCode::OK_200, res->status);
  12374. EXPECT_EQ(body, res->body);
  12375. }
  12376. }
  12377. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  12378. // gzip-encoded response even when the build has no zlib support.
  12379. static const char GZIPPED_HELLO_WORLD[] = {
  12380. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  12381. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  12382. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  12383. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  12384. // A content coding is a whole token, not something the field value merely
  12385. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  12386. // as "fibre" look like Brotli, and turned a multi-coding value like
  12387. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  12388. // it was never meant to see.
  12389. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  12390. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12391. Server svr;
  12392. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  12393. res.set_content(body, "image/jpeg");
  12394. res.set_header("Content-Encoding", "fibre");
  12395. });
  12396. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  12397. res.set_content(body, "image/jpeg");
  12398. res.set_header("Content-Encoding", "gzip, br");
  12399. });
  12400. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  12401. res.set_content(body, "image/jpeg");
  12402. res.set_header("Content-Encoding", "x-zstd-ish");
  12403. });
  12404. auto port = svr.bind_to_any_port(HOST);
  12405. thread t = thread([&]() { svr.listen_after_bind(); });
  12406. auto se = detail::scope_exit([&] {
  12407. svr.stop();
  12408. t.join();
  12409. ASSERT_FALSE(svr.is_running());
  12410. });
  12411. svr.wait_until_ready();
  12412. Client cli(HOST, port);
  12413. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  12414. auto res = cli.Get(path);
  12415. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12416. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12417. // Not a coding we recognize, so the payload comes back untouched
  12418. EXPECT_EQ(body, res->body) << path;
  12419. }
  12420. }
  12421. // A content coding cpp-httplib recognizes but was not built with must be
  12422. // reported as such. Handing the still-compressed payload back to the caller
  12423. // would silently corrupt it.
  12424. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  12425. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12426. Server svr;
  12427. // "image/jpeg" keeps the server from applying a content coding of its own,
  12428. // so the hand-crafted Content-Encoding below survives.
  12429. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  12430. res.set_content(gzipped, "image/jpeg");
  12431. res.set_header("Content-Encoding", "gzip");
  12432. });
  12433. // Content codings are case-insensitive (RFC 9110 8.4.1).
  12434. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  12435. res.set_content(gzipped, "image/jpeg");
  12436. res.set_header("Content-Encoding", "GZIP");
  12437. });
  12438. thread t = thread([&]() { svr.listen(HOST, PORT); });
  12439. auto se = detail::scope_exit([&] {
  12440. svr.stop();
  12441. t.join();
  12442. ASSERT_FALSE(svr.is_running());
  12443. });
  12444. svr.wait_until_ready();
  12445. Client cli(HOST, PORT);
  12446. {
  12447. auto res = cli.Get("/gzipped");
  12448. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12449. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12450. EXPECT_EQ("Hello World!", res->body);
  12451. #else
  12452. ASSERT_FALSE(res);
  12453. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12454. #endif
  12455. }
  12456. {
  12457. // open_stream() must behave the same way.
  12458. auto handle = cli.open_stream("GET", "/gzipped");
  12459. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12460. ASSERT_TRUE(handle.is_valid());
  12461. std::string received;
  12462. char buf[256];
  12463. ssize_t n;
  12464. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  12465. received.append(buf, static_cast<size_t>(n));
  12466. }
  12467. EXPECT_EQ("Hello World!", received);
  12468. #else
  12469. EXPECT_FALSE(handle.is_valid());
  12470. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  12471. #endif
  12472. }
  12473. {
  12474. // A differently-cased coding must not be mistaken for an unknown one, or
  12475. // the body would be handed back still compressed.
  12476. auto res = cli.Get("/gzipped-uppercase");
  12477. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12478. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12479. EXPECT_EQ("Hello World!", res->body);
  12480. #else
  12481. ASSERT_FALSE(res);
  12482. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  12483. #endif
  12484. }
  12485. }
  12486. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  12487. // A handler serving pre-compressed content (e.g. build-time gzipped static
  12488. // assets) sets Content-Encoding itself. The server used to pick a coding from
  12489. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  12490. // body a second time and appending a second Content-Encoding field line, so
  12491. // clients that decode one coding per listed value handed back raw gzip bytes.
  12492. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  12493. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12494. Server svr;
  12495. // text/plain is a compressible type, so only the pre-set Content-Encoding
  12496. // keeps the server from applying a coding of its own.
  12497. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12498. res.set_content(gzipped, "text/plain");
  12499. res.set_header("Content-Encoding", "gzip");
  12500. });
  12501. auto port = svr.bind_to_any_port(HOST);
  12502. thread t = thread([&]() { svr.listen_after_bind(); });
  12503. auto se = detail::scope_exit([&] {
  12504. svr.stop();
  12505. t.join();
  12506. ASSERT_FALSE(svr.is_running());
  12507. });
  12508. svr.wait_until_ready();
  12509. Client cli(HOST, port);
  12510. Headers headers = {{"Accept-Encoding", "gzip"}};
  12511. auto res = cli.Get("/pre-gzipped", headers);
  12512. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12513. EXPECT_EQ(StatusCode::OK_200, res->status);
  12514. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12515. EXPECT_EQ("Hello World!", res->body);
  12516. }
  12517. // set_compress(false) sends every handler response as it is, buffered or
  12518. // streamed
  12519. TEST(ContentEncodingTest, SetCompressFalseSendsIdentity) {
  12520. const std::string text(1000, 'a');
  12521. Server svr;
  12522. svr.set_compress(false);
  12523. svr.Get("/buffered", [&](const Request &, Response &res) {
  12524. res.set_content(text, "text/plain");
  12525. });
  12526. svr.Get("/streamed", [&](const Request &, Response &res) {
  12527. res.set_chunked_content_provider("text/plain", [&](size_t, DataSink &sink) {
  12528. sink.write(text.data(), text.size());
  12529. sink.done();
  12530. return true;
  12531. });
  12532. });
  12533. auto port = svr.bind_to_any_port(HOST);
  12534. ASSERT_LT(0, port);
  12535. thread t = thread([&] { svr.listen_after_bind(); });
  12536. auto se = detail::scope_exit([&] {
  12537. svr.stop();
  12538. t.join();
  12539. ASSERT_FALSE(svr.is_running());
  12540. });
  12541. svr.wait_until_ready();
  12542. Client cli(HOST, port);
  12543. cli.set_decompress(false);
  12544. for (auto path : {"/buffered", "/streamed"}) {
  12545. SCOPED_TRACE(path);
  12546. auto res = cli.Get(path, Headers{{"Accept-Encoding", "gzip"}});
  12547. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12548. EXPECT_FALSE(res->has_header("Content-Encoding"));
  12549. EXPECT_EQ(text, res->body);
  12550. }
  12551. }
  12552. // A chunked provider settles its coding where the headers are written and
  12553. // reuses it at write time. Both ends of that have to hold: a handler's own
  12554. // Content-Encoding suppresses the coding, and a response without one is still
  12555. // compressed as it always was.
  12556. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  12557. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  12558. const std::string plain = "Hello World! Hello World! Hello World!";
  12559. Server svr;
  12560. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  12561. res.set_header("Content-Encoding", "gzip");
  12562. res.set_chunked_content_provider(
  12563. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  12564. sink.write(gzipped.data(), gzipped.size());
  12565. sink.done();
  12566. return true;
  12567. });
  12568. });
  12569. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  12570. res.set_chunked_content_provider(
  12571. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  12572. sink.write(plain.data(), plain.size());
  12573. sink.done();
  12574. return true;
  12575. });
  12576. });
  12577. auto port = svr.bind_to_any_port(HOST);
  12578. thread t = thread([&]() { svr.listen_after_bind(); });
  12579. auto se = detail::scope_exit([&] {
  12580. svr.stop();
  12581. t.join();
  12582. ASSERT_FALSE(svr.is_running());
  12583. });
  12584. svr.wait_until_ready();
  12585. Client cli(HOST, port);
  12586. Headers headers = {{"Accept-Encoding", "gzip"}};
  12587. {
  12588. auto res = cli.Get("/pre-gzipped", headers);
  12589. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12590. EXPECT_EQ(StatusCode::OK_200, res->status);
  12591. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  12592. EXPECT_EQ("Hello World!", res->body);
  12593. }
  12594. {
  12595. auto res = cli.Get("/negotiated", headers);
  12596. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12597. EXPECT_EQ(StatusCode::OK_200, res->status);
  12598. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  12599. EXPECT_EQ(plain, res->body);
  12600. }
  12601. }
  12602. #endif
  12603. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  12604. // the same message as the comma-joined one, so both have to be read the same
  12605. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  12606. // single gzip coding, and a body the sender says was encoded twice was handed
  12607. // back after one pass, still compressed but presented as decoded.
  12608. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  12609. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  12610. Server svr;
  12611. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  12612. res.set_content(body, "image/jpeg");
  12613. res.headers.emplace("Content-Encoding", "gzip");
  12614. res.headers.emplace("Content-Encoding", "gzip");
  12615. });
  12616. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  12617. res.set_content(body, "image/jpeg");
  12618. res.set_header("Content-Encoding", "gzip, gzip");
  12619. });
  12620. auto port = svr.bind_to_any_port(HOST);
  12621. thread t = thread([&]() { svr.listen_after_bind(); });
  12622. auto se = detail::scope_exit([&] {
  12623. svr.stop();
  12624. t.join();
  12625. ASSERT_FALSE(svr.is_running());
  12626. });
  12627. svr.wait_until_ready();
  12628. Client cli(HOST, port);
  12629. // Two codings is not something cpp-httplib decodes, so both representations
  12630. // take the pass-through path rather than one of them being gunzipped once.
  12631. for (const char *path : {"/split", "/joined"}) {
  12632. auto res = cli.Get(path);
  12633. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  12634. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  12635. EXPECT_EQ(body, res->body) << path;
  12636. }
  12637. }
  12638. // Regression test for DoS vulnerability: a malicious server sending a response
  12639. // without Content-Length header must not cause unbounded memory consumption on
  12640. // the client side. The client should stop reading after a reasonable limit,
  12641. // similar to the server-side set_payload_max_length protection.
  12642. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  12643. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  12644. #ifndef _WIN32
  12645. signal(SIGPIPE, SIG_IGN);
  12646. #endif
  12647. auto server_thread = std::thread([] {
  12648. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  12649. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12650. default_socket_options(srv);
  12651. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12652. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12653. sockaddr_in addr{};
  12654. addr.sin_family = AF_INET;
  12655. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12656. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12657. int opt = 1;
  12658. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12659. #ifdef _WIN32
  12660. reinterpret_cast<const char *>(&opt),
  12661. #else
  12662. &opt,
  12663. #endif
  12664. sizeof(opt));
  12665. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12666. ::listen(srv, 1);
  12667. sockaddr_in cli_addr{};
  12668. socklen_t cli_len = sizeof(cli_addr);
  12669. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12670. if (cli != INVALID_SOCKET) {
  12671. char buf[4096];
  12672. ::recv(cli, buf, sizeof(buf), 0);
  12673. // Malicious response: no Content-Length, no chunked encoding
  12674. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12675. "Connection: close\r\n"
  12676. "\r\n";
  12677. ::send(cli,
  12678. #ifdef _WIN32
  12679. static_cast<const char *>(response_header.c_str()),
  12680. static_cast<int>(response_header.size()),
  12681. #else
  12682. response_header.c_str(), response_header.size(),
  12683. #endif
  12684. 0);
  12685. // Send 10MB of data
  12686. std::string chunk(64 * 1024, 'A');
  12687. size_t total_sent = 0;
  12688. while (total_sent < MALICIOUS_DATA_SIZE) {
  12689. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  12690. auto sent = ::send(cli,
  12691. #ifdef _WIN32
  12692. static_cast<const char *>(chunk.c_str()),
  12693. static_cast<int>(to_send),
  12694. #else
  12695. chunk.c_str(), to_send,
  12696. #endif
  12697. 0);
  12698. if (sent <= 0) break;
  12699. total_sent += static_cast<size_t>(sent);
  12700. }
  12701. detail::close_socket(cli);
  12702. }
  12703. detail::close_socket(srv);
  12704. });
  12705. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12706. size_t total_read = 0;
  12707. {
  12708. Client cli("127.0.0.1", PORT + 2);
  12709. cli.set_read_timeout(5, 0);
  12710. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  12711. auto stream = cli.open_stream("GET", "/malicious");
  12712. ASSERT_TRUE(stream.is_valid());
  12713. char buffer[64 * 1024];
  12714. ssize_t n;
  12715. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12716. total_read += static_cast<size_t>(n);
  12717. }
  12718. } // StreamHandle and Client destroyed here, closing the socket
  12719. server_thread.join();
  12720. // With set_payload_max_length, the client must stop reading before consuming
  12721. // all 10MB. The read loop should be cut off at or near the configured limit.
  12722. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  12723. << "Client read " << total_read << " bytes, exceeding the configured "
  12724. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  12725. }
  12726. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  12727. // the entire response body without truncation.
  12728. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  12729. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  12730. #ifndef _WIN32
  12731. signal(SIGPIPE, SIG_IGN);
  12732. #endif
  12733. auto server_thread = std::thread([] {
  12734. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12735. default_socket_options(srv);
  12736. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12737. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12738. sockaddr_in addr{};
  12739. addr.sin_family = AF_INET;
  12740. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12741. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12742. int opt = 1;
  12743. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12744. #ifdef _WIN32
  12745. reinterpret_cast<const char *>(&opt),
  12746. #else
  12747. &opt,
  12748. #endif
  12749. sizeof(opt));
  12750. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12751. ::listen(srv, 1);
  12752. sockaddr_in cli_addr{};
  12753. socklen_t cli_len = sizeof(cli_addr);
  12754. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12755. if (cli != INVALID_SOCKET) {
  12756. char buf[4096];
  12757. ::recv(cli, buf, sizeof(buf), 0);
  12758. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12759. "Connection: close\r\n"
  12760. "\r\n";
  12761. ::send(cli,
  12762. #ifdef _WIN32
  12763. static_cast<const char *>(response_header.c_str()),
  12764. static_cast<int>(response_header.size()),
  12765. #else
  12766. response_header.c_str(), response_header.size(),
  12767. #endif
  12768. 0);
  12769. std::string chunk(64 * 1024, 'A');
  12770. size_t total_sent = 0;
  12771. while (total_sent < DATA_SIZE) {
  12772. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12773. auto sent = ::send(cli,
  12774. #ifdef _WIN32
  12775. static_cast<const char *>(chunk.c_str()),
  12776. static_cast<int>(to_send),
  12777. #else
  12778. chunk.c_str(), to_send,
  12779. #endif
  12780. 0);
  12781. if (sent <= 0) break;
  12782. total_sent += static_cast<size_t>(sent);
  12783. }
  12784. #ifdef _WIN32
  12785. ::shutdown(cli, SD_SEND);
  12786. #else
  12787. ::shutdown(cli, SHUT_WR);
  12788. #endif
  12789. // Drain until the client closes its end, ensuring all data is delivered
  12790. char drain[1024];
  12791. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  12792. detail::close_socket(cli);
  12793. }
  12794. detail::close_socket(srv);
  12795. });
  12796. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12797. size_t total_read = 0;
  12798. {
  12799. Client cli("127.0.0.1", PORT + 2);
  12800. cli.set_read_timeout(5, 0);
  12801. cli.set_payload_max_length(0); // 0 means no limit
  12802. auto stream = cli.open_stream("GET", "/data");
  12803. ASSERT_TRUE(stream.is_valid());
  12804. char buffer[64 * 1024];
  12805. ssize_t n;
  12806. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  12807. total_read += static_cast<size_t>(n);
  12808. }
  12809. }
  12810. server_thread.join();
  12811. EXPECT_EQ(total_read, DATA_SIZE)
  12812. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  12813. << " bytes without truncation, but only read " << total_read << " bytes.";
  12814. }
  12815. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  12816. // enormous Content-Length must not cause the client to pre-allocate a huge
  12817. // response body buffer. The reservation is capped at payload_max_length_, and
  12818. // the read itself fails when the body exceeds the limit.
  12819. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  12820. #ifndef _WIN32
  12821. signal(SIGPIPE, SIG_IGN);
  12822. #endif
  12823. auto server_thread = std::thread([] {
  12824. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12825. default_socket_options(srv);
  12826. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12827. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12828. sockaddr_in addr{};
  12829. addr.sin_family = AF_INET;
  12830. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12831. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12832. int opt = 1;
  12833. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12834. #ifdef _WIN32
  12835. reinterpret_cast<const char *>(&opt),
  12836. #else
  12837. &opt,
  12838. #endif
  12839. sizeof(opt));
  12840. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12841. ::listen(srv, 1);
  12842. sockaddr_in cli_addr{};
  12843. socklen_t cli_len = sizeof(cli_addr);
  12844. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12845. if (cli != INVALID_SOCKET) {
  12846. char buf[4096];
  12847. ::recv(cli, buf, sizeof(buf), 0);
  12848. // Malicious response: claim a 20GB body but send only a tiny payload.
  12849. std::string response = "HTTP/1.1 200 OK\r\n"
  12850. "Content-Length: 20000000000\r\n"
  12851. "\r\n"
  12852. "abc";
  12853. ::send(cli,
  12854. #ifdef _WIN32
  12855. static_cast<const char *>(response.c_str()),
  12856. static_cast<int>(response.size()),
  12857. #else
  12858. response.c_str(), response.size(),
  12859. #endif
  12860. 0);
  12861. detail::close_socket(cli);
  12862. }
  12863. detail::close_socket(srv);
  12864. });
  12865. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12866. {
  12867. Client cli("127.0.0.1", PORT + 2);
  12868. cli.set_read_timeout(5, 0);
  12869. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  12870. // result in a 20GB pre-allocation. The Get() call is expected to fail
  12871. // (server claims more bytes than payload_max_length permits), but it must
  12872. // not exhaust memory before getting there.
  12873. auto res = cli.Get("/malicious");
  12874. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  12875. }
  12876. server_thread.join();
  12877. }
  12878. // Verify that content_receiver bypasses the default payload_max_length,
  12879. // allowing streaming downloads larger than 100MB without requiring an explicit
  12880. // set_payload_max_length call.
  12881. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  12882. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12883. #ifndef _WIN32
  12884. signal(SIGPIPE, SIG_IGN);
  12885. #endif
  12886. auto server_thread = std::thread([] {
  12887. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12888. default_socket_options(srv);
  12889. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12890. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12891. sockaddr_in addr{};
  12892. addr.sin_family = AF_INET;
  12893. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12894. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12895. int opt = 1;
  12896. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12897. #ifdef _WIN32
  12898. reinterpret_cast<const char *>(&opt),
  12899. #else
  12900. &opt,
  12901. #endif
  12902. sizeof(opt));
  12903. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12904. ::listen(srv, 1);
  12905. sockaddr_in cli_addr{};
  12906. socklen_t cli_len = sizeof(cli_addr);
  12907. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12908. if (cli != INVALID_SOCKET) {
  12909. char buf[4096];
  12910. ::recv(cli, buf, sizeof(buf), 0);
  12911. // Response with Content-Length larger than default 100MB limit
  12912. auto content_length = std::to_string(DATA_SIZE);
  12913. std::string response_header = "HTTP/1.1 200 OK\r\n"
  12914. "Content-Length: " +
  12915. content_length +
  12916. "\r\n"
  12917. "Connection: close\r\n"
  12918. "\r\n";
  12919. ::send(cli,
  12920. #ifdef _WIN32
  12921. static_cast<const char *>(response_header.c_str()),
  12922. static_cast<int>(response_header.size()),
  12923. #else
  12924. response_header.c_str(), response_header.size(),
  12925. #endif
  12926. 0);
  12927. std::string chunk(64 * 1024, 'A');
  12928. size_t total_sent = 0;
  12929. while (total_sent < DATA_SIZE) {
  12930. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  12931. auto sent = ::send(cli,
  12932. #ifdef _WIN32
  12933. static_cast<const char *>(chunk.c_str()),
  12934. static_cast<int>(to_send),
  12935. #else
  12936. chunk.c_str(), to_send,
  12937. #endif
  12938. 0);
  12939. if (sent <= 0) break;
  12940. total_sent += static_cast<size_t>(sent);
  12941. }
  12942. detail::close_socket(cli);
  12943. }
  12944. detail::close_socket(srv);
  12945. });
  12946. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  12947. size_t total_received = 0;
  12948. {
  12949. Client cli("127.0.0.1", PORT + 2);
  12950. cli.set_read_timeout(10, 0);
  12951. // Do NOT call set_payload_max_length — use the default 100MB limit
  12952. auto res =
  12953. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  12954. total_received += data_length;
  12955. return true;
  12956. });
  12957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12958. EXPECT_EQ(StatusCode::OK_200, res->status);
  12959. }
  12960. server_thread.join();
  12961. EXPECT_EQ(total_received, DATA_SIZE)
  12962. << "With content_receiver, the client should read all " << DATA_SIZE
  12963. << " bytes despite the default 100MB payload_max_length, but only read "
  12964. << total_received << " bytes.";
  12965. }
  12966. // Verify that an explicit set_payload_max_length smaller than the response is
  12967. // enforced even when a content_receiver is used.
  12968. TEST(ClientVulnerabilityTest,
  12969. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  12970. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  12971. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  12972. #ifndef _WIN32
  12973. signal(SIGPIPE, SIG_IGN);
  12974. #endif
  12975. auto server_thread = std::thread([] {
  12976. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  12977. default_socket_options(srv);
  12978. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  12979. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  12980. sockaddr_in addr{};
  12981. addr.sin_family = AF_INET;
  12982. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  12983. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  12984. int opt = 1;
  12985. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  12986. #ifdef _WIN32
  12987. reinterpret_cast<const char *>(&opt),
  12988. #else
  12989. &opt,
  12990. #endif
  12991. sizeof(opt));
  12992. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  12993. ::listen(srv, 1);
  12994. sockaddr_in cli_addr{};
  12995. socklen_t cli_len = sizeof(cli_addr);
  12996. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  12997. if (cli != INVALID_SOCKET) {
  12998. char buf[4096];
  12999. ::recv(cli, buf, sizeof(buf), 0);
  13000. auto content_length = std::to_string(DATA_SIZE);
  13001. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13002. "Content-Length: " +
  13003. content_length +
  13004. "\r\n"
  13005. "Connection: close\r\n"
  13006. "\r\n";
  13007. ::send(cli,
  13008. #ifdef _WIN32
  13009. static_cast<const char *>(response_header.c_str()),
  13010. static_cast<int>(response_header.size()),
  13011. #else
  13012. response_header.c_str(), response_header.size(),
  13013. #endif
  13014. 0);
  13015. std::string chunk(64 * 1024, 'A');
  13016. size_t total_sent = 0;
  13017. while (total_sent < DATA_SIZE) {
  13018. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13019. auto sent = ::send(cli,
  13020. #ifdef _WIN32
  13021. static_cast<const char *>(chunk.c_str()),
  13022. static_cast<int>(to_send),
  13023. #else
  13024. chunk.c_str(), to_send,
  13025. #endif
  13026. 0);
  13027. if (sent <= 0) break;
  13028. total_sent += static_cast<size_t>(sent);
  13029. }
  13030. detail::close_socket(cli);
  13031. }
  13032. detail::close_socket(srv);
  13033. });
  13034. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13035. size_t total_received = 0;
  13036. {
  13037. Client cli("127.0.0.1", PORT + 2);
  13038. cli.set_read_timeout(10, 0);
  13039. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  13040. auto res =
  13041. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13042. total_received += data_length;
  13043. return true;
  13044. });
  13045. // Should fail because 200MB exceeds the explicit 150MB limit
  13046. EXPECT_FALSE(res);
  13047. }
  13048. server_thread.join();
  13049. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  13050. << "Client with content_receiver should respect the explicit "
  13051. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  13052. << total_received << " bytes.";
  13053. }
  13054. // Verify that an explicit set_payload_max_length larger than the response
  13055. // allows the content_receiver to read all data successfully.
  13056. TEST(ClientVulnerabilityTest,
  13057. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  13058. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  13059. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  13060. #ifndef _WIN32
  13061. signal(SIGPIPE, SIG_IGN);
  13062. #endif
  13063. auto server_thread = std::thread([] {
  13064. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13065. default_socket_options(srv);
  13066. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13067. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13068. sockaddr_in addr{};
  13069. addr.sin_family = AF_INET;
  13070. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  13071. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13072. int opt = 1;
  13073. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13074. #ifdef _WIN32
  13075. reinterpret_cast<const char *>(&opt),
  13076. #else
  13077. &opt,
  13078. #endif
  13079. sizeof(opt));
  13080. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  13081. ::listen(srv, 1);
  13082. sockaddr_in cli_addr{};
  13083. socklen_t cli_len = sizeof(cli_addr);
  13084. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13085. if (cli != INVALID_SOCKET) {
  13086. char buf[4096];
  13087. ::recv(cli, buf, sizeof(buf), 0);
  13088. auto content_length = std::to_string(DATA_SIZE);
  13089. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13090. "Content-Length: " +
  13091. content_length +
  13092. "\r\n"
  13093. "Connection: close\r\n"
  13094. "\r\n";
  13095. ::send(cli,
  13096. #ifdef _WIN32
  13097. static_cast<const char *>(response_header.c_str()),
  13098. static_cast<int>(response_header.size()),
  13099. #else
  13100. response_header.c_str(), response_header.size(),
  13101. #endif
  13102. 0);
  13103. std::string chunk(64 * 1024, 'A');
  13104. size_t total_sent = 0;
  13105. while (total_sent < DATA_SIZE) {
  13106. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  13107. auto sent = ::send(cli,
  13108. #ifdef _WIN32
  13109. static_cast<const char *>(chunk.c_str()),
  13110. static_cast<int>(to_send),
  13111. #else
  13112. chunk.c_str(), to_send,
  13113. #endif
  13114. 0);
  13115. if (sent <= 0) break;
  13116. total_sent += static_cast<size_t>(sent);
  13117. }
  13118. #ifdef _WIN32
  13119. ::shutdown(cli, SD_SEND);
  13120. #else
  13121. ::shutdown(cli, SHUT_WR);
  13122. #endif
  13123. char drain[1024];
  13124. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  13125. detail::close_socket(cli);
  13126. }
  13127. detail::close_socket(srv);
  13128. });
  13129. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  13130. size_t total_received = 0;
  13131. {
  13132. Client cli("127.0.0.1", PORT + 2);
  13133. cli.set_read_timeout(10, 0);
  13134. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  13135. auto res =
  13136. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  13137. total_received += data_length;
  13138. return true;
  13139. });
  13140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13141. EXPECT_EQ(StatusCode::OK_200, res->status);
  13142. }
  13143. server_thread.join();
  13144. EXPECT_EQ(total_received, DATA_SIZE)
  13145. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  13146. << " bytes (larger than " << DATA_SIZE
  13147. << " bytes response), content_receiver should read all data, but only "
  13148. "read "
  13149. << total_received << " bytes.";
  13150. }
  13151. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  13152. // Regression test for "zip bomb" attack on the client side: a malicious server
  13153. // sends a small gzip-compressed response that decompresses to a huge payload.
  13154. // The client must enforce payload_max_length on the decompressed size.
  13155. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  13156. constexpr size_t DECOMPRESSED_SIZE =
  13157. 10 * 1024 * 1024; // 10MB after decompression
  13158. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  13159. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  13160. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  13161. std::string compressed;
  13162. {
  13163. httplib::detail::gzip_compressor compressor;
  13164. bool ok =
  13165. compressor.compress(uncompressed.data(), uncompressed.size(),
  13166. /*last=*/true, [&](const char *buf, size_t len) {
  13167. compressed.append(buf, len);
  13168. return true;
  13169. });
  13170. ASSERT_TRUE(ok);
  13171. }
  13172. // Sanity: compressed data should be much smaller than the decompressed size
  13173. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  13174. #ifndef _WIN32
  13175. signal(SIGPIPE, SIG_IGN);
  13176. #endif
  13177. // Set up the listening socket in the main thread so the server is guaranteed
  13178. // to be ready before the client connects (eliminates race condition).
  13179. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  13180. default_socket_options(srv);
  13181. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  13182. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  13183. sockaddr_in addr{};
  13184. addr.sin_family = AF_INET;
  13185. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  13186. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  13187. int opt = 1;
  13188. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  13189. #ifdef _WIN32
  13190. reinterpret_cast<const char *>(&opt),
  13191. #else
  13192. &opt,
  13193. #endif
  13194. sizeof(opt));
  13195. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  13196. ASSERT_EQ(0, ::listen(srv, 1));
  13197. auto server_thread = std::thread([&compressed, srv] {
  13198. sockaddr_in cli_addr{};
  13199. socklen_t cli_len = sizeof(cli_addr);
  13200. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  13201. if (cli != INVALID_SOCKET) {
  13202. // Read the full HTTP request (until \r\n\r\n)
  13203. char buf[4096];
  13204. size_t total = 0;
  13205. while (total < sizeof(buf)) {
  13206. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  13207. if (n <= 0) break;
  13208. total += static_cast<size_t>(n);
  13209. // Check for end of headers
  13210. if (total >= 4) {
  13211. std::string req(buf, total);
  13212. if (req.find("\r\n\r\n") != std::string::npos) break;
  13213. }
  13214. }
  13215. // Malicious response: gzip-compressed body, no Content-Length
  13216. std::string response_header = "HTTP/1.1 200 OK\r\n"
  13217. "Content-Encoding: gzip\r\n"
  13218. "Connection: close\r\n"
  13219. "\r\n";
  13220. ::send(cli,
  13221. #ifdef _WIN32
  13222. static_cast<const char *>(response_header.c_str()),
  13223. static_cast<int>(response_header.size()),
  13224. #else
  13225. response_header.c_str(), response_header.size(),
  13226. #endif
  13227. 0);
  13228. // Send the compressed payload (small on the wire, huge when decompressed)
  13229. size_t total_sent = 0;
  13230. while (total_sent < compressed.size()) {
  13231. auto to_send = std::min(compressed.size() - total_sent,
  13232. static_cast<size_t>(64 * 1024));
  13233. auto sent =
  13234. ::send(cli,
  13235. #ifdef _WIN32
  13236. static_cast<const char *>(compressed.c_str() + total_sent),
  13237. static_cast<int>(to_send),
  13238. #else
  13239. compressed.c_str() + total_sent, to_send,
  13240. #endif
  13241. 0);
  13242. if (sent <= 0) break;
  13243. total_sent += static_cast<size_t>(sent);
  13244. }
  13245. detail::close_socket(cli);
  13246. }
  13247. });
  13248. auto se = detail::scope_exit([&] {
  13249. detail::close_socket(srv);
  13250. server_thread.join();
  13251. });
  13252. size_t total_decompressed = 0;
  13253. {
  13254. Client cli("127.0.0.1", PORT + 3);
  13255. cli.set_read_timeout(5, 0);
  13256. cli.set_decompress(true);
  13257. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  13258. auto stream = cli.open_stream("GET", "/zipbomb");
  13259. ASSERT_TRUE(stream.is_valid());
  13260. char buffer[64 * 1024];
  13261. ssize_t n;
  13262. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  13263. total_decompressed += static_cast<size_t>(n);
  13264. }
  13265. }
  13266. // The decompressed size must be capped by payload_max_length. Without
  13267. // protection, the client would decompress the full 10MB from a tiny
  13268. // compressed payload, enabling a zip bomb DoS attack.
  13269. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  13270. << "Client decompressed " << total_decompressed
  13271. << " bytes from a gzip response. The decompressed size should be "
  13272. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  13273. }
  13274. #endif
  13275. TEST(HostAndPortPropertiesTest, NoSSL) {
  13276. httplib::Client cli("www.google.com", 1234);
  13277. ASSERT_EQ("www.google.com", cli.host());
  13278. ASSERT_EQ(1234, cli.port());
  13279. }
  13280. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  13281. httplib::Client cli("www.google.com:1234");
  13282. ASSERT_EQ("www.google.com", cli.host());
  13283. ASSERT_EQ(1234, cli.port());
  13284. }
  13285. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  13286. // Port number that overflows int — should not crash, client becomes invalid
  13287. httplib::Client cli("http://www.google.com:99999999999999999999");
  13288. ASSERT_FALSE(cli.is_valid());
  13289. }
  13290. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  13291. // Port 99999 exceeds valid range (1-65535) — should not crash
  13292. httplib::Client cli("http://www.google.com:99999");
  13293. ASSERT_FALSE(cli.is_valid());
  13294. auto res = cli.Get("/");
  13295. EXPECT_FALSE(res);
  13296. EXPECT_EQ(Error::Connection, res.error());
  13297. }
  13298. TEST(HostAndPortPropertiesTest, UserinfoIsNotSupported) {
  13299. httplib::Client cli("http://user:pass@localhost:1234");
  13300. ASSERT_FALSE(cli.is_valid());
  13301. EXPECT_FALSE(cli.Get("/"));
  13302. EXPECT_FALSE(httplib::Client("//user@localhost:1234").is_valid());
  13303. }
  13304. TEST(HostAndPortPropertiesTest, TrailingCharactersInPort) {
  13305. httplib::Client cli("http://www.google.com:80abc");
  13306. ASSERT_FALSE(cli.is_valid());
  13307. }
  13308. #ifdef CPPHTTPLIB_SSL_ENABLED
  13309. TEST(HostAndPortPropertiesTest, SSL) {
  13310. httplib::SSLClient cli("www.google.com");
  13311. ASSERT_EQ("www.google.com", cli.host());
  13312. ASSERT_EQ(443, cli.port());
  13313. }
  13314. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  13315. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  13316. std::string cert;
  13317. read_file(CA_CERT_FILE, cert);
  13318. httplib::SSLClient httplib_client("www.google.com");
  13319. // Load CA store first time
  13320. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13321. // Load CA store second time (update)
  13322. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  13323. // Verify client is still valid and can make connections
  13324. httplib_client.enable_server_certificate_verification(true);
  13325. auto res = httplib_client.Get("/");
  13326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13327. // Google may return 200 or 301 depending on various factors
  13328. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  13329. res->status == StatusCode::MovedPermanently_301);
  13330. }
  13331. TEST(SSLClientTest, ServerNameIndication_Online) {
  13332. auto host = "httpbingo.org";
  13333. auto path = std::string{"/get"};
  13334. SSLClient cli(host, 443);
  13335. auto res = cli.Get(path);
  13336. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13337. ASSERT_EQ(StatusCode::OK_200, res->status);
  13338. }
  13339. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  13340. // Use a site that will cause SSL verification failure due to self-signed cert
  13341. SSLClient cli("self-signed.badssl.com", 443);
  13342. cli.enable_server_certificate_verification(true);
  13343. auto res = cli.Get("/");
  13344. ASSERT_TRUE(!res);
  13345. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13346. // Verify backend error is captured for SSLServerVerification
  13347. // This occurs when certificate verification fails
  13348. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  13349. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  13350. EXPECT_NE(0UL, res.ssl_backend_error());
  13351. EXPECT_EQ(static_cast<int>(tls::ErrorCode::CertVerifyFailed),
  13352. res.ssl_error());
  13353. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13354. #if !defined(_WIN32) || \
  13355. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13356. // On non-Windows or when Windows Schannel is disabled, the error comes
  13357. // from OpenSSL's verification
  13358. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  13359. res.ssl_backend_error());
  13360. #endif
  13361. #endif
  13362. }
  13363. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  13364. // Use a site where hostname doesn't match the certificate
  13365. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  13366. SSLClient cli("wrong.host.badssl.com", 443);
  13367. cli.enable_server_certificate_verification(true);
  13368. cli.enable_server_hostname_verification(true);
  13369. auto res = cli.Get("/");
  13370. ASSERT_TRUE(!res);
  13371. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  13372. // Verify backend error is captured for hostname verification failure
  13373. EXPECT_NE(0UL, res.ssl_backend_error());
  13374. EXPECT_EQ(static_cast<int>(tls::ErrorCode::HostnameMismatch),
  13375. res.ssl_error());
  13376. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13377. #if !defined(_WIN32) || \
  13378. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13379. // On non-Windows or when Windows Schannel is disabled, the error comes
  13380. // from OpenSSL's hostname verification
  13381. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  13382. res.ssl_backend_error());
  13383. #endif
  13384. #endif
  13385. }
  13386. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  13387. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  13388. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  13389. SSLClient cli("www.google.com", 443);
  13390. cli.enable_server_certificate_verification(true);
  13391. auto res = cli.Get("/");
  13392. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13393. }
  13394. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  13395. SSLClient cli("www.google.com", 443);
  13396. cli.enable_server_certificate_verification(true);
  13397. cli.enable_windows_certificate_verification(false);
  13398. auto res = cli.Get("/");
  13399. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  13400. }
  13401. // The server sends an intermediate cross-signed by a root Windows trusts,
  13402. // while the leaf's AIA URL leads to one under a root Windows does not trust.
  13403. TEST(SSLClientTest, WindowsCertificateVerification_ServerIntermediates_Online) {
  13404. SSLClient cli("accounts.spotify.com", 443);
  13405. auto res = cli.Get("/");
  13406. ASSERT_TRUE(res) << "Error: " << to_string(res.error())
  13407. << " ssl_backend_error=" << res.ssl_backend_error();
  13408. }
  13409. // Windows, not the backend, decides on the chain: the error is a CryptoAPI
  13410. // policy status, which no backend reports for a self-signed certificate.
  13411. TEST(SSLClientTest, WindowsCertificateVerification_RejectsUntrustedRoot) {
  13412. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13413. ASSERT_TRUE(svr.is_valid());
  13414. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13415. auto se = detail::scope_exit([&] {
  13416. svr.stop();
  13417. t.join();
  13418. ASSERT_FALSE(svr.is_running());
  13419. });
  13420. svr.wait_until_ready();
  13421. SSLClient cli("127.0.0.1", PORT);
  13422. cli.set_connection_timeout(30);
  13423. auto res = cli.Get("/");
  13424. ASSERT_FALSE(res);
  13425. EXPECT_EQ(Error::SSLServerVerification, res.error());
  13426. EXPECT_EQ(static_cast<DWORD>(CERT_E_UNTRUSTEDROOT), res.ssl_backend_error());
  13427. }
  13428. #endif
  13429. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  13430. Client cli("https://google.com");
  13431. auto res = cli.Get("/");
  13432. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13433. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13434. }
  13435. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  13436. SSLClient cli("google.com");
  13437. cli.set_ca_cert_path(CA_CERT_FILE);
  13438. auto res = cli.Get("/");
  13439. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13440. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13441. }
  13442. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  13443. SSLClient cli("google.com");
  13444. cli.enable_server_certificate_verification(true);
  13445. cli.set_ca_cert_path("hello");
  13446. auto res = cli.Get("/");
  13447. ASSERT_TRUE(!res);
  13448. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  13449. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  13450. // should be set
  13451. EXPECT_EQ(0, res.ssl_error());
  13452. // Verify backend error is captured for SSLLoadingCerts
  13453. // This error occurs when loading CA certificates fails
  13454. EXPECT_NE(0UL, res.ssl_backend_error());
  13455. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  13456. // OpenSSL specific error codes:
  13457. // > openssl errstr 0x80000002
  13458. // error:80000002:system library::No such file or directory
  13459. // > openssl errstr 0xA000126
  13460. // error:0A000126:SSL routines::unexpected eof while reading
  13461. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  13462. res.ssl_backend_error() == 0xA000126);
  13463. #endif
  13464. }
  13465. TEST(SSLClientTest, ServerCertificateVerification4) {
  13466. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13467. ASSERT_TRUE(svr.is_valid());
  13468. svr.Get("/test", [&](const Request &, Response &res) {
  13469. res.set_content("test", "text/plain");
  13470. svr.stop();
  13471. ASSERT_TRUE(true);
  13472. });
  13473. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13474. auto se = detail::scope_exit([&] {
  13475. t.join();
  13476. ASSERT_FALSE(svr.is_running());
  13477. });
  13478. svr.wait_until_ready();
  13479. SSLClient cli("127.0.0.1", PORT);
  13480. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  13481. cli.enable_server_certificate_verification(true);
  13482. cli.set_connection_timeout(30);
  13483. auto res = cli.Get("/test");
  13484. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13485. ASSERT_EQ(StatusCode::OK_200, res->status);
  13486. }
  13487. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  13488. std::string cert;
  13489. read_file(CA_CERT_FILE, cert);
  13490. SSLClient cli("google.com");
  13491. cli.load_ca_cert_store(cert.data(), cert.size());
  13492. const auto res = cli.Get("/");
  13493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13494. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13495. }
  13496. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  13497. // clang-format off
  13498. static constexpr char cert[] =
  13499. "GlobalSign Root CA\n"
  13500. "==================\n"
  13501. "-----BEGIN CERTIFICATE-----\n"
  13502. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  13503. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  13504. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  13505. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  13506. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  13507. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  13508. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  13509. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  13510. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  13511. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  13512. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  13513. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  13514. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  13515. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  13516. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  13517. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  13518. "-----END CERTIFICATE-----\n";
  13519. // clang-format on
  13520. SSLClient cli("google.com");
  13521. cli.load_ca_cert_store(cert, sizeof(cert));
  13522. const auto res = cli.Get("/");
  13523. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13524. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13525. }
  13526. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  13527. SSLClient cli("www.youtube.com");
  13528. cli.set_ca_cert_path(CA_CERT_FILE);
  13529. cli.enable_server_certificate_verification(true);
  13530. cli.set_follow_location(true);
  13531. auto res = cli.Get("/");
  13532. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13533. ASSERT_EQ(StatusCode::OK_200, res->status);
  13534. }
  13535. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  13536. SSLClient cli("wWw.YouTube.Com");
  13537. cli.set_ca_cert_path(CA_CERT_FILE);
  13538. cli.enable_server_certificate_verification(true);
  13539. cli.enable_server_hostname_verification(true);
  13540. cli.set_follow_location(true);
  13541. auto res = cli.Get("/");
  13542. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13543. ASSERT_EQ(StatusCode::OK_200, res->status);
  13544. }
  13545. TEST(SSLClientTest, HostNameMatchCase_Online) {
  13546. SSLClient cli("gOoGlE.COm");
  13547. cli.enable_server_certificate_verification(true);
  13548. cli.enable_server_hostname_verification(true);
  13549. cli.set_follow_location(true);
  13550. auto res = cli.Get("/");
  13551. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13552. ASSERT_EQ(StatusCode::OK_200, res->status);
  13553. }
  13554. TEST(SSLClientTest, Issue2004_Online) {
  13555. Client client("https://google.com");
  13556. client.set_follow_location(true);
  13557. auto res = client.Get("/");
  13558. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13559. ASSERT_EQ(StatusCode::OK_200, res->status);
  13560. auto body = res->body;
  13561. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  13562. }
  13563. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  13564. // Create SSLClient with invalid cert/key to make is_valid() return false
  13565. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  13566. "nonexistent_key.pem");
  13567. // is_valid() should be false due to cert loading failure
  13568. ASSERT_FALSE(cli.is_valid());
  13569. auto res = cli.Get("/");
  13570. ASSERT_FALSE(res);
  13571. EXPECT_EQ(Error::SSLConnection, res.error());
  13572. }
  13573. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  13574. // Test for Issue #2251: SSL error not properly reported when client cert
  13575. // and key paths are swapped or mismatched
  13576. // This simulates the scenario where user accidentally swaps the cert and key
  13577. // files
  13578. // Using client cert file as private key and vice versa (completely wrong)
  13579. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  13580. // Should fail validation due to cert/key mismatch
  13581. ASSERT_FALSE(cli.is_valid());
  13582. // Attempt to make a request should fail with proper error
  13583. auto res = cli.Get("/");
  13584. ASSERT_FALSE(res);
  13585. EXPECT_EQ(Error::SSLConnection, res.error());
  13586. // SSL error should be recorded in the Result object (this is the key fix for
  13587. // Issue #2251)
  13588. auto backend_error = res.ssl_backend_error();
  13589. EXPECT_NE(0u, backend_error);
  13590. }
  13591. // Tests cert/key mismatch detection at the TLS context level
  13592. TEST(TlsApiTest, ClientCertKeyMismatch) {
  13593. // Test that using mismatched cert/key causes connection failure.
  13594. // We verify this at the SSLClient level rather than through internal
  13595. // TLS API functions.
  13596. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  13597. cli.enable_server_certificate_verification(false);
  13598. cli.set_connection_timeout(2);
  13599. // The mismatch should cause a connection or handshake error
  13600. auto res = cli.Get("/test");
  13601. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  13602. // Either way, the request should fail
  13603. EXPECT_FALSE(res);
  13604. }
  13605. #endif
  13606. #if 0
  13607. TEST(SSLClientTest, SetInterfaceWithINET6) {
  13608. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  13609. ASSERT_TRUE(cli != nullptr);
  13610. cli->set_address_family(AF_INET6);
  13611. cli->set_interface("en0");
  13612. auto res = cli->Get("/get");
  13613. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13614. ASSERT_EQ(StatusCode::OK_200, res->status);
  13615. }
  13616. #endif
  13617. // Client certificate tests - work with all TLS backends
  13618. #ifdef CPPHTTPLIB_SSL_ENABLED
  13619. using ClientCertServerSetup = std::function<void(SSLServer &)>;
  13620. void ClientCertPresent(
  13621. const std::string &client_cert_file,
  13622. const std::string &client_private_key_file,
  13623. const std::string &client_encrypted_private_key_pass = std::string(),
  13624. const ClientCertServerSetup &setup = nullptr) {
  13625. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13626. ASSERT_TRUE(svr.is_valid());
  13627. if (setup) { setup(svr); }
  13628. svr.Get("/test", [&](const Request &req, Response &res) {
  13629. res.set_content("test", "text/plain");
  13630. auto cert = req.peer_cert();
  13631. ASSERT_TRUE(static_cast<bool>(cert));
  13632. std::string common_name = cert.subject_cn();
  13633. EXPECT_EQ("Common Name", common_name);
  13634. });
  13635. auto port = svr.bind_to_any_port(HOST);
  13636. ASSERT_LT(0, port);
  13637. thread t = thread([&]() { svr.listen_after_bind(); });
  13638. auto se = detail::scope_exit([&] {
  13639. svr.stop();
  13640. t.join();
  13641. ASSERT_FALSE(svr.is_running());
  13642. });
  13643. svr.wait_until_ready();
  13644. SSLClient cli(HOST, port, client_cert_file, client_private_key_file,
  13645. client_encrypted_private_key_pass);
  13646. cli.enable_server_certificate_verification(false);
  13647. cli.set_connection_timeout(30);
  13648. auto res = cli.Get("/test");
  13649. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13650. ASSERT_EQ(StatusCode::OK_200, res->status);
  13651. }
  13652. TEST(SSLClientServerTest, ClientCertPresent) {
  13653. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13654. }
  13655. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  13656. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13657. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13658. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13659. }
  13660. // Expects svr, which must require client certificates, to reject a client
  13661. // that has none
  13662. void RejectsClientWithoutCert(SSLServer &svr) {
  13663. svr.Get("/test", [](const Request &, Response &) { FAIL(); });
  13664. auto port = svr.bind_to_any_port(HOST);
  13665. ASSERT_LT(0, port);
  13666. thread t = thread([&]() { svr.listen_after_bind(); });
  13667. auto se = detail::scope_exit([&] {
  13668. svr.stop();
  13669. t.join();
  13670. ASSERT_FALSE(svr.is_running());
  13671. });
  13672. svr.wait_until_ready();
  13673. SSLClient cli(HOST, port);
  13674. cli.set_connection_timeout(30);
  13675. // Skip the server certificate check, so that the request fails because the
  13676. // client certificate is missing rather than because cert.pem is not trusted
  13677. cli.enable_server_certificate_verification(false);
  13678. auto res = cli.Get("/test");
  13679. ASSERT_FALSE(res);
  13680. // The server rejects the client during the handshake, or on TLS 1.3 right
  13681. // after it, which the client notices on its first write or read
  13682. EXPECT_TRUE(res.error() == Error::SSLConnection ||
  13683. res.error() == Error::Write || res.error() == Error::Read)
  13684. << to_string(res.error());
  13685. if (res.error() == Error::SSLConnection) {
  13686. EXPECT_NE(0UL, res.ssl_backend_error());
  13687. }
  13688. // A rejection noticed on the write keeps the TLS error the write hit
  13689. if (res.error() == Error::Write) { EXPECT_NE(0, res.ssl_error()); }
  13690. }
  13691. void ClientCertMissing(const ClientCertServerSetup &setup = nullptr) {
  13692. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  13693. ASSERT_TRUE(svr.is_valid());
  13694. if (setup) { setup(svr); }
  13695. RejectsClientWithoutCert(svr);
  13696. }
  13697. TEST(SSLClientServerTest, ClientCertMissing) { ClientCertMissing(); }
  13698. // A server that requires client certificates must keep requiring them after
  13699. // setup changes it, and keep accepting a client that has one
  13700. void ClientCertStillRequired(const ClientCertServerSetup &setup) {
  13701. ClientCertMissing(setup);
  13702. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, std::string(),
  13703. setup);
  13704. }
  13705. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackSet) {
  13706. ClientCertStillRequired([](SSLServer &svr) {
  13707. ASSERT_TRUE(tls::set_verify_callback(
  13708. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13709. });
  13710. }
  13711. TEST(SSLClientServerTest, ClientCertStillRequiredAfterVerifyCallbackCleared) {
  13712. ClientCertStillRequired([](SSLServer &svr) {
  13713. ASSERT_TRUE(tls::set_verify_callback(
  13714. svr.tls_context(), [](const tls::VerifyContext &) { return true; }));
  13715. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(), nullptr));
  13716. });
  13717. }
  13718. // The client verifies the server certificate during the handshake, so a
  13719. // server that fails the check never gets the client certificate, even when a
  13720. // verifier of the client's own accepts it
  13721. TEST(SSLClientServerTest, ClientCertNotSentToUnverifiedServer) {
  13722. struct Case {
  13723. const char *trusted_ca;
  13724. const char *host;
  13725. Error error;
  13726. };
  13727. // cert2.pem names localhost: the first client does not trust it, and the
  13728. // second trusts it but asks for another name
  13729. for (const auto &c :
  13730. {Case{CLIENT_CA_CERT_FILE, "localhost", Error::SSLServerVerification},
  13731. Case{SERVER_CERT2_FILE, "example.com",
  13732. Error::SSLServerHostnameVerification}}) {
  13733. for (auto with_verifier : {false, true}) {
  13734. SCOPED_TRACE(std::string(c.host) + (with_verifier ? " +verifier" : ""));
  13735. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE,
  13736. CLIENT_CA_CERT_FILE);
  13737. ASSERT_TRUE(svr.is_valid());
  13738. std::atomic<bool> got_client_cert{false};
  13739. ASSERT_TRUE(tls::set_verify_callback(svr.tls_context(),
  13740. [&](const tls::VerifyContext &) {
  13741. got_client_cert = true;
  13742. return true;
  13743. }));
  13744. auto port = svr.bind_to_any_port("127.0.0.1");
  13745. ASSERT_LT(0, port);
  13746. thread t = thread([&] { svr.listen_after_bind(); });
  13747. svr.wait_until_ready();
  13748. SSLClient cli(c.host, port, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13749. cli.set_hostname_addr_map({{c.host, "127.0.0.1"}});
  13750. cli.set_ca_cert_path(c.trusted_ca);
  13751. if (with_verifier) {
  13752. cli.set_server_certificate_verifier(
  13753. [](const tls::VerifyContext &) { return true; });
  13754. }
  13755. auto res = cli.Get("/");
  13756. EXPECT_FALSE(res);
  13757. EXPECT_EQ(c.error, res.error());
  13758. svr.stop();
  13759. t.join();
  13760. EXPECT_FALSE(got_client_cert);
  13761. }
  13762. }
  13763. }
  13764. void UpdateCertsPemWithClientCA(SSLServer &svr) {
  13765. std::string cert_pem, key_pem, ca_pem;
  13766. read_file(SERVER_CERT_FILE, cert_pem);
  13767. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  13768. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  13769. ASSERT_TRUE(
  13770. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  13771. }
  13772. TEST(SSLClientServerTest, UpdateCertsPemWithClientCARequiresClientCert) {
  13773. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13774. ASSERT_TRUE(svr.is_valid());
  13775. UpdateCertsPemWithClientCA(svr);
  13776. RejectsClientWithoutCert(svr);
  13777. }
  13778. TEST(SSLClientServerTest, ClientCertStillRequiredAfterUpdateCertsPem) {
  13779. ClientCertStillRequired(UpdateCertsPemWithClientCA);
  13780. }
  13781. // A TLS error from one request must not show up in a later request's Result
  13782. TEST(SSLClientServerTest, SSLErrorNotCarriedToLaterRequest) {
  13783. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13784. ASSERT_TRUE(svr.is_valid());
  13785. svr.Get("/test", [](const Request &, Response &res) {
  13786. res.set_content("test", "text/plain");
  13787. });
  13788. auto port = svr.bind_to_any_port(HOST);
  13789. ASSERT_LT(0, port);
  13790. thread t = thread([&]() { svr.listen_after_bind(); });
  13791. auto se = detail::scope_exit([&] {
  13792. svr.stop();
  13793. t.join();
  13794. ASSERT_FALSE(svr.is_running());
  13795. });
  13796. svr.wait_until_ready();
  13797. SSLClient cli(HOST, port);
  13798. cli.set_connection_timeout(30);
  13799. cli.enable_server_hostname_verification(false);
  13800. // cert.pem is not trusted, so the handshake fails
  13801. ASSERT_FALSE(cli.Get("/test"));
  13802. cli.enable_server_certificate_verification(false);
  13803. auto res = cli.Get("/test");
  13804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13805. EXPECT_EQ(0, res.ssl_error());
  13806. EXPECT_EQ(0UL, res.ssl_backend_error());
  13807. }
  13808. // PEM memory-based constructor tests (works with all TLS backends).
  13809. // exact_size passes each PEM in a buffer of its own size, with no NUL
  13810. // terminator after it.
  13811. void PemMemoryClientCertPresent(
  13812. const std::string &client_cert_file,
  13813. const std::string &client_private_key_file,
  13814. const std::string &client_encrypted_private_key_pass = std::string(),
  13815. bool exact_size = false) {
  13816. // Read PEM files into memory
  13817. std::string server_cert_pem, server_key_pem;
  13818. std::string client_ca_pem;
  13819. std::string client_cert_pem, client_key_pem;
  13820. read_file(SERVER_CERT_FILE, server_cert_pem);
  13821. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13822. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13823. read_file(client_cert_file, client_cert_pem);
  13824. read_file(client_private_key_file, client_key_pem);
  13825. std::list<std::vector<char>> exact_copies;
  13826. auto data = [&](const std::string &pem) -> const char * {
  13827. if (!exact_size) { return pem.c_str(); }
  13828. exact_copies.emplace_back(pem.begin(), pem.end());
  13829. return exact_copies.back().data();
  13830. };
  13831. // Create server with PEM memory
  13832. SSLServer::PemMemory server_pem = {
  13833. data(server_cert_pem),
  13834. server_cert_pem.size(),
  13835. data(server_key_pem),
  13836. server_key_pem.size(),
  13837. data(client_ca_pem),
  13838. client_ca_pem.size(),
  13839. nullptr // no password for server key
  13840. };
  13841. SSLServer svr(server_pem);
  13842. ASSERT_TRUE(svr.is_valid());
  13843. svr.Get("/test", [&](const Request &req, Response &res) {
  13844. res.set_content("test", "text/plain");
  13845. auto cert = req.peer_cert();
  13846. ASSERT_TRUE(static_cast<bool>(cert));
  13847. EXPECT_EQ("Common Name", cert.subject_cn());
  13848. });
  13849. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13850. auto se = detail::scope_exit([&] {
  13851. svr.stop();
  13852. t.join();
  13853. ASSERT_FALSE(svr.is_running());
  13854. });
  13855. svr.wait_until_ready();
  13856. // Create client with PEM memory
  13857. const char *password = client_encrypted_private_key_pass.empty()
  13858. ? nullptr
  13859. : client_encrypted_private_key_pass.c_str();
  13860. SSLClient::PemMemory client_pem = {
  13861. data(client_cert_pem), client_cert_pem.size(), data(client_key_pem),
  13862. client_key_pem.size(), password};
  13863. SSLClient cli(HOST, PORT, client_pem);
  13864. cli.enable_server_certificate_verification(false);
  13865. cli.set_connection_timeout(30);
  13866. auto res = cli.Get("/test");
  13867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13868. ASSERT_EQ(StatusCode::OK_200, res->status);
  13869. }
  13870. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  13871. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13872. }
  13873. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  13874. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  13875. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  13876. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  13877. }
  13878. // A server built from PEM memory with a client CA requires client certificates,
  13879. // also when the CA is a NUL-terminated string passed with a length of 0
  13880. TEST(SSLClientServerTest, PemMemoryClientCertMissing) {
  13881. std::string server_cert_pem, server_key_pem, client_ca_pem;
  13882. read_file(SERVER_CERT_FILE, server_cert_pem);
  13883. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  13884. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  13885. SSLServer::PemMemory server_pem = {
  13886. server_cert_pem.c_str(),
  13887. server_cert_pem.size(),
  13888. server_key_pem.c_str(),
  13889. server_key_pem.size(),
  13890. client_ca_pem.c_str(),
  13891. client_ca_pem.size(),
  13892. nullptr // no password for server key
  13893. };
  13894. for (auto client_ca_pem_len : {client_ca_pem.size(), size_t{0}}) {
  13895. SCOPED_TRACE(client_ca_pem_len);
  13896. server_pem.client_ca_pem_len = client_ca_pem_len;
  13897. SSLServer svr(server_pem);
  13898. ASSERT_TRUE(svr.is_valid());
  13899. RejectsClientWithoutCert(svr);
  13900. }
  13901. // An empty CA fails to load instead of turning the check off
  13902. server_pem.client_ca_pem = "";
  13903. server_pem.client_ca_pem_len = 0;
  13904. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13905. }
  13906. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  13907. TEST(SSLClientServerTest, PemMemoryExactSizeBuffers) {
  13908. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, "",
  13909. true);
  13910. }
  13911. // A length shorter than the PEM cuts it short, so it no longer loads
  13912. TEST(SSLClientServerTest, PemMemoryShortLengthCutsThePem) {
  13913. std::string cert, key;
  13914. read_file(SERVER_CERT_FILE, cert);
  13915. read_file(SERVER_PRIVATE_KEY_FILE, key);
  13916. for (auto cut_cert : {true, false}) {
  13917. auto cert_len = cut_cert ? cert.size() / 2 : cert.size();
  13918. auto key_len = cut_cert ? key.size() : key.size() / 2;
  13919. SSLServer::PemMemory server_pem = {
  13920. cert.c_str(), cert_len, key.c_str(), key_len, nullptr, 0, nullptr};
  13921. EXPECT_FALSE(SSLServer(server_pem).is_valid());
  13922. SSLClient::PemMemory client_pem = {cert.c_str(), cert_len, key.c_str(),
  13923. key_len, nullptr};
  13924. EXPECT_FALSE(SSLClient(HOST, PORT, client_pem).is_valid());
  13925. ws::WebSocketClient::PemMemory ws_pem = {cert.c_str(), cert_len,
  13926. key.c_str(), key_len, nullptr};
  13927. EXPECT_FALSE(ws::WebSocketClient("wss://localhost/", ws_pem).is_valid());
  13928. }
  13929. }
  13930. TEST(SSLClientServerTest, SSLConnectTimeout) {
  13931. class NoListenSSLServer : public SSLServer {
  13932. public:
  13933. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  13934. const char *client_ca_cert_file_path,
  13935. const char *client_ca_cert_dir_path = nullptr)
  13936. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  13937. client_ca_cert_dir_path),
  13938. stop_(false) {}
  13939. std::atomic_bool stop_;
  13940. private:
  13941. bool process_and_close_socket(socket_t /*sock*/) override {
  13942. // Don't create SSL context
  13943. while (!stop_.load()) {
  13944. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  13945. }
  13946. return true;
  13947. }
  13948. };
  13949. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  13950. CLIENT_CA_CERT_FILE);
  13951. ASSERT_TRUE(svr.is_valid());
  13952. svr.Get("/test", [&](const Request &, Response &res) {
  13953. res.set_content("test", "text/plain");
  13954. });
  13955. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13956. auto se = detail::scope_exit([&] {
  13957. svr.stop_ = true;
  13958. svr.stop();
  13959. t.join();
  13960. ASSERT_FALSE(svr.is_running());
  13961. });
  13962. svr.wait_until_ready();
  13963. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13964. cli.enable_server_certificate_verification(false);
  13965. cli.set_connection_timeout(1);
  13966. auto res = cli.Get("/test");
  13967. ASSERT_TRUE(!res);
  13968. EXPECT_EQ(Error::SSLConnection, res.error());
  13969. // Timeout results in WantRead error code (maps to backend-specific value)
  13970. EXPECT_NE(0, res.ssl_error());
  13971. }
  13972. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  13973. // Test SSLServer with client certificate verification using the standard
  13974. // constructor (ContextSetupCallback is tested by backend-specific tests)
  13975. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  13976. CLIENT_CA_CERT_DIR);
  13977. ASSERT_TRUE(svr.is_valid());
  13978. svr.Get("/test", [&](const Request &req, Response &res) {
  13979. res.set_content("test", "text/plain");
  13980. auto cert = req.peer_cert();
  13981. ASSERT_TRUE(static_cast<bool>(cert));
  13982. auto common_name = cert.subject_cn();
  13983. EXPECT_EQ("Common Name", common_name);
  13984. });
  13985. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  13986. auto se = detail::scope_exit([&] {
  13987. svr.stop();
  13988. t.join();
  13989. ASSERT_FALSE(svr.is_running());
  13990. });
  13991. svr.wait_until_ready();
  13992. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  13993. cli.enable_server_certificate_verification(false);
  13994. cli.set_connection_timeout(30);
  13995. auto res = cli.Get("/test");
  13996. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13997. ASSERT_EQ(StatusCode::OK_200, res->status);
  13998. }
  13999. // Test verify_hostname for both OpenSSL and MbedTLS backends
  14000. // Verifies that wildcard matching and exact matching work consistently
  14001. TEST(SSLClientServerTest, TlsVerifyHostname) {
  14002. using namespace httplib::tls;
  14003. // We need a running server to test against
  14004. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14005. ASSERT_TRUE(svr.is_valid());
  14006. svr.Get("/test", [](const Request &, Response &res) {
  14007. res.set_content("ok", "text/plain");
  14008. });
  14009. thread t([&]() { svr.listen(HOST, PORT); });
  14010. auto se = detail::scope_exit([&] {
  14011. svr.stop();
  14012. t.join();
  14013. });
  14014. svr.wait_until_ready();
  14015. bool verify_callback_called = false;
  14016. bool verify_result_wrong = false;
  14017. SSLClient cli(HOST, PORT);
  14018. cli.enable_server_certificate_verification(true);
  14019. cli.set_ca_cert_path(CA_CERT_FILE);
  14020. cli.set_connection_timeout(5);
  14021. // Note: Test certificate has CN="Common Name", not "localhost"
  14022. bool verify_result_cn = false;
  14023. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14024. verify_callback_called = true;
  14025. if (!ctx.cert) return false;
  14026. // Test 1: "Common Name" should match (our test server cert CN)
  14027. verify_result_cn = ctx.check_hostname("Common Name");
  14028. // Test 2: wrong hostname should not match
  14029. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  14030. return true; // Accept for the purpose of this test
  14031. });
  14032. auto res = cli.Get("/test");
  14033. // The request may succeed or fail depending on cert configuration
  14034. // but the callback should have been called
  14035. ASSERT_TRUE(verify_callback_called)
  14036. << "Verify callback should have been called";
  14037. // CN="Common Name" should match our test certificate
  14038. //
  14039. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  14040. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  14041. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  14042. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  14043. // <openssl/base.h>, which is included transitively when
  14044. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  14045. #if defined(OPENSSL_IS_BORINGSSL)
  14046. EXPECT_FALSE(verify_result_cn)
  14047. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  14048. #else
  14049. EXPECT_TRUE(verify_result_cn)
  14050. << "verify_hostname should match 'Common Name' (certificate CN)";
  14051. #endif
  14052. // Wrong hostname should not match
  14053. EXPECT_FALSE(verify_result_wrong)
  14054. << "verify_hostname should not match 'wronghost.example.com'";
  14055. }
  14056. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  14057. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  14058. // X509_check_ip behavior and must hold for every backend.
  14059. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  14060. using namespace httplib::tls;
  14061. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  14062. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  14063. ASSERT_TRUE(svr.is_valid());
  14064. svr.Get("/test", [](const Request &, Response &res) {
  14065. res.set_content("ok", "text/plain");
  14066. });
  14067. thread t([&]() { svr.listen(HOST, PORT); });
  14068. auto se = detail::scope_exit([&] {
  14069. svr.stop();
  14070. t.join();
  14071. });
  14072. svr.wait_until_ready();
  14073. bool verify_callback_called = false;
  14074. bool ip_matched_via_cn = true;
  14075. SSLClient cli(HOST, PORT);
  14076. cli.enable_server_certificate_verification(true);
  14077. cli.set_ca_cert_path(CA_CERT_FILE);
  14078. cli.set_connection_timeout(5);
  14079. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14080. verify_callback_called = true;
  14081. if (!ctx.cert) return false;
  14082. // The IP appears only in the CN, so it must NOT be accepted.
  14083. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  14084. return true; // Accept for the purpose of this test
  14085. });
  14086. cli.Get("/test");
  14087. ASSERT_TRUE(verify_callback_called)
  14088. << "Verify callback should have been called";
  14089. EXPECT_FALSE(ip_matched_via_cn)
  14090. << "An IP host must not be authenticated via the certificate CN";
  14091. }
  14092. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  14093. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  14094. using namespace httplib::tls;
  14095. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  14096. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  14097. ASSERT_TRUE(svr.is_valid());
  14098. svr.Get("/test", [](const Request &, Response &res) {
  14099. res.set_content("ok", "text/plain");
  14100. });
  14101. thread t([&]() { svr.listen(HOST, PORT); });
  14102. auto se = detail::scope_exit([&] {
  14103. svr.stop();
  14104. t.join();
  14105. });
  14106. svr.wait_until_ready();
  14107. bool verify_callback_called = false;
  14108. bool san_matched = false;
  14109. bool wrong_ipv6_matched = true;
  14110. bool cn_ipv6_matched = true;
  14111. SSLClient cli(HOST, PORT);
  14112. cli.enable_server_certificate_verification(true);
  14113. cli.set_ca_cert_path(CA_CERT_FILE);
  14114. cli.set_connection_timeout(5);
  14115. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14116. verify_callback_called = true;
  14117. if (!ctx.cert) return false;
  14118. // Matches the IPv6 iPAddress SAN.
  14119. san_matched = ctx.check_hostname("2001:db8::1");
  14120. // A different IPv6 address must not match.
  14121. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  14122. // "::1" lives only in the CN, so it must not be accepted.
  14123. cn_ipv6_matched = ctx.check_hostname("::1");
  14124. return true; // Accept for the purpose of this test
  14125. });
  14126. cli.Get("/test");
  14127. ASSERT_TRUE(verify_callback_called)
  14128. << "Verify callback should have been called";
  14129. EXPECT_TRUE(san_matched)
  14130. << "verify_hostname should match an IPv6 iPAddress SAN";
  14131. EXPECT_FALSE(wrong_ipv6_matched)
  14132. << "verify_hostname should not match a non-matching IPv6 address";
  14133. EXPECT_FALSE(cn_ipv6_matched)
  14134. << "An IPv6 host must not be authenticated via the certificate CN";
  14135. }
  14136. // A SAN entry must only match a host of its own type: the bytes of the dNSName
  14137. // "a.zz" are also 97.46.122.122, and 42.46.122.122 reads as "*.zz".
  14138. TEST(SSLClientServerTest, TlsVerifyHostnameSanType) {
  14139. using namespace httplib::tls;
  14140. // SANs: DNS:a.zz, IP:42.46.122.122
  14141. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14142. ASSERT_TRUE(svr.is_valid());
  14143. svr.Get("/test", [](const Request &, Response &res) {
  14144. res.set_content("ok", "text/plain");
  14145. });
  14146. auto port = svr.bind_to_any_port(HOST);
  14147. thread t([&]() { svr.listen_after_bind(); });
  14148. auto se = detail::scope_exit([&] {
  14149. svr.stop();
  14150. t.join();
  14151. });
  14152. svr.wait_until_ready();
  14153. bool verify_callback_called = false;
  14154. bool dns_san_matched = false;
  14155. bool ip_san_matched = false;
  14156. bool ip_matched_via_dns_san = true;
  14157. bool dns_matched_via_ip_san = true;
  14158. bool cn_matched_next_to_dns_san = true;
  14159. SSLClient cli(HOST, port);
  14160. cli.enable_server_certificate_verification(true);
  14161. cli.set_ca_cert_path(CA_CERT_FILE);
  14162. cli.set_connection_timeout(5);
  14163. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14164. verify_callback_called = true;
  14165. if (!ctx.cert) return false;
  14166. dns_san_matched = ctx.check_hostname("a.zz");
  14167. ip_san_matched = ctx.check_hostname("42.46.122.122");
  14168. ip_matched_via_dns_san = ctx.check_hostname("97.46.122.122");
  14169. dns_matched_via_ip_san = ctx.check_hostname("b.zz");
  14170. cn_matched_next_to_dns_san = ctx.check_hostname("san-types");
  14171. return true; // Accept for the purpose of this test
  14172. });
  14173. cli.Get("/test");
  14174. ASSERT_TRUE(verify_callback_called)
  14175. << "Verify callback should have been called";
  14176. EXPECT_TRUE(dns_san_matched) << "verify_hostname should match a dNSName SAN";
  14177. EXPECT_TRUE(ip_san_matched)
  14178. << "verify_hostname should match an iPAddress SAN";
  14179. EXPECT_FALSE(ip_matched_via_dns_san)
  14180. << "An IP host must not be authenticated via a dNSName SAN";
  14181. EXPECT_FALSE(dns_matched_via_ip_san)
  14182. << "A DNS host must not be authenticated via an iPAddress SAN";
  14183. EXPECT_FALSE(cn_matched_next_to_dns_san)
  14184. << "The CN must not be consulted next to a dNSName SAN (RFC 6125)";
  14185. }
  14186. // RFC 6125 6.4.3: only the leftmost label of a dNSName may be a wildcard, so
  14187. // "www.*.example.test" names one host and not every host under example.test.
  14188. TEST(SSLClientServerTest, TlsVerifyHostnameWildcardLabel) {
  14189. using namespace httplib::tls;
  14190. // SANs: DNS:*.leftmost.example.test, DNS:www.*.example.test
  14191. SSLServer svr(SERVER_CERT_WILDCARD_SAN_FILE, SERVER_PRIVATE_KEY_FILE);
  14192. ASSERT_TRUE(svr.is_valid());
  14193. svr.Get("/test", [](const Request &, Response &res) {
  14194. res.set_content("ok", "text/plain");
  14195. });
  14196. auto port = svr.bind_to_any_port(HOST);
  14197. thread t([&]() { svr.listen_after_bind(); });
  14198. auto se = detail::scope_exit([&] {
  14199. svr.stop();
  14200. t.join();
  14201. });
  14202. svr.wait_until_ready();
  14203. bool verify_callback_called = false;
  14204. bool leftmost_wildcard_matched = false;
  14205. bool wildcard_spanned_labels = true;
  14206. bool inner_wildcard_matched = true;
  14207. SSLClient cli(HOST, port);
  14208. cli.enable_server_certificate_verification(true);
  14209. cli.set_ca_cert_path(CA_CERT_FILE);
  14210. cli.set_connection_timeout(5);
  14211. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14212. verify_callback_called = true;
  14213. if (!ctx.cert) return false;
  14214. leftmost_wildcard_matched = ctx.check_hostname("a.leftmost.example.test");
  14215. wildcard_spanned_labels = ctx.check_hostname("a.b.leftmost.example.test");
  14216. inner_wildcard_matched = ctx.check_hostname("www.evil.example.test");
  14217. return true; // Accept for the purpose of this test
  14218. });
  14219. cli.Get("/test");
  14220. ASSERT_TRUE(verify_callback_called)
  14221. << "Verify callback should have been called";
  14222. EXPECT_TRUE(leftmost_wildcard_matched)
  14223. << "A leftmost wildcard should match a single label";
  14224. EXPECT_FALSE(wildcard_spanned_labels)
  14225. << "A wildcard label must not match more than one label";
  14226. EXPECT_FALSE(inner_wildcard_matched)
  14227. << "A wildcard outside the leftmost label must not be honoured";
  14228. }
  14229. // sans() must report each SAN entry under its own type.
  14230. TEST(SSLClientServerTest, TlsCertSansEntryTypes) {
  14231. using namespace httplib::tls;
  14232. // SANs: DNS:a.zz, IP:42.46.122.122
  14233. SSLServer svr(SERVER_CERT_SAN_TYPES_FILE, SERVER_PRIVATE_KEY_FILE);
  14234. ASSERT_TRUE(svr.is_valid());
  14235. svr.Get("/test", [](const Request &, Response &res) {
  14236. res.set_content("ok", "text/plain");
  14237. });
  14238. auto port = svr.bind_to_any_port(HOST);
  14239. thread t([&]() { svr.listen_after_bind(); });
  14240. auto se = detail::scope_exit([&] {
  14241. svr.stop();
  14242. t.join();
  14243. });
  14244. svr.wait_until_ready();
  14245. bool verify_callback_called = false;
  14246. std::vector<SanEntry> sans;
  14247. SSLClient cli(HOST, port);
  14248. cli.enable_server_certificate_verification(true);
  14249. cli.set_ca_cert_path(CA_CERT_FILE);
  14250. cli.set_connection_timeout(5);
  14251. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14252. verify_callback_called = true;
  14253. if (!ctx.cert) return false;
  14254. sans = ctx.sans();
  14255. return true; // Accept for the purpose of this test
  14256. });
  14257. cli.Get("/test");
  14258. ASSERT_TRUE(verify_callback_called)
  14259. << "Verify callback should have been called";
  14260. auto has_san = [&](SanType type, const std::string &value) {
  14261. return std::any_of(sans.begin(), sans.end(), [&](const SanEntry &san) {
  14262. return san.type == type && san.value == value;
  14263. });
  14264. };
  14265. EXPECT_TRUE(has_san(SanType::DNS, "a.zz"))
  14266. << "sans() should report the dNSName SAN";
  14267. EXPECT_TRUE(has_san(SanType::IP, "42.46.122.122"))
  14268. << "sans() should report the iPAddress SAN";
  14269. EXPECT_FALSE(has_san(SanType::IP, "97.46.122.122"))
  14270. << "sans() must not report the dNSName SAN as an address";
  14271. EXPECT_FALSE(has_san(SanType::DNS, "*.zz"))
  14272. << "sans() must not report the iPAddress SAN as a DNS name";
  14273. }
  14274. #endif
  14275. // mbedTLS-specific callback constructor test
  14276. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  14277. #ifdef CPPHTTPLIB_SSL_ENABLED
  14278. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  14279. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14280. ASSERT_TRUE(svr.is_valid());
  14281. // Set up a handler to verify client certificate is present
  14282. bool client_cert_verified = false;
  14283. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  14284. // Verify that client certificate was provided
  14285. client_cert_verified = true;
  14286. res.set_content("success", "text/plain");
  14287. });
  14288. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14289. auto se = detail::scope_exit([&] {
  14290. svr.stop();
  14291. t.join();
  14292. ASSERT_FALSE(svr.is_running());
  14293. });
  14294. svr.wait_until_ready();
  14295. // Client with certificate
  14296. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14297. cli.enable_server_certificate_verification(false);
  14298. cli.set_connection_timeout(30);
  14299. auto res = cli.Get("/test");
  14300. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14301. ASSERT_EQ(StatusCode::OK_200, res->status);
  14302. ASSERT_TRUE(client_cert_verified);
  14303. EXPECT_EQ("success", res->body);
  14304. }
  14305. #endif
  14306. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  14307. // backends
  14308. #ifdef CPPHTTPLIB_SSL_ENABLED
  14309. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  14310. using namespace httplib::tls;
  14311. // Test that when client CA cert file is provided,
  14312. // the server properly requests and validates client certificates
  14313. // Create a server with client authentication
  14314. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  14315. ASSERT_TRUE(svr.is_valid());
  14316. bool handler_called = false;
  14317. svr.Get("/test", [&](const Request &req, Response &res) {
  14318. handler_called = true;
  14319. // Verify that a client certificate was provided
  14320. auto cert = req.peer_cert();
  14321. ASSERT_TRUE(static_cast<bool>(cert));
  14322. // Get the issuer name
  14323. std::string issuer_str = cert.issuer_name();
  14324. ASSERT_FALSE(issuer_str.empty());
  14325. // The client certificate should be issued by our test CA
  14326. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  14327. res.set_content("authenticated", "text/plain");
  14328. });
  14329. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14330. auto se = detail::scope_exit([&] {
  14331. svr.stop();
  14332. t.join();
  14333. ASSERT_FALSE(svr.is_running());
  14334. });
  14335. svr.wait_until_ready();
  14336. // Connect with a client certificate issued by the CA
  14337. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14338. cli.enable_server_certificate_verification(false);
  14339. cli.set_connection_timeout(30);
  14340. auto res = cli.Get("/test");
  14341. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14342. ASSERT_EQ(StatusCode::OK_200, res->status);
  14343. ASSERT_TRUE(handler_called);
  14344. EXPECT_EQ("authenticated", res->body);
  14345. }
  14346. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  14347. using namespace httplib::tls;
  14348. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14349. ASSERT_TRUE(svr.is_valid());
  14350. svr.Get("/test", [](const Request &, Response &res) {
  14351. res.set_content("ok", "text/plain");
  14352. });
  14353. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14354. auto se = detail::scope_exit([&] {
  14355. svr.stop();
  14356. t.join();
  14357. });
  14358. svr.wait_until_ready();
  14359. SSLClient cli(HOST, PORT);
  14360. cli.enable_server_certificate_verification(false);
  14361. cli.set_connection_timeout(30);
  14362. bool cert_checked = false;
  14363. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14364. if (ctx.cert) {
  14365. auto sans = ctx.sans();
  14366. // Test certificate may or may not have SANs - just verify the API
  14367. // works If SANs exist, verify the types are valid
  14368. for (const auto &san : sans) {
  14369. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  14370. san.type == SanType::EMAIL || san.type == SanType::URI ||
  14371. san.type == SanType::OTHER);
  14372. EXPECT_FALSE(san.value.empty());
  14373. }
  14374. cert_checked = true;
  14375. }
  14376. return true;
  14377. });
  14378. auto res = cli.Get("/test");
  14379. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14380. EXPECT_TRUE(cert_checked);
  14381. }
  14382. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  14383. using namespace httplib::tls;
  14384. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14385. ASSERT_TRUE(svr.is_valid());
  14386. svr.Get("/test", [](const Request &, Response &res) {
  14387. res.set_content("ok", "text/plain");
  14388. });
  14389. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14390. auto se = detail::scope_exit([&] {
  14391. svr.stop();
  14392. t.join();
  14393. });
  14394. svr.wait_until_ready();
  14395. SSLClient cli(HOST, PORT);
  14396. cli.enable_server_certificate_verification(false);
  14397. cli.set_connection_timeout(30);
  14398. bool validity_checked = false;
  14399. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14400. if (ctx.cert) {
  14401. time_t not_before = 0, not_after = 0;
  14402. bool result = ctx.validity(not_before, not_after);
  14403. EXPECT_TRUE(result);
  14404. // Verify that not_before < now < not_after for a valid cert
  14405. time_t now = time(nullptr);
  14406. EXPECT_LT(not_before, now);
  14407. EXPECT_GT(not_after, now);
  14408. validity_checked = true;
  14409. }
  14410. return true;
  14411. });
  14412. auto res = cli.Get("/test");
  14413. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14414. EXPECT_TRUE(validity_checked);
  14415. }
  14416. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  14417. using namespace httplib::tls;
  14418. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14419. ASSERT_TRUE(svr.is_valid());
  14420. svr.Get("/test", [](const Request &, Response &res) {
  14421. res.set_content("ok", "text/plain");
  14422. });
  14423. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14424. auto se = detail::scope_exit([&] {
  14425. svr.stop();
  14426. t.join();
  14427. });
  14428. svr.wait_until_ready();
  14429. SSLClient cli(HOST, PORT);
  14430. cli.enable_server_certificate_verification(false);
  14431. cli.set_connection_timeout(30);
  14432. bool serial_checked = false;
  14433. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14434. if (ctx.cert) {
  14435. std::string serial = ctx.serial();
  14436. EXPECT_FALSE(serial.empty());
  14437. // Serial should be a hex string
  14438. for (char c : serial) {
  14439. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  14440. (c >= 'a' && c <= 'f'));
  14441. }
  14442. serial_checked = true;
  14443. }
  14444. return true;
  14445. });
  14446. auto res = cli.Get("/test");
  14447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14448. EXPECT_TRUE(serial_checked);
  14449. }
  14450. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  14451. // Test 1: Valid CA file - no error should be recorded
  14452. {
  14453. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  14454. CLIENT_CA_CERT_FILE);
  14455. ASSERT_TRUE(svr.is_valid());
  14456. // With valid setup, last_ssl_error should be 0
  14457. EXPECT_EQ(0, svr.ssl_last_error());
  14458. }
  14459. // Test 2: Invalid CA file content
  14460. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  14461. {
  14462. // Create a temporary file with completely invalid content
  14463. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  14464. {
  14465. std::ofstream ofs(temp_invalid_ca);
  14466. ofs << "This is not a certificate file at all\n";
  14467. ofs << "Just plain text content\n";
  14468. }
  14469. // Create server with invalid CA file
  14470. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  14471. // Clean up temporary file
  14472. std::remove(temp_invalid_ca);
  14473. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  14474. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  14475. // Note: SSL_CTX_load_verify_locations typically fails first,
  14476. // but our error handling code path is still exercised
  14477. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  14478. }
  14479. }
  14480. TEST(VerifyCallbackTest, VerifyContextFields) {
  14481. using namespace httplib::tls;
  14482. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14483. ASSERT_TRUE(svr.is_valid());
  14484. svr.Get("/test", [](const Request &, Response &res) {
  14485. res.set_content("ok", "text/plain");
  14486. });
  14487. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14488. auto se = detail::scope_exit([&] {
  14489. svr.stop();
  14490. t.join();
  14491. });
  14492. svr.wait_until_ready();
  14493. SSLClient cli(HOST, PORT);
  14494. cli.enable_server_certificate_verification(false);
  14495. cli.set_connection_timeout(30);
  14496. int callback_count = 0;
  14497. bool saw_leaf_cert = false;
  14498. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  14499. if (ctx.cert) {
  14500. callback_count++;
  14501. // We should see at least one certificate (the leaf)
  14502. std::string cn = ctx.subject_cn();
  14503. if (!cn.empty()) { saw_leaf_cert = true; }
  14504. // Verify context fields are populated
  14505. EXPECT_NE(ctx.session, nullptr);
  14506. EXPECT_GE(ctx.depth, 0);
  14507. }
  14508. return true;
  14509. });
  14510. auto res = cli.Get("/test");
  14511. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14512. EXPECT_GT(callback_count, 0);
  14513. EXPECT_TRUE(saw_leaf_cert);
  14514. }
  14515. // A verifier that accepts runs alongside the built-in verification, and is the
  14516. // only check once that is turned off.
  14517. TEST(VerifyCallbackTest, AcceptingVerifierDoesNotOverrideVerification) {
  14518. using namespace httplib::tls;
  14519. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14520. ASSERT_TRUE(svr.is_valid());
  14521. svr.Get("/test", [](const Request &, Response &res) {
  14522. res.set_content("ok", "text/plain");
  14523. });
  14524. auto port = svr.bind_to_any_port(HOST);
  14525. thread t([&]() { svr.listen_after_bind(); });
  14526. auto se = detail::scope_exit([&] {
  14527. svr.stop();
  14528. t.join();
  14529. });
  14530. svr.wait_until_ready();
  14531. SSLClient cli(HOST, port);
  14532. cli.enable_server_hostname_verification(false);
  14533. auto calls = 0;
  14534. cli.set_server_certificate_verifier([&](const VerifyContext &) {
  14535. calls++;
  14536. return true;
  14537. });
  14538. // cert.pem is not trusted
  14539. auto res = cli.Get("/test");
  14540. ASSERT_FALSE(res);
  14541. EXPECT_EQ(Error::SSLServerVerification, res.error());
  14542. EXPECT_GT(calls, 0);
  14543. cli.enable_server_certificate_verification(false);
  14544. res = cli.Get("/test");
  14545. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14546. EXPECT_EQ("ok", res->body);
  14547. }
  14548. // A verifier belongs to the client that set it, not to the thread that set it.
  14549. TEST(VerifyCallbackTest, VerifierStaysWithItsClient) {
  14550. using namespace httplib::tls;
  14551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14552. ASSERT_TRUE(svr.is_valid());
  14553. svr.Get("/test", [](const Request &, Response &res) {
  14554. res.set_content("ok", "text/plain");
  14555. });
  14556. auto port = svr.bind_to_any_port(HOST);
  14557. thread t([&]() { svr.listen_after_bind(); });
  14558. auto se = detail::scope_exit([&] {
  14559. svr.stop();
  14560. t.join();
  14561. });
  14562. svr.wait_until_ready();
  14563. auto rejecting_calls = 0;
  14564. SSLClient rejecting(HOST, port);
  14565. rejecting.enable_server_certificate_verification(false);
  14566. rejecting.set_server_certificate_verifier([&](const VerifyContext &) {
  14567. rejecting_calls++;
  14568. return false;
  14569. });
  14570. auto accepting_calls = 0;
  14571. SSLClient accepting(HOST, port);
  14572. accepting.enable_server_certificate_verification(false);
  14573. // Set on another thread than the requests below.
  14574. thread([&]() {
  14575. accepting.set_server_certificate_verifier([&](const VerifyContext &) {
  14576. accepting_calls++;
  14577. return true;
  14578. });
  14579. }).join();
  14580. // Requested on another thread than the verifier was set on.
  14581. thread([&]() { EXPECT_FALSE(rejecting.Get("/test")); }).join();
  14582. EXPECT_GT(rejecting_calls, 0);
  14583. auto res = accepting.Get("/test");
  14584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14585. EXPECT_GT(accepting_calls, 0);
  14586. }
  14587. // A verifier replaced while a handshake runs it lives until it returns.
  14588. TEST(VerifyCallbackTest, VerifierReplacedDuringHandshake) {
  14589. using namespace httplib::tls;
  14590. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14591. ASSERT_TRUE(svr.is_valid());
  14592. svr.Get("/test", [](const Request &, Response &res) {
  14593. res.set_content("ok", "text/plain");
  14594. });
  14595. auto port = svr.bind_to_any_port(HOST);
  14596. thread t([&]() { svr.listen_after_bind(); });
  14597. auto se = detail::scope_exit([&] {
  14598. svr.stop();
  14599. t.join();
  14600. });
  14601. svr.wait_until_ready();
  14602. SSLClient cli(HOST, port);
  14603. cli.enable_server_certificate_verification(false);
  14604. std::promise<void> entered;
  14605. std::promise<void> replaced;
  14606. auto replaced_future = replaced.get_future();
  14607. auto first_call = true;
  14608. // Long enough to live on the heap
  14609. std::string expected(64, 'v');
  14610. cli.set_server_certificate_verifier([&, expected](const VerifyContext &) {
  14611. if (first_call) {
  14612. first_call = false;
  14613. entered.set_value();
  14614. replaced_future.wait();
  14615. }
  14616. return expected == std::string(64, 'v');
  14617. });
  14618. thread request([&]() {
  14619. auto res = cli.Get("/test");
  14620. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14621. });
  14622. entered.get_future().wait();
  14623. cli.set_server_certificate_verifier(
  14624. [](const VerifyContext &) { return true; });
  14625. replaced.set_value();
  14626. request.join();
  14627. }
  14628. // VerifyContext::session is the same handle the other tls:: functions take.
  14629. TEST(VerifyCallbackTest, SessionMatchesSessionVerifier) {
  14630. using namespace httplib::tls;
  14631. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14632. ASSERT_TRUE(svr.is_valid());
  14633. svr.Get("/test", [](const Request &, Response &res) {
  14634. res.set_content("ok", "text/plain");
  14635. });
  14636. auto port = svr.bind_to_any_port(HOST);
  14637. thread t([&]() { svr.listen_after_bind(); });
  14638. auto se = detail::scope_exit([&] {
  14639. svr.stop();
  14640. t.join();
  14641. });
  14642. svr.wait_until_ready();
  14643. SSLClient cli(HOST, port);
  14644. cli.enable_server_certificate_verification(false);
  14645. session_t verifier_session = nullptr;
  14646. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) {
  14647. verifier_session = ctx.session;
  14648. return true;
  14649. });
  14650. session_t session_verifier_session = nullptr;
  14651. cli.set_session_verifier([&](session_t session) {
  14652. session_verifier_session = session;
  14653. return SSLVerifierResponse::NoDecisionMade;
  14654. });
  14655. auto res = cli.Get("/test");
  14656. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14657. EXPECT_NE(nullptr, verifier_session);
  14658. EXPECT_EQ(session_verifier_session, verifier_session);
  14659. }
  14660. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  14661. using httplib::tls::TlsError;
  14662. // Test that verify_error_to_string returns empty for success
  14663. std::string success_str = TlsError::verify_error_to_string(0);
  14664. EXPECT_TRUE(success_str.empty());
  14665. // Test that verify_error_to_string returns non-empty for error codes
  14666. // Using a common error code (certificate expired)
  14667. std::string error_str =
  14668. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  14669. EXPECT_FALSE(error_str.empty());
  14670. }
  14671. TEST(SessionVerifierTest, CertificateAccepted) {
  14672. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14673. ASSERT_TRUE(svr.is_valid());
  14674. svr.Get("/test", [](const Request &, Response &res) {
  14675. res.set_content("ok", "text/plain");
  14676. });
  14677. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14678. auto se = detail::scope_exit([&] {
  14679. svr.stop();
  14680. t.join();
  14681. });
  14682. svr.wait_until_ready();
  14683. SSLClient cli(HOST, PORT);
  14684. cli.enable_server_certificate_verification(false);
  14685. cli.set_connection_timeout(30);
  14686. bool callback_called = false;
  14687. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14688. EXPECT_NE(session, nullptr);
  14689. callback_called = true;
  14690. return SSLVerifierResponse::CertificateAccepted;
  14691. });
  14692. auto res = cli.Get("/test");
  14693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14694. EXPECT_EQ(200, res->status);
  14695. EXPECT_TRUE(callback_called);
  14696. }
  14697. TEST(SessionVerifierTest, CertificateRejected) {
  14698. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14699. ASSERT_TRUE(svr.is_valid());
  14700. svr.Get("/test", [](const Request &, Response &res) {
  14701. res.set_content("ok", "text/plain");
  14702. });
  14703. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14704. auto se = detail::scope_exit([&] {
  14705. svr.stop();
  14706. t.join();
  14707. });
  14708. svr.wait_until_ready();
  14709. SSLClient cli(HOST, PORT);
  14710. cli.enable_server_certificate_verification(false);
  14711. cli.set_connection_timeout(30);
  14712. bool callback_called = false;
  14713. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14714. EXPECT_NE(session, nullptr);
  14715. callback_called = true;
  14716. return SSLVerifierResponse::CertificateRejected;
  14717. });
  14718. auto res = cli.Get("/test");
  14719. EXPECT_FALSE(res);
  14720. EXPECT_TRUE(callback_called);
  14721. }
  14722. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  14723. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14724. ASSERT_TRUE(svr.is_valid());
  14725. svr.Get("/test", [](const Request &, Response &res) {
  14726. res.set_content("ok", "text/plain");
  14727. });
  14728. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14729. auto se = detail::scope_exit([&] {
  14730. svr.stop();
  14731. t.join();
  14732. });
  14733. svr.wait_until_ready();
  14734. // NoDecisionMade with verification disabled should succeed (no default check)
  14735. SSLClient cli(HOST, PORT);
  14736. cli.enable_server_certificate_verification(false);
  14737. cli.set_connection_timeout(30);
  14738. bool callback_called = false;
  14739. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14740. EXPECT_NE(session, nullptr);
  14741. callback_called = true;
  14742. return SSLVerifierResponse::NoDecisionMade;
  14743. });
  14744. auto res = cli.Get("/test");
  14745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14746. EXPECT_EQ(200, res->status);
  14747. EXPECT_TRUE(callback_called);
  14748. }
  14749. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  14750. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  14751. ASSERT_TRUE(svr.is_valid());
  14752. svr.Get("/test", [](const Request &, Response &res) {
  14753. res.set_content("ok", "text/plain");
  14754. });
  14755. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  14756. auto se = detail::scope_exit([&] {
  14757. svr.stop();
  14758. t.join();
  14759. });
  14760. svr.wait_until_ready();
  14761. // NoDecisionMade with verification enabled should fail (self-signed cert).
  14762. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  14763. // so we only check that the request fails, not whether the callback was
  14764. // called.
  14765. SSLClient cli(HOST, PORT);
  14766. cli.enable_server_certificate_verification(true);
  14767. cli.set_connection_timeout(30);
  14768. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  14769. EXPECT_NE(session, nullptr);
  14770. return SSLVerifierResponse::NoDecisionMade;
  14771. });
  14772. auto res = cli.Get("/test");
  14773. EXPECT_FALSE(res);
  14774. }
  14775. TEST(SSLClientServerTest, ClientCAListFromPem) {
  14776. // Test SSL server using PemMemory constructor with client CA certificates
  14777. // Read PEM files
  14778. std::string server_cert_pem, server_key_pem, client_ca_pem;
  14779. read_file(SERVER_CERT_FILE, server_cert_pem);
  14780. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  14781. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  14782. // Create SSLServer with PemMemory constructor including client CA
  14783. SSLServer::PemMemory server_pem = {
  14784. server_cert_pem.c_str(),
  14785. server_cert_pem.size(),
  14786. server_key_pem.c_str(),
  14787. server_key_pem.size(),
  14788. client_ca_pem.c_str(),
  14789. client_ca_pem.size(),
  14790. nullptr // no password for server key
  14791. };
  14792. SSLServer svr(server_pem);
  14793. ASSERT_TRUE(svr.is_valid());
  14794. // No SSL error should be recorded for valid setup
  14795. EXPECT_EQ(0, svr.ssl_last_error());
  14796. // Set up server endpoints
  14797. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  14798. res.set_content("ok", "text/plain");
  14799. });
  14800. // Start server in a thread
  14801. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  14802. svr.wait_until_ready();
  14803. // Connect with client certificate (using constructor with paths)
  14804. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  14805. cli.enable_server_certificate_verification(false);
  14806. auto res = cli.Get("/test-pem-ca");
  14807. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14808. EXPECT_EQ(200, res->status);
  14809. EXPECT_EQ("ok", res->body);
  14810. svr.stop();
  14811. server_thread.join();
  14812. }
  14813. #endif
  14814. #ifdef _WIN32
  14815. TEST(CleanupTest, WSACleanup) {
  14816. int ret = WSACleanup();
  14817. ASSERT_EQ(0, ret);
  14818. }
  14819. #endif
  14820. #ifndef CPPHTTPLIB_SSL_ENABLED
  14821. TEST(NoSSLSupport, SimpleInterface) {
  14822. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  14823. }
  14824. #endif
  14825. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  14826. TEST(InvalidScheme, SimpleInterface) {
  14827. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  14828. }
  14829. #endif
  14830. TEST(NoScheme, SimpleInterface) {
  14831. Client cli("yahoo.com:80");
  14832. ASSERT_TRUE(cli.is_valid());
  14833. }
  14834. TEST(SendAPI, SimpleInterface_Online) {
  14835. Client cli("http://yahoo.com");
  14836. Request req;
  14837. req.method = "GET";
  14838. req.path = "/";
  14839. auto res = cli.send(req);
  14840. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14841. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14842. }
  14843. TEST(SendAPI, WithParamsInRequest) {
  14844. Server svr;
  14845. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  14846. EXPECT_TRUE(req.has_param("test"));
  14847. EXPECT_EQ("test_value", req.get_param_value("test"));
  14848. });
  14849. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  14850. auto se = detail::scope_exit([&] {
  14851. svr.stop();
  14852. t.join();
  14853. ASSERT_FALSE(svr.is_running());
  14854. });
  14855. svr.wait_until_ready();
  14856. Client cli(HOST, PORT);
  14857. {
  14858. Request req;
  14859. req.method = "GET";
  14860. req.path = "/";
  14861. req.params.emplace("test", "test_value");
  14862. auto res = cli.send(req);
  14863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14864. }
  14865. {
  14866. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  14867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14868. }
  14869. }
  14870. TEST(ClientImplMethods, GetSocketTest) {
  14871. httplib::Server svr;
  14872. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  14873. res.status = StatusCode::OK_200;
  14874. });
  14875. auto port = svr.bind_to_any_port("127.0.0.1");
  14876. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14877. auto se = detail::scope_exit([&] {
  14878. svr.stop();
  14879. thread.join();
  14880. ASSERT_FALSE(svr.is_running());
  14881. });
  14882. svr.wait_until_ready();
  14883. {
  14884. httplib::Client cli("127.0.0.1", port);
  14885. cli.set_keep_alive(true);
  14886. // Use the behavior of cpp-httplib of opening the connection
  14887. // only when the first request happens. If that changes,
  14888. // this test would be obsolete.
  14889. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  14890. // This also implicitly tests the server. But other tests would fail much
  14891. // earlier than this one to be considered.
  14892. auto res = cli.Get("/");
  14893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14894. EXPECT_EQ(StatusCode::OK_200, res->status);
  14895. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  14896. }
  14897. }
  14898. #ifdef CPPHTTPLIB_SSL_ENABLED
  14899. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  14900. Client cli("http://yahoo.com");
  14901. auto res = cli.Get("/");
  14902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14903. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14904. cli.set_follow_location(true);
  14905. res = cli.Get("/");
  14906. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14907. EXPECT_EQ(StatusCode::OK_200, res->status);
  14908. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14909. }
  14910. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  14911. Client cli("https://yahoo.com");
  14912. auto res = cli.Get("/");
  14913. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14914. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14915. cli.set_follow_location(true);
  14916. res = cli.Get("/");
  14917. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14918. EXPECT_EQ(StatusCode::OK_200, res->status);
  14919. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14920. }
  14921. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  14922. Client cli("https://yahoo.com");
  14923. auto res = cli.Get("/");
  14924. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14925. ASSERT_FALSE(!res);
  14926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14927. ASSERT_FALSE(res == nullptr);
  14928. ASSERT_TRUE(res != nullptr);
  14929. EXPECT_EQ(Error::Success, res.error());
  14930. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  14931. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  14932. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  14933. cli.set_follow_location(true);
  14934. res = cli.Get("/");
  14935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14936. EXPECT_EQ(Error::Success, res.error());
  14937. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  14938. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  14939. EXPECT_EQ(StatusCode::OK_200, res->status);
  14940. EXPECT_EQ("https://www.yahoo.com/", res->location);
  14941. }
  14942. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  14943. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  14944. Client cli("https://cdnjs.cloudflare.com");
  14945. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  14946. Headers{{"Accept-Encoding", "br"}});
  14947. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14948. EXPECT_EQ(StatusCode::OK_200, res->status);
  14949. EXPECT_EQ(287630U, res->body.size());
  14950. EXPECT_EQ("application/javascript; charset=utf-8",
  14951. res->get_header_value("Content-Type"));
  14952. }
  14953. #endif
  14954. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  14955. #undef REDIR_HOST // Silence compiler warning
  14956. #define REDIR_HOST "https://httpbingo.org"
  14957. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  14958. Client cli(REDIR_HOST);
  14959. cli.set_follow_location(true);
  14960. auto res =
  14961. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  14962. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14963. EXPECT_EQ(StatusCode::OK_200, res->status);
  14964. }
  14965. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  14966. Client cli(REDIR_HOST);
  14967. cli.set_follow_location(true);
  14968. Params params;
  14969. params.emplace("url", "http://example.com");
  14970. params.emplace("status_code", "302");
  14971. auto res = cli.Get(REDIR_PATH, params, Headers{});
  14972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14973. EXPECT_EQ(StatusCode::OK_200, res->status);
  14974. }
  14975. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  14976. Client cli(REDIR_HOST);
  14977. cli.set_follow_location(true);
  14978. Params params;
  14979. params.emplace("url", "http://example.com");
  14980. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  14981. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14982. EXPECT_EQ(StatusCode::OK_200, res->status);
  14983. }
  14984. TEST(HttpToHttpsRedirectTest, CertFile) {
  14985. auto ssl_port = PORT + 1;
  14986. Server svr;
  14987. ASSERT_TRUE(svr.is_valid());
  14988. svr.Get("/index", [&](const Request &, Response &res) {
  14989. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  14990. "/index");
  14991. svr.stop();
  14992. });
  14993. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  14994. ASSERT_TRUE(ssl_svr.is_valid());
  14995. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  14996. res.set_content("test", "text/plain");
  14997. ssl_svr.stop();
  14998. });
  14999. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15000. thread t2 =
  15001. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  15002. auto se = detail::scope_exit([&] {
  15003. t2.join();
  15004. t.join();
  15005. ASSERT_FALSE(svr.is_running());
  15006. });
  15007. svr.wait_until_ready();
  15008. ssl_svr.wait_until_ready();
  15009. Client cli("127.0.0.1", PORT);
  15010. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  15011. cli.enable_server_certificate_verification(true);
  15012. cli.set_follow_location(true);
  15013. cli.set_connection_timeout(30);
  15014. auto res = cli.Get("/index");
  15015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15016. ASSERT_EQ(StatusCode::OK_200, res->status);
  15017. }
  15018. TEST(SSLClientRedirectTest, CertFile) {
  15019. auto ssl_port = PORT + 1;
  15020. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15021. ASSERT_TRUE(ssl_svr1.is_valid());
  15022. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15023. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15024. "/index");
  15025. ssl_svr1.stop();
  15026. });
  15027. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15028. ASSERT_TRUE(ssl_svr2.is_valid());
  15029. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15030. res.set_content("test", "text/plain");
  15031. ssl_svr2.stop();
  15032. });
  15033. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15034. thread t2 =
  15035. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15036. auto se = detail::scope_exit([&] {
  15037. t2.join();
  15038. t.join();
  15039. ASSERT_FALSE(ssl_svr1.is_running());
  15040. });
  15041. ssl_svr1.wait_until_ready();
  15042. ssl_svr2.wait_until_ready();
  15043. SSLClient cli("127.0.0.1", PORT);
  15044. std::string cert;
  15045. read_file(SERVER_CERT2_FILE, cert);
  15046. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15047. cli.enable_server_certificate_verification(true);
  15048. cli.set_follow_location(true);
  15049. cli.set_connection_timeout(30);
  15050. auto res = cli.Get("/index");
  15051. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15052. ASSERT_EQ(StatusCode::OK_200, res->status);
  15053. }
  15054. // Redirects from a server with SERVER_CERT2_FILE to one with target_cert on
  15055. // another port, so the client follows it with a new client.
  15056. static Result GetThroughTlsRedirectToDifferentPort(
  15057. const std::function<void(SSLClient &)> &setup,
  15058. const char *target_cert = SERVER_CERT2_FILE,
  15059. const char *target_key = SERVER_PRIVATE_KEY_FILE) {
  15060. auto ssl_port = PORT + 1;
  15061. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15062. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15063. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15064. "/index");
  15065. });
  15066. SSLServer ssl_svr2(target_cert, target_key);
  15067. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15068. res.set_content("test", "text/plain");
  15069. });
  15070. thread t = thread([&]() { ssl_svr1.listen("127.0.0.1", PORT); });
  15071. thread t2 = thread([&]() { ssl_svr2.listen("127.0.0.1", ssl_port); });
  15072. auto se = detail::scope_exit([&] {
  15073. ssl_svr2.stop();
  15074. ssl_svr1.stop();
  15075. t2.join();
  15076. t.join();
  15077. });
  15078. ssl_svr1.wait_until_ready();
  15079. ssl_svr2.wait_until_ready();
  15080. SSLClient cli("127.0.0.1", PORT);
  15081. cli.set_follow_location(true);
  15082. cli.set_connection_timeout(30);
  15083. setup(cli);
  15084. return cli.Get("/index");
  15085. }
  15086. TEST(SSLClientRedirectTest, KeepSessionVerifier) {
  15087. auto calls = 0;
  15088. auto res = GetThroughTlsRedirectToDifferentPort([&](SSLClient &cli) {
  15089. cli.enable_server_certificate_verification(false);
  15090. // Accept the first server only.
  15091. cli.set_session_verifier([&](tls::session_t) {
  15092. return ++calls == 1 ? SSLVerifierResponse::NoDecisionMade
  15093. : SSLVerifierResponse::CertificateRejected;
  15094. });
  15095. });
  15096. ASSERT_FALSE(res);
  15097. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15098. EXPECT_EQ(2, calls);
  15099. }
  15100. TEST(SSLClientRedirectTest, KeepServerCertificateVerifier) {
  15101. std::string pinned;
  15102. auto res = GetThroughTlsRedirectToDifferentPort(
  15103. [&](SSLClient &cli) {
  15104. cli.enable_server_certificate_verification(false);
  15105. // Pin the first certificate seen.
  15106. cli.set_server_certificate_verifier([&](const tls::VerifyContext &ctx) {
  15107. if (pinned.empty()) { pinned = ctx.serial(); }
  15108. return ctx.serial() == pinned;
  15109. });
  15110. },
  15111. // A certificate other than the first server's.
  15112. SERVER_CERT_FILE);
  15113. EXPECT_FALSE(res);
  15114. EXPECT_FALSE(pinned.empty());
  15115. }
  15116. TEST(SSLClientRedirectTest, KeepCaCertStore) {
  15117. auto res = GetThroughTlsRedirectToDifferentPort([](SSLClient &cli) {
  15118. std::string cert;
  15119. read_file(SERVER_CERT2_FILE, cert);
  15120. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15121. });
  15122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15123. EXPECT_EQ(StatusCode::OK_200, res->status);
  15124. }
  15125. // The target's certificate is signed by the root CA, which the first server's
  15126. // is not. Its name is not checked, as it carries none of 127.0.0.1.
  15127. TEST(SSLClientRedirectTest, KeepEveryCaCertPem) {
  15128. auto res = GetThroughTlsRedirectToDifferentPort(
  15129. [](SSLClient &cli) {
  15130. std::string root_ca, cert;
  15131. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15132. read_file(SERVER_CERT2_FILE, cert);
  15133. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15134. cli.load_ca_cert_store(cert.data(), cert.size());
  15135. cli.enable_server_hostname_verification(false);
  15136. },
  15137. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15139. EXPECT_EQ(StatusCode::OK_200, res->status);
  15140. }
  15141. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15142. // set_ca_cert_store() replaces the root CA loaded before it, so the target is
  15143. // not trusted after the redirect either. (wolfSSL adds the store instead.)
  15144. TEST(SSLClientRedirectTest, CaCertStoreReplacesEarlierPem) {
  15145. auto res = GetThroughTlsRedirectToDifferentPort(
  15146. [](SSLClient &cli) {
  15147. std::string root_ca, cert;
  15148. read_file(CLIENT_CA_CERT_FILE, root_ca);
  15149. read_file(SERVER_CERT2_FILE, cert);
  15150. cli.load_ca_cert_store(root_ca.data(), root_ca.size());
  15151. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15152. cli.enable_server_hostname_verification(false);
  15153. },
  15154. CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  15155. ASSERT_FALSE(res);
  15156. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15157. }
  15158. #endif
  15159. #endif
  15160. #ifdef CPPHTTPLIB_SSL_ENABLED
  15161. // Test that set_ca_cert_store() skips system certs (consistent with
  15162. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  15163. // should be trusted - system certs should NOT be loaded.
  15164. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  15165. // Load a specific cert that is NOT a system CA cert
  15166. std::string cert;
  15167. read_file(SERVER_CERT2_FILE, cert);
  15168. SSLClient cli("google.com");
  15169. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15170. cli.enable_server_certificate_verification(true);
  15171. // This should FAIL because:
  15172. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  15173. // 2. System certs should NOT be loaded when custom store is set
  15174. // If system certs WERE loaded, this would succeed
  15175. auto res = cli.Get("/");
  15176. ASSERT_FALSE(res);
  15177. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15178. }
  15179. // Same as above, but through the native store handle path. Regression test:
  15180. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  15181. // merged system certs into the user-provided store.
  15182. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  15183. std::string cert;
  15184. read_file(SERVER_CERT2_FILE, cert);
  15185. SSLClient cli("google.com");
  15186. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15187. cli.enable_server_certificate_verification(true);
  15188. auto res = cli.Get("/");
  15189. ASSERT_FALSE(res);
  15190. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15191. }
  15192. // A custom store set via the native handle must still verify a server whose
  15193. // cert it does contain.
  15194. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  15195. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15196. ASSERT_TRUE(svr.is_valid());
  15197. svr.Get("/test", [&](const Request &, Response &res) {
  15198. res.set_content("test", "text/plain");
  15199. });
  15200. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15201. auto se = detail::scope_exit([&] {
  15202. svr.stop();
  15203. t.join();
  15204. ASSERT_FALSE(svr.is_running());
  15205. });
  15206. svr.wait_until_ready();
  15207. SSLClient cli("127.0.0.1", PORT);
  15208. std::string cert;
  15209. read_file(SERVER_CERT2_FILE, cert);
  15210. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  15211. cli.enable_server_certificate_verification(true);
  15212. cli.set_connection_timeout(30);
  15213. auto res = cli.Get("/test");
  15214. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15215. ASSERT_EQ(StatusCode::OK_200, res->status);
  15216. }
  15217. // CA certs loaded through the universal Client must be transferred to the
  15218. // client created internally for following an HTTPS redirect. Regression test:
  15219. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  15220. // the CA data for redirect transfer.
  15221. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  15222. auto ssl_port = PORT + 1;
  15223. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15224. ASSERT_TRUE(ssl_svr1.is_valid());
  15225. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  15226. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  15227. "/index");
  15228. });
  15229. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15230. ASSERT_TRUE(ssl_svr2.is_valid());
  15231. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  15232. res.set_content("test", "text/plain");
  15233. });
  15234. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  15235. thread t2 =
  15236. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  15237. auto se = detail::scope_exit([&] {
  15238. ssl_svr2.stop();
  15239. ssl_svr1.stop();
  15240. t2.join();
  15241. t.join();
  15242. ASSERT_FALSE(ssl_svr1.is_running());
  15243. });
  15244. ssl_svr1.wait_until_ready();
  15245. ssl_svr2.wait_until_ready();
  15246. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15247. std::string cert;
  15248. read_file(SERVER_CERT2_FILE, cert);
  15249. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15250. cli.enable_server_certificate_verification(true);
  15251. cli.set_follow_location(true);
  15252. cli.set_connection_timeout(30);
  15253. auto res = cli.Get("/index");
  15254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15255. ASSERT_EQ(StatusCode::OK_200, res->status);
  15256. }
  15257. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  15258. // so a host signed by a system CA verifies even though a custom CA is set
  15259. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  15260. std::string cert;
  15261. read_file(SERVER_CERT2_FILE, cert);
  15262. SSLClient cli("google.com");
  15263. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15264. cli.enable_system_ca(true);
  15265. cli.enable_server_certificate_verification(true);
  15266. auto res = cli.Get("/");
  15267. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15268. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15269. }
  15270. // The custom CA remains effective when combined with the system CA
  15271. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  15272. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15273. ASSERT_TRUE(svr.is_valid());
  15274. svr.Get("/test", [&](const Request &, Response &res) {
  15275. res.set_content("test", "text/plain");
  15276. });
  15277. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15278. auto se = detail::scope_exit([&] {
  15279. svr.stop();
  15280. t.join();
  15281. ASSERT_FALSE(svr.is_running());
  15282. });
  15283. svr.wait_until_ready();
  15284. SSLClient cli("127.0.0.1", PORT);
  15285. std::string cert;
  15286. read_file(SERVER_CERT2_FILE, cert);
  15287. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15288. cli.enable_system_ca(true);
  15289. cli.enable_server_certificate_verification(true);
  15290. cli.set_connection_timeout(30);
  15291. auto res = cli.Get("/test");
  15292. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15293. ASSERT_EQ(StatusCode::OK_200, res->status);
  15294. }
  15295. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  15296. // skip chain verification entirely (only the certificate identity was
  15297. // checked), so a server presenting an untrusted certificate with a matching
  15298. // IP SAN was accepted. The chain must be validated for IP hosts too.
  15299. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  15300. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15301. ASSERT_TRUE(svr.is_valid());
  15302. svr.Get("/test", [&](const Request &, Response &res) {
  15303. res.set_content("test", "text/plain");
  15304. });
  15305. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15306. auto se = detail::scope_exit([&] {
  15307. svr.stop();
  15308. t.join();
  15309. ASSERT_FALSE(svr.is_running());
  15310. });
  15311. svr.wait_until_ready();
  15312. SSLClient cli("127.0.0.1", PORT);
  15313. std::string cert;
  15314. // A trusted CA that did not sign the server certificate. The server cert
  15315. // (cert2) carries the matching IP SAN, so only chain validation can reject
  15316. // this connection.
  15317. read_file(CLIENT_CA_CERT_FILE, cert);
  15318. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15319. cli.enable_server_certificate_verification(true);
  15320. cli.set_connection_timeout(30);
  15321. auto res = cli.Get("/test");
  15322. ASSERT_FALSE(res);
  15323. }
  15324. #ifndef CPPHTTPLIB_WOLFSSL_SUPPORT
  15325. // A custom CA that brings no certificate still keeps the system CAs out, so a
  15326. // CA that failed to come through fails verification instead of trusting them.
  15327. // (wolfSSL does not list the system CAs it loaded.)
  15328. TEST(SSLClientTest, EmptyCustomCaKeepsSystemCasOut) {
  15329. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15330. ASSERT_TRUE(svr.is_valid());
  15331. auto port = svr.bind_to_any_port("127.0.0.1");
  15332. ASSERT_LT(0, port);
  15333. thread t = thread([&] { svr.listen_after_bind(); });
  15334. auto se = detail::scope_exit([&] {
  15335. svr.stop();
  15336. t.join();
  15337. ASSERT_FALSE(svr.is_running());
  15338. });
  15339. svr.wait_until_ready();
  15340. // The CAs a client trusts once its first request has loaded them
  15341. auto loaded_cas = [&](const std::function<void(Client &)> &setup) {
  15342. Client cli("https://127.0.0.1:" + std::to_string(port));
  15343. setup(cli);
  15344. cli.Get("/");
  15345. return tls::get_ca_names(cli.tls_context()).size();
  15346. };
  15347. EXPECT_EQ(0u, loaded_cas([](Client &cli) { cli.load_ca_cert_store("", 0); }));
  15348. EXPECT_EQ(0u,
  15349. loaded_cas([](Client &cli) { cli.set_ca_cert_store(nullptr); }));
  15350. }
  15351. #endif
  15352. // A TLS setting changed between requests applies to the next one, not just to
  15353. // the next connection
  15354. TEST(SSLClientTest, TlsSettingChangeClosesKeptAliveConnection) {
  15355. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15356. ASSERT_TRUE(svr.is_valid());
  15357. svr.Get("/", [](const Request &req, Response &res) {
  15358. res.set_content(std::to_string(req.remote_port), "text/plain");
  15359. });
  15360. auto port = svr.bind_to_any_port("127.0.0.1");
  15361. ASSERT_LT(0, port);
  15362. thread t = thread([&] { svr.listen_after_bind(); });
  15363. auto se = detail::scope_exit([&] {
  15364. svr.stop();
  15365. t.join();
  15366. ASSERT_FALSE(svr.is_running());
  15367. });
  15368. svr.wait_until_ready();
  15369. SSLClient cli("127.0.0.1", port);
  15370. cli.set_keep_alive(true);
  15371. cli.set_ca_cert_path(CLIENT_CA_CERT_FILE); // does not trust cert2.pem
  15372. cli.enable_server_certificate_verification(false);
  15373. // The port the request went out from, so a new one means a new connection
  15374. auto client_port = [&] {
  15375. auto res = cli.Get("/");
  15376. return res ? res->body : std::string();
  15377. };
  15378. auto last = client_port();
  15379. ASSERT_FALSE(last.empty());
  15380. // Setting a value it already has keeps the connection
  15381. cli.enable_server_certificate_verification(false);
  15382. cli.enable_server_hostname_verification(true);
  15383. EXPECT_EQ(last, client_port());
  15384. cli.enable_server_certificate_verification(true);
  15385. auto res = cli.Get("/");
  15386. EXPECT_FALSE(res);
  15387. EXPECT_EQ(Error::SSLServerVerification, res.error());
  15388. std::string ca;
  15389. read_file(SERVER_CERT2_FILE, ca);
  15390. cli.load_ca_cert_store(ca.c_str(), ca.size());
  15391. last = client_port();
  15392. ASSERT_FALSE(last.empty());
  15393. std::vector<std::function<void()>> setters = {
  15394. [&] { cli.enable_server_hostname_verification(false); },
  15395. [&] { cli.load_ca_cert_store(ca.c_str(), ca.size()); },
  15396. [&] {
  15397. cli.set_ca_cert_store(tls::create_ca_store(ca.c_str(), ca.size()));
  15398. },
  15399. [&] {
  15400. cli.set_server_certificate_verifier(
  15401. [](const tls::VerifyContext &) { return true; });
  15402. },
  15403. [&] {
  15404. cli.set_session_verifier(
  15405. [](tls::session_t) { return SSLVerifierResponse::NoDecisionMade; });
  15406. },
  15407. };
  15408. for (const auto &setter : setters) {
  15409. setter();
  15410. auto next = client_port();
  15411. ASSERT_FALSE(next.empty());
  15412. EXPECT_NE(last, next);
  15413. last = next;
  15414. }
  15415. cli.set_session_verifier(
  15416. [](tls::session_t) { return SSLVerifierResponse::CertificateRejected; });
  15417. auto handle = cli.open_stream("GET", "/");
  15418. EXPECT_FALSE(handle.is_valid());
  15419. EXPECT_EQ(Error::SSLServerVerification, handle.error);
  15420. }
  15421. // A PEM given to create_ca_store() needs no NUL after it
  15422. TEST(SSLClientTest, CreateCaStoreFromPemWithoutNul) {
  15423. std::string pem;
  15424. read_file(SERVER_CERT2_FILE, pem);
  15425. auto buf = pem + "X";
  15426. auto store = tls::create_ca_store(buf.data(), pem.size());
  15427. EXPECT_TRUE(store != nullptr);
  15428. SSLClient cli("localhost");
  15429. cli.set_ca_cert_store(store);
  15430. }
  15431. // enable_system_ca(false) prevents system CA loading entirely
  15432. TEST(SSLClientTest, DisableSystemCa_Online) {
  15433. SSLClient cli("google.com");
  15434. cli.enable_system_ca(false);
  15435. cli.enable_server_certificate_verification(true);
  15436. auto res = cli.Get("/");
  15437. ASSERT_FALSE(res);
  15438. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  15439. // itself when the CA chain is empty
  15440. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  15441. res.error() == Error::SSLConnection);
  15442. }
  15443. // The universal Client forwards enable_system_ca()
  15444. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  15445. std::string cert;
  15446. read_file(SERVER_CERT2_FILE, cert);
  15447. Client cli("https://google.com");
  15448. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15449. cli.enable_system_ca(true);
  15450. cli.enable_server_certificate_verification(true);
  15451. auto res = cli.Get("/");
  15452. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15453. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  15454. }
  15455. // The system CA policy must carry over to the client created internally for
  15456. // following a cross-host HTTPS redirect
  15457. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  15458. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  15459. ASSERT_TRUE(svr.is_valid());
  15460. svr.Get("/index", [&](const Request &, Response &res) {
  15461. res.set_redirect("https://www.google.com/");
  15462. });
  15463. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  15464. auto se = detail::scope_exit([&] {
  15465. svr.stop();
  15466. t.join();
  15467. ASSERT_FALSE(svr.is_running());
  15468. });
  15469. svr.wait_until_ready();
  15470. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  15471. std::string cert;
  15472. read_file(SERVER_CERT2_FILE, cert);
  15473. cli.load_ca_cert_store(cert.c_str(), cert.size());
  15474. cli.enable_system_ca(true);
  15475. cli.enable_server_certificate_verification(true);
  15476. cli.set_follow_location(true);
  15477. cli.set_connection_timeout(30);
  15478. // Receiving any response proves the redirect client completed the TLS
  15479. // handshake with a system-CA-signed host
  15480. auto res = cli.Get("/index");
  15481. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15482. }
  15483. TEST(MultipartFormDataTest, LargeData) {
  15484. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15485. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  15486. const ContentReader &content_reader) {
  15487. if (req.is_multipart_form_data()) {
  15488. std::vector<FormData> items;
  15489. content_reader(
  15490. [&](const FormData &file) {
  15491. items.push_back(file);
  15492. return true;
  15493. },
  15494. [&](const char *data, size_t data_length) {
  15495. items.back().content.append(data, data_length);
  15496. return true;
  15497. });
  15498. EXPECT_TRUE(std::string(items[0].name) == "document");
  15499. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15500. EXPECT_TRUE(items[0].filename == "2MB_data");
  15501. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15502. EXPECT_TRUE(items[1].name == "hello");
  15503. EXPECT_TRUE(items[1].content == "world");
  15504. EXPECT_TRUE(items[1].filename == "");
  15505. EXPECT_TRUE(items[1].content_type == "");
  15506. } else {
  15507. std::string body;
  15508. content_reader([&](const char *data, size_t data_length) {
  15509. body.append(data, data_length);
  15510. return true;
  15511. });
  15512. }
  15513. });
  15514. auto port = svr.bind_to_any_port(HOST);
  15515. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15516. auto se = detail::scope_exit([&] {
  15517. svr.stop();
  15518. t.join();
  15519. ASSERT_FALSE(svr.is_running());
  15520. });
  15521. svr.wait_until_ready();
  15522. {
  15523. std::string data(1024 * 1024 * 2, '.');
  15524. std::stringstream buffer;
  15525. buffer << data;
  15526. SSLClient cli(HOST, port);
  15527. cli.enable_server_certificate_verification(false);
  15528. UploadFormDataItems items{
  15529. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15530. {"hello", "world", "", ""},
  15531. };
  15532. auto res = cli.Post("/post", items);
  15533. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15534. ASSERT_EQ(StatusCode::OK_200, res->status);
  15535. }
  15536. }
  15537. TEST(MultipartFormDataTest, DataProviderItems) {
  15538. std::random_device seed_gen;
  15539. std::mt19937 random(seed_gen());
  15540. std::string rand1;
  15541. rand1.resize(1000);
  15542. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  15543. std::string rand2;
  15544. rand2.resize(3000);
  15545. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  15546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15547. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  15548. const ContentReader &content_reader) {
  15549. ASSERT_FALSE(req.is_multipart_form_data());
  15550. std::string body;
  15551. content_reader([&](const char *data, size_t data_length) {
  15552. body.append(data, data_length);
  15553. return true;
  15554. });
  15555. EXPECT_EQ(body, "");
  15556. });
  15557. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  15558. const ContentReader &content_reader) {
  15559. ASSERT_TRUE(req.is_multipart_form_data());
  15560. std::vector<FormData> items;
  15561. content_reader(
  15562. [&](const FormData &file) {
  15563. items.push_back(file);
  15564. return true;
  15565. },
  15566. [&](const char *data, size_t data_length) {
  15567. items.back().content.append(data, data_length);
  15568. return true;
  15569. });
  15570. ASSERT_TRUE(items.size() == 2);
  15571. EXPECT_EQ(std::string(items[0].name), "name1");
  15572. EXPECT_EQ(items[0].content, "Testing123");
  15573. EXPECT_EQ(items[0].filename, "filename1");
  15574. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15575. EXPECT_EQ(items[1].name, "name2");
  15576. EXPECT_EQ(items[1].content, "Testing456");
  15577. EXPECT_EQ(items[1].filename, "");
  15578. EXPECT_EQ(items[1].content_type, "");
  15579. });
  15580. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  15581. const ContentReader &content_reader) {
  15582. ASSERT_TRUE(req.is_multipart_form_data());
  15583. std::vector<FormData> items;
  15584. content_reader(
  15585. [&](const FormData &file) {
  15586. items.push_back(file);
  15587. return true;
  15588. },
  15589. [&](const char *data, size_t data_length) {
  15590. items.back().content.append(data, data_length);
  15591. return true;
  15592. });
  15593. ASSERT_TRUE(items.size() == 2);
  15594. EXPECT_EQ(items[0].name, "name3");
  15595. EXPECT_EQ(items[0].content, rand1);
  15596. EXPECT_EQ(items[0].filename, "filename3");
  15597. EXPECT_EQ(items[0].content_type, "");
  15598. EXPECT_EQ(items[1].name, "name4");
  15599. EXPECT_EQ(items[1].content, rand2);
  15600. EXPECT_EQ(items[1].filename, "filename4");
  15601. EXPECT_EQ(items[1].content_type, "");
  15602. });
  15603. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  15604. const ContentReader &content_reader) {
  15605. ASSERT_TRUE(req.is_multipart_form_data());
  15606. std::vector<FormData> items;
  15607. content_reader(
  15608. [&](const FormData &file) {
  15609. items.push_back(file);
  15610. return true;
  15611. },
  15612. [&](const char *data, size_t data_length) {
  15613. items.back().content.append(data, data_length);
  15614. return true;
  15615. });
  15616. ASSERT_TRUE(items.size() == 4);
  15617. EXPECT_EQ(std::string(items[0].name), "name1");
  15618. EXPECT_EQ(items[0].content, "Testing123");
  15619. EXPECT_EQ(items[0].filename, "filename1");
  15620. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  15621. EXPECT_EQ(items[1].name, "name2");
  15622. EXPECT_EQ(items[1].content, "Testing456");
  15623. EXPECT_EQ(items[1].filename, "");
  15624. EXPECT_EQ(items[1].content_type, "");
  15625. EXPECT_EQ(items[2].name, "name3");
  15626. EXPECT_EQ(items[2].content, rand1);
  15627. EXPECT_EQ(items[2].filename, "filename3");
  15628. EXPECT_EQ(items[2].content_type, "");
  15629. EXPECT_EQ(items[3].name, "name4");
  15630. EXPECT_EQ(items[3].content, rand2);
  15631. EXPECT_EQ(items[3].filename, "filename4");
  15632. EXPECT_EQ(items[3].content_type, "");
  15633. });
  15634. auto port = svr.bind_to_any_port("localhost");
  15635. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15636. auto se = detail::scope_exit([&] {
  15637. svr.stop();
  15638. t.join();
  15639. ASSERT_FALSE(svr.is_running());
  15640. });
  15641. svr.wait_until_ready();
  15642. {
  15643. SSLClient cli("localhost", port);
  15644. cli.enable_server_certificate_verification(false);
  15645. UploadFormDataItems items{
  15646. {"name1", "Testing123", "filename1", "application/octet-stream"},
  15647. {"name2", "Testing456", "", ""}, // not a file
  15648. };
  15649. {
  15650. auto res = cli.Post("/post-none", {}, {}, {});
  15651. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15652. ASSERT_EQ(StatusCode::OK_200, res->status);
  15653. }
  15654. FormDataProviderItems providers;
  15655. {
  15656. auto res =
  15657. cli.Post("/post-items", {}, items, providers); // empty providers
  15658. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15659. ASSERT_EQ(StatusCode::OK_200, res->status);
  15660. }
  15661. providers.push_back({"name3",
  15662. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15663. // test the offset is given correctly at each step
  15664. if (!offset)
  15665. sink.os.write(rand1.data(), 30);
  15666. else if (offset == 30)
  15667. sink.os.write(rand1.data() + 30, 300);
  15668. else if (offset == 330)
  15669. sink.os.write(rand1.data() + 330, 670);
  15670. else if (offset == rand1.size())
  15671. sink.done();
  15672. return true;
  15673. },
  15674. "filename3",
  15675. {}});
  15676. providers.push_back({"name4",
  15677. [&](size_t offset, httplib::DataSink &sink) -> bool {
  15678. // test the offset is given correctly at each step
  15679. if (!offset)
  15680. sink.os.write(rand2.data(), 2000);
  15681. else if (offset == 2000)
  15682. sink.os.write(rand2.data() + 2000, 1);
  15683. else if (offset == 2001)
  15684. sink.os.write(rand2.data() + 2001, 999);
  15685. else if (offset == rand2.size())
  15686. sink.done();
  15687. return true;
  15688. },
  15689. "filename4",
  15690. {}});
  15691. {
  15692. auto res = cli.Post("/post-providers", {}, {}, providers);
  15693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15694. ASSERT_EQ(StatusCode::OK_200, res->status);
  15695. }
  15696. {
  15697. auto res = cli.Post("/post-both", {}, items, providers);
  15698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15699. ASSERT_EQ(StatusCode::OK_200, res->status);
  15700. }
  15701. }
  15702. }
  15703. TEST(MultipartFormDataTest, BadHeader) {
  15704. Server svr;
  15705. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15706. res.set_content("ok", "text/plain");
  15707. });
  15708. thread t = thread([&] { svr.listen(HOST, PORT); });
  15709. auto se = detail::scope_exit([&] {
  15710. svr.stop();
  15711. t.join();
  15712. ASSERT_FALSE(svr.is_running());
  15713. });
  15714. svr.wait_until_ready();
  15715. const std::string body =
  15716. "This is the preamble. It is to be ignored, though it\r\n"
  15717. "is a handy place for composition agents to include an\r\n"
  15718. "explanatory note to non-MIME conformant readers.\r\n"
  15719. "\r\n"
  15720. "\r\n"
  15721. "--simple boundary\r\n"
  15722. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15723. ": BAD...\r\n"
  15724. "\r\n"
  15725. "value1\r\n"
  15726. "--simple boundary\r\n"
  15727. "Content-Disposition: form-data; name=\"field2\"; "
  15728. "filename=\"example.txt\"\r\n"
  15729. "\r\n"
  15730. "value2\r\n"
  15731. "--simple boundary--\r\n"
  15732. "This is the epilogue. It is also to be ignored.\r\n";
  15733. std::string content_type =
  15734. R"(multipart/form-data; boundary="simple boundary")";
  15735. Client cli(HOST, PORT);
  15736. auto res = cli.Post("/post", body, content_type.c_str());
  15737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15738. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  15739. }
  15740. TEST(MultipartFormDataTest, WithPreamble) {
  15741. Server svr;
  15742. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  15743. res.set_content("ok", "text/plain");
  15744. });
  15745. thread t = thread([&] { svr.listen(HOST, PORT); });
  15746. auto se = detail::scope_exit([&] {
  15747. svr.stop();
  15748. t.join();
  15749. ASSERT_FALSE(svr.is_running());
  15750. });
  15751. svr.wait_until_ready();
  15752. const std::string body =
  15753. "This is the preamble. It is to be ignored, though it\r\n"
  15754. "is a handy place for composition agents to include an\r\n"
  15755. "explanatory note to non-MIME conformant readers.\r\n"
  15756. "\r\n"
  15757. "\r\n"
  15758. "--simple boundary\r\n"
  15759. "Content-Disposition: form-data; name=\"field1\"\r\n"
  15760. "\r\n"
  15761. "value1\r\n"
  15762. "--simple boundary\r\n"
  15763. "Content-Disposition: form-data; name=\"field2\"; "
  15764. "filename=\"example.txt\"\r\n"
  15765. "\r\n"
  15766. "value2\r\n"
  15767. "--simple boundary--\r\n"
  15768. "This is the epilogue. It is also to be ignored.\r\n";
  15769. std::string content_type =
  15770. R"(multipart/form-data; boundary="simple boundary")";
  15771. Client cli(HOST, PORT);
  15772. auto res = cli.Post("/post", body, content_type.c_str());
  15773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15774. EXPECT_EQ(StatusCode::OK_200, res->status);
  15775. }
  15776. TEST(MultipartFormDataTest, PostCustomBoundary) {
  15777. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15778. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  15779. const ContentReader &content_reader) {
  15780. if (req.is_multipart_form_data()) {
  15781. std::vector<FormData> items;
  15782. content_reader(
  15783. [&](const FormData &file) {
  15784. items.push_back(file);
  15785. return true;
  15786. },
  15787. [&](const char *data, size_t data_length) {
  15788. items.back().content.append(data, data_length);
  15789. return true;
  15790. });
  15791. EXPECT_TRUE(std::string(items[0].name) == "document");
  15792. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15793. EXPECT_TRUE(items[0].filename == "2MB_data");
  15794. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15795. EXPECT_TRUE(items[1].name == "hello");
  15796. EXPECT_TRUE(items[1].content == "world");
  15797. EXPECT_TRUE(items[1].filename == "");
  15798. EXPECT_TRUE(items[1].content_type == "");
  15799. } else {
  15800. std::string body;
  15801. content_reader([&](const char *data, size_t data_length) {
  15802. body.append(data, data_length);
  15803. return true;
  15804. });
  15805. }
  15806. });
  15807. auto port = svr.bind_to_any_port("localhost");
  15808. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15809. auto se = detail::scope_exit([&] {
  15810. svr.stop();
  15811. t.join();
  15812. ASSERT_FALSE(svr.is_running());
  15813. });
  15814. svr.wait_until_ready();
  15815. {
  15816. std::string data(1024 * 1024 * 2, '.');
  15817. std::stringstream buffer;
  15818. buffer << data;
  15819. SSLClient cli("localhost", port);
  15820. cli.enable_server_certificate_verification(false);
  15821. UploadFormDataItems items{
  15822. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15823. {"hello", "world", "", ""},
  15824. };
  15825. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  15826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15827. ASSERT_EQ(StatusCode::OK_200, res->status);
  15828. }
  15829. }
  15830. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  15831. std::string data(1024 * 1024 * 2, '&');
  15832. std::stringstream buffer;
  15833. buffer << data;
  15834. Client cli("https://localhost:8080");
  15835. UploadFormDataItems items{
  15836. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15837. {"hello", "world", "", ""},
  15838. };
  15839. for (const char &c : " \t\r\n") {
  15840. auto res =
  15841. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  15842. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15843. ASSERT_FALSE(res);
  15844. }
  15845. }
  15846. TEST(MultipartFormDataTest, PutFormData) {
  15847. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15848. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  15849. const ContentReader &content_reader) {
  15850. if (req.is_multipart_form_data()) {
  15851. std::vector<FormData> items;
  15852. content_reader(
  15853. [&](const FormData &file) {
  15854. items.push_back(file);
  15855. return true;
  15856. },
  15857. [&](const char *data, size_t data_length) {
  15858. items.back().content.append(data, data_length);
  15859. return true;
  15860. });
  15861. EXPECT_TRUE(std::string(items[0].name) == "document");
  15862. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15863. EXPECT_TRUE(items[0].filename == "2MB_data");
  15864. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15865. EXPECT_TRUE(items[1].name == "hello");
  15866. EXPECT_TRUE(items[1].content == "world");
  15867. EXPECT_TRUE(items[1].filename == "");
  15868. EXPECT_TRUE(items[1].content_type == "");
  15869. } else {
  15870. std::string body;
  15871. content_reader([&](const char *data, size_t data_length) {
  15872. body.append(data, data_length);
  15873. return true;
  15874. });
  15875. }
  15876. });
  15877. auto port = svr.bind_to_any_port("localhost");
  15878. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15879. auto se = detail::scope_exit([&] {
  15880. svr.stop();
  15881. t.join();
  15882. ASSERT_FALSE(svr.is_running());
  15883. });
  15884. svr.wait_until_ready();
  15885. {
  15886. std::string data(1024 * 1024 * 2, '&');
  15887. std::stringstream buffer;
  15888. buffer << data;
  15889. SSLClient cli("localhost", port);
  15890. cli.enable_server_certificate_verification(false);
  15891. UploadFormDataItems items{
  15892. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15893. {"hello", "world", "", ""},
  15894. };
  15895. auto res = cli.Put("/put", items);
  15896. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15897. ASSERT_EQ(StatusCode::OK_200, res->status);
  15898. }
  15899. }
  15900. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  15901. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15902. svr.Put("/put_customboundary",
  15903. [&](const Request &req, const Response & /*res*/,
  15904. const ContentReader &content_reader) {
  15905. if (req.is_multipart_form_data()) {
  15906. std::vector<FormData> items;
  15907. content_reader(
  15908. [&](const FormData &file) {
  15909. items.push_back(file);
  15910. return true;
  15911. },
  15912. [&](const char *data, size_t data_length) {
  15913. items.back().content.append(data, data_length);
  15914. return true;
  15915. });
  15916. EXPECT_TRUE(std::string(items[0].name) == "document");
  15917. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  15918. EXPECT_TRUE(items[0].filename == "2MB_data");
  15919. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  15920. EXPECT_TRUE(items[1].name == "hello");
  15921. EXPECT_TRUE(items[1].content == "world");
  15922. EXPECT_TRUE(items[1].filename == "");
  15923. EXPECT_TRUE(items[1].content_type == "");
  15924. } else {
  15925. std::string body;
  15926. content_reader([&](const char *data, size_t data_length) {
  15927. body.append(data, data_length);
  15928. return true;
  15929. });
  15930. }
  15931. });
  15932. auto port = svr.bind_to_any_port("localhost");
  15933. auto t = std::thread([&]() { svr.listen_after_bind(); });
  15934. auto se = detail::scope_exit([&] {
  15935. svr.stop();
  15936. t.join();
  15937. ASSERT_FALSE(svr.is_running());
  15938. });
  15939. svr.wait_until_ready();
  15940. {
  15941. std::string data(1024 * 1024 * 2, '&');
  15942. std::stringstream buffer;
  15943. buffer << data;
  15944. SSLClient cli("localhost", port);
  15945. cli.enable_server_certificate_verification(false);
  15946. UploadFormDataItems items{
  15947. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15948. {"hello", "world", "", ""},
  15949. };
  15950. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  15951. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15952. ASSERT_EQ(StatusCode::OK_200, res->status);
  15953. }
  15954. }
  15955. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  15956. std::string data(1024 * 1024 * 2, '&');
  15957. std::stringstream buffer;
  15958. buffer << data;
  15959. Client cli("https://localhost:8080");
  15960. cli.enable_server_certificate_verification(false);
  15961. UploadFormDataItems items{
  15962. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  15963. {"hello", "world", "", ""},
  15964. };
  15965. for (const char &c : " \t\r\n") {
  15966. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  15967. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  15968. ASSERT_FALSE(res);
  15969. }
  15970. }
  15971. TEST(MultipartFormDataTest, AlternateFilename) {
  15972. auto handled = false;
  15973. Server svr;
  15974. svr.Post("/test", [&](const Request &req, Response &res) {
  15975. ASSERT_EQ(2u, req.form.files.size());
  15976. ASSERT_EQ(1u, req.form.fields.size());
  15977. // Test files
  15978. const auto &file1 = req.form.get_file("file1");
  15979. ASSERT_EQ("file1", file1.name);
  15980. ASSERT_EQ("A.txt", file1.filename);
  15981. ASSERT_EQ("text/plain", file1.content_type);
  15982. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  15983. const auto &file2 = req.form.get_file("file2");
  15984. ASSERT_EQ("file2", file2.name);
  15985. ASSERT_EQ("a.html", file2.filename);
  15986. ASSERT_EQ("text/html", file2.content_type);
  15987. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  15988. file2.content);
  15989. // Test text field
  15990. const auto &text = req.form.get_field("text");
  15991. ASSERT_EQ("text default", text);
  15992. res.set_content("ok", "text/plain");
  15993. handled = true;
  15994. });
  15995. thread t = thread([&] { svr.listen(HOST, PORT); });
  15996. auto se = detail::scope_exit([&] {
  15997. svr.stop();
  15998. t.join();
  15999. ASSERT_FALSE(svr.is_running());
  16000. ASSERT_TRUE(handled);
  16001. });
  16002. svr.wait_until_ready();
  16003. auto req = "POST /test HTTP/1.1\r\n"
  16004. "Host: localhost\r\n"
  16005. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16006. "Content-Length: 399\r\n"
  16007. "\r\n"
  16008. "----------\r\n"
  16009. "Content-Disposition: form-data; name=\"text\"\r\n"
  16010. "\r\n"
  16011. "text default\r\n"
  16012. "----------\r\n"
  16013. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  16014. "filename=\"a.txt\"; name=\"file1\"\r\n"
  16015. "Content-Type: text/plain\r\n"
  16016. "\r\n"
  16017. "Content of a.txt.\r\n"
  16018. "\r\n"
  16019. "----------\r\n"
  16020. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  16021. "\"a.html\"\r\n"
  16022. "Content-Type: text/html\r\n"
  16023. "\r\n"
  16024. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  16025. "\r\n"
  16026. "------------\r\n";
  16027. ASSERT_TRUE(send_request(1, req));
  16028. }
  16029. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  16030. auto handled = false;
  16031. Server svr;
  16032. svr.Post("/test", [&](const Request &req, Response &res) {
  16033. // Case-insensitive "utf-8''" prefix with a long value
  16034. const auto &file = req.form.get_file("file1");
  16035. ASSERT_EQ("file1", file.name);
  16036. // 8000 chars exercises both the Content-Disposition parser and the
  16037. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  16038. // Prior to the fix, std::regex_match on this header would cause O(N)
  16039. // stack recursion in libstdc++, leading to SIGSEGV.
  16040. std::string expected_filename(8000, 'A');
  16041. ASSERT_EQ(expected_filename, file.filename);
  16042. res.set_content("ok", "text/plain");
  16043. handled = true;
  16044. });
  16045. thread t = thread([&] { svr.listen(HOST, PORT); });
  16046. auto se = detail::scope_exit([&] {
  16047. svr.stop();
  16048. t.join();
  16049. ASSERT_FALSE(svr.is_running());
  16050. ASSERT_TRUE(handled);
  16051. });
  16052. svr.wait_until_ready();
  16053. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  16054. // Regression test for GHSA-qq6v-r583-3h69
  16055. std::string long_filename(8000, 'A');
  16056. std::string body = "----------\r\n"
  16057. "Content-Disposition: form-data; name=\"file1\"; "
  16058. "filename*=\"Utf-8''" +
  16059. long_filename +
  16060. "\"\r\n"
  16061. "\r\n"
  16062. "hello\r\n"
  16063. "------------\r\n";
  16064. auto req = "POST /test HTTP/1.1\r\n"
  16065. "Host: localhost\r\n"
  16066. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16067. "Content-Length: " +
  16068. std::to_string(body.size()) + "\r\n\r\n" + body;
  16069. ASSERT_TRUE(send_request(1, req));
  16070. }
  16071. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  16072. auto handled = false;
  16073. Server svr;
  16074. svr.Post("/test", [&](const Request &req, Response &) {
  16075. ASSERT_EQ(2u, req.form.fields.size());
  16076. const auto &text1 = req.form.get_field("text1");
  16077. ASSERT_EQ("text1", text1);
  16078. const auto &text2 = req.form.get_field("text2");
  16079. ASSERT_EQ("text2", text2);
  16080. handled = true;
  16081. });
  16082. thread t = thread([&] { svr.listen(HOST, PORT); });
  16083. auto se = detail::scope_exit([&] {
  16084. svr.stop();
  16085. t.join();
  16086. ASSERT_FALSE(svr.is_running());
  16087. ASSERT_TRUE(handled);
  16088. });
  16089. svr.wait_until_ready();
  16090. auto req = "POST /test HTTP/1.1\r\n"
  16091. "Host: localhost\r\n"
  16092. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16093. "Content-Length: 146\r\n"
  16094. "\r\n----------\r\n"
  16095. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16096. "\r\n"
  16097. "text1"
  16098. "\r\n----------\r\n"
  16099. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16100. "\r\n"
  16101. "text2"
  16102. "\r\n------------";
  16103. std::string response;
  16104. ASSERT_TRUE(send_request(1, req, &response));
  16105. ASSERT_EQ("200", response.substr(9, 3));
  16106. }
  16107. TEST(MultipartFormDataTest, ContentLength) {
  16108. auto handled = false;
  16109. Server svr;
  16110. svr.Post("/test", [&](const Request &req, Response &) {
  16111. ASSERT_EQ(2u, req.form.fields.size());
  16112. const auto &text1 = req.form.get_field("text1");
  16113. ASSERT_EQ("text1", text1);
  16114. const auto &text2 = req.form.get_field("text2");
  16115. ASSERT_EQ("text2", text2);
  16116. handled = true;
  16117. });
  16118. thread t = thread([&] { svr.listen(HOST, PORT); });
  16119. auto se = detail::scope_exit([&] {
  16120. svr.stop();
  16121. t.join();
  16122. ASSERT_FALSE(svr.is_running());
  16123. ASSERT_TRUE(handled);
  16124. });
  16125. svr.wait_until_ready();
  16126. auto req = "POST /test HTTP/1.1\r\n"
  16127. "Host: localhost\r\n"
  16128. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16129. "Content-Length: 167\r\n"
  16130. "\r\n----------\r\n"
  16131. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16132. "Content-Length: 5\r\n"
  16133. "\r\n"
  16134. "text1"
  16135. "\r\n----------\r\n"
  16136. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16137. "\r\n"
  16138. "text2"
  16139. "\r\n------------\r\n";
  16140. std::string response;
  16141. ASSERT_TRUE(send_request(1, req, &response));
  16142. ASSERT_EQ("200", response.substr(9, 3));
  16143. }
  16144. TEST(MultipartFormDataTest, AccessPartHeaders) {
  16145. auto handled = false;
  16146. Server svr;
  16147. svr.Post("/test", [&](const Request &req, Response &) {
  16148. ASSERT_EQ(2u, req.form.fields.size());
  16149. const auto &text1 = req.form.get_field("text1");
  16150. ASSERT_EQ("text1", text1);
  16151. // TODO: Add header access for text fields if needed
  16152. const auto &text2 = req.form.get_field("text2");
  16153. ASSERT_EQ("text2", text2);
  16154. // TODO: Header access for text fields needs to be implemented
  16155. // auto &headers = it->second.headers;
  16156. // ASSERT_EQ(3U, headers.size());
  16157. // auto custom_header = headers.find("x-whatever");
  16158. // ASSERT_TRUE(custom_header != headers.end());
  16159. // ASSERT_NE("customvalue", custom_header->second);
  16160. // ASSERT_EQ("CustomValue", custom_header->second);
  16161. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  16162. handled = true;
  16163. });
  16164. thread t = thread([&] { svr.listen(HOST, PORT); });
  16165. auto se = detail::scope_exit([&] {
  16166. svr.stop();
  16167. t.join();
  16168. ASSERT_FALSE(svr.is_running());
  16169. ASSERT_TRUE(handled);
  16170. });
  16171. svr.wait_until_ready();
  16172. auto req = "POST /test HTTP/1.1\r\n"
  16173. "Host: localhost\r\n"
  16174. "Content-Type: multipart/form-data;boundary=--------\r\n"
  16175. "Content-Length: 232\r\n"
  16176. "\r\n----------\r\n"
  16177. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16178. "Content-Length: 5\r\n"
  16179. "X-Test: 1\r\n"
  16180. "\r\n"
  16181. "text1"
  16182. "\r\n----------\r\n"
  16183. "Content-Disposition: form-data; name=\"text2\"\r\n"
  16184. "Content-Type: text/plain\r\n"
  16185. "X-Whatever: CustomValue\r\n"
  16186. "\r\n"
  16187. "text2"
  16188. "\r\n------------\r\n"
  16189. "That should be disregarded. Not even read";
  16190. std::string response;
  16191. ASSERT_TRUE(send_request(1, req, &response));
  16192. ASSERT_EQ("200", response.substr(9, 3));
  16193. }
  16194. TEST(MultipartFormDataTest, LargeHeader) {
  16195. auto handled = false;
  16196. Server svr;
  16197. svr.Post("/test", [&](const Request &req, Response &) {
  16198. ASSERT_EQ(1u, req.form.fields.size());
  16199. const auto &text = req.form.get_field("name1");
  16200. ASSERT_EQ("text1", text);
  16201. handled = true;
  16202. });
  16203. thread t = thread([&] { svr.listen(HOST, PORT); });
  16204. auto se = detail::scope_exit([&] {
  16205. svr.stop();
  16206. t.join();
  16207. ASSERT_FALSE(svr.is_running());
  16208. ASSERT_TRUE(handled);
  16209. });
  16210. svr.wait_until_ready();
  16211. auto boundary = std::string("cpp-httplib-multipart-data");
  16212. std::string content = "--" + boundary +
  16213. "\r\n"
  16214. "Content-Disposition: form-data; name=\"name1\"\r\n"
  16215. "\r\n"
  16216. "text1\r\n"
  16217. "--" +
  16218. boundary + "--\r\n";
  16219. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  16220. "Host: localhost\r\n"
  16221. "Content-Type: multipart/form-data;boundary=" +
  16222. boundary +
  16223. "\r\n"
  16224. "Content-Length: " +
  16225. std::to_string(content.size()) +
  16226. "\r\n"
  16227. "Dummy-Header: ";
  16228. std::string header_suffix = "\r\n"
  16229. "\r\n";
  16230. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  16231. size_t header_dummy_size =
  16232. read_buff_size -
  16233. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  16234. auto header_dummy = std::string(header_dummy_size, '@');
  16235. auto req = header_prefix + header_dummy + header_suffix + content;
  16236. std::string response;
  16237. ASSERT_TRUE(send_request(1, req, &response));
  16238. ASSERT_EQ("200", response.substr(9, 3));
  16239. }
  16240. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  16241. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  16242. // (not chunked Transfer-Encoding) after the streaming refactor.
  16243. auto handled = false;
  16244. Server svr;
  16245. svr.Post("/upload", [&](const Request &req, Response &res) {
  16246. auto cl_it = req.headers.find("Content-Length");
  16247. EXPECT_TRUE(cl_it != req.headers.end());
  16248. auto te_it = req.headers.find("Transfer-Encoding");
  16249. EXPECT_TRUE(te_it == req.headers.end());
  16250. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  16251. res.set_content("ok", "text/plain");
  16252. handled = true;
  16253. });
  16254. auto port = svr.bind_to_any_port(HOST);
  16255. auto t = thread([&] { svr.listen_after_bind(); });
  16256. auto se = detail::scope_exit([&] {
  16257. svr.stop();
  16258. t.join();
  16259. ASSERT_FALSE(svr.is_running());
  16260. ASSERT_TRUE(handled);
  16261. });
  16262. svr.wait_until_ready();
  16263. UploadFormDataItems items = {
  16264. {"field1", "hello", "", "text/plain"},
  16265. {"file1", "world", "test.txt", "application/octet-stream"},
  16266. };
  16267. Client cli(HOST, port);
  16268. auto res = cli.Post("/upload", {}, items);
  16269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16270. EXPECT_EQ(StatusCode::OK_200, res->status);
  16271. }
  16272. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  16273. // Verify that make_multipart_content_provider coalesces many small segments
  16274. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  16275. constexpr size_t kItemCount = 1000;
  16276. UploadFormDataItems items;
  16277. items.reserve(kItemCount);
  16278. for (size_t i = 0; i < kItemCount; i++) {
  16279. items.push_back(
  16280. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16281. }
  16282. const std::string boundary = "----test-boundary";
  16283. auto content_length = detail::get_multipart_content_length(items, boundary);
  16284. auto provider = detail::make_multipart_content_provider(items, boundary);
  16285. // Drive the provider the same way write_content_with_progress does
  16286. size_t write_count = 0;
  16287. size_t total_bytes = 0;
  16288. DataSink sink;
  16289. size_t offset = 0;
  16290. sink.write = [&](const char *d, size_t l) -> bool {
  16291. (void)d;
  16292. write_count++;
  16293. total_bytes += l;
  16294. offset += l;
  16295. return true;
  16296. };
  16297. sink.is_writable = []() -> bool { return true; };
  16298. while (offset < content_length) {
  16299. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  16300. }
  16301. EXPECT_EQ(content_length, total_bytes);
  16302. // The total number of segments is 3 * kItemCount + 1 = 3001.
  16303. // With buffering into 64KB blocks, write_count should be much smaller.
  16304. auto segment_count = 3 * kItemCount + 1;
  16305. EXPECT_LT(write_count, segment_count / 10);
  16306. }
  16307. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  16308. // Integration test: send many UploadFormDataItems and verify the server
  16309. // receives all of them correctly (#2410).
  16310. constexpr size_t kItemCount = 500;
  16311. auto handled = false;
  16312. Server svr;
  16313. svr.Post("/upload", [&](const Request &req, Response &res) {
  16314. EXPECT_EQ(kItemCount, req.form.fields.size());
  16315. for (size_t i = 0; i < kItemCount; i++) {
  16316. auto key = "field" + std::to_string(i);
  16317. auto val = "value" + std::to_string(i);
  16318. auto it = req.form.fields.find(key);
  16319. if (it != req.form.fields.end()) {
  16320. EXPECT_EQ(val, it->second.content);
  16321. } else {
  16322. ADD_FAILURE() << "Missing field: " << key;
  16323. }
  16324. }
  16325. res.set_content("ok", "text/plain");
  16326. handled = true;
  16327. });
  16328. auto port = svr.bind_to_any_port(HOST);
  16329. auto t = thread([&] { svr.listen_after_bind(); });
  16330. auto se = detail::scope_exit([&] {
  16331. svr.stop();
  16332. t.join();
  16333. ASSERT_FALSE(svr.is_running());
  16334. ASSERT_TRUE(handled);
  16335. });
  16336. svr.wait_until_ready();
  16337. UploadFormDataItems items;
  16338. items.reserve(kItemCount);
  16339. for (size_t i = 0; i < kItemCount; i++) {
  16340. items.push_back(
  16341. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  16342. }
  16343. Client cli(HOST, port);
  16344. auto res = cli.Post("/upload", items);
  16345. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16346. EXPECT_EQ(StatusCode::OK_200, res->status);
  16347. }
  16348. TEST(MultipartFormDataTest, MakeFileProvider) {
  16349. // Verify make_file_provider sends a file's contents correctly.
  16350. const std::string file_content(4096, 'Z');
  16351. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  16352. {
  16353. std::ofstream ofs(tmp_path, std::ios::binary);
  16354. ofs.write(file_content.data(),
  16355. static_cast<std::streamsize>(file_content.size()));
  16356. }
  16357. auto handled = false;
  16358. Server svr;
  16359. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  16360. const ContentReader &content_reader) {
  16361. ASSERT_TRUE(req.is_multipart_form_data());
  16362. std::vector<FormData> items;
  16363. content_reader(
  16364. [&](const FormData &file) {
  16365. items.push_back(file);
  16366. return true;
  16367. },
  16368. [&](const char *data, size_t data_length) {
  16369. items.back().content.append(data, data_length);
  16370. return true;
  16371. });
  16372. ASSERT_EQ(1u, items.size());
  16373. EXPECT_EQ("myfile", items[0].name);
  16374. EXPECT_EQ("data.bin", items[0].filename);
  16375. EXPECT_EQ("application/octet-stream", items[0].content_type);
  16376. EXPECT_EQ(file_content, items[0].content);
  16377. handled = true;
  16378. });
  16379. auto port = svr.bind_to_any_port(HOST);
  16380. auto t = thread([&] { svr.listen_after_bind(); });
  16381. auto se = detail::scope_exit([&] {
  16382. svr.stop();
  16383. t.join();
  16384. ASSERT_FALSE(svr.is_running());
  16385. ASSERT_TRUE(handled);
  16386. std::remove(tmp_path.c_str());
  16387. });
  16388. svr.wait_until_ready();
  16389. FormDataProviderItems providers;
  16390. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  16391. "application/octet-stream"));
  16392. Client cli(HOST, port);
  16393. auto res = cli.Post("/upload", {}, {}, providers);
  16394. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16395. EXPECT_EQ(StatusCode::OK_200, res->status);
  16396. }
  16397. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  16398. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  16399. // (100) headers is rejected with a 400 Bad Request response.
  16400. Server svr;
  16401. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  16402. res.set_content("ok", "text/plain");
  16403. });
  16404. thread t = thread([&] { svr.listen(HOST, PORT); });
  16405. auto se = detail::scope_exit([&] {
  16406. svr.stop();
  16407. t.join();
  16408. ASSERT_FALSE(svr.is_running());
  16409. });
  16410. svr.wait_until_ready();
  16411. // Build a multipart part with 101 custom headers (exceeding
  16412. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  16413. std::stringstream body;
  16414. body << "--simpleboundary\r\n"
  16415. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  16416. for (int i = 0; i < 101; i++) {
  16417. body << "X-Custom-Header-" << i << ": value\r\n";
  16418. }
  16419. body << "\r\n"
  16420. << "value1\r\n"
  16421. << "--simpleboundary--\r\n";
  16422. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  16423. Client cli(HOST, PORT);
  16424. auto res = cli.Post("/post", body.str(), content_type.c_str());
  16425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16426. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16427. }
  16428. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  16429. // A body that never contains the declared boundary must not be accumulated
  16430. // while the parser waits for it. Buffering it would also make every read
  16431. // rescan everything seen so far, which is quadratic in the body size.
  16432. Server svr;
  16433. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16434. res.set_content("ok", "text/plain");
  16435. });
  16436. auto port = svr.bind_to_any_port(HOST);
  16437. thread t = thread([&] { svr.listen_after_bind(); });
  16438. auto se = detail::scope_exit([&] {
  16439. svr.stop();
  16440. t.join();
  16441. ASSERT_FALSE(svr.is_running());
  16442. });
  16443. svr.wait_until_ready();
  16444. Client cli(HOST, port);
  16445. cli.set_read_timeout(60, 0);
  16446. cli.set_write_timeout(60, 0);
  16447. // '-' is the worst case: it matches the first character of the boundary, so
  16448. // every position has to be checked against it.
  16449. auto post_dashes = [&](size_t size) {
  16450. const std::string body(size, '-');
  16451. auto start = std::chrono::steady_clock::now();
  16452. auto res =
  16453. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  16454. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  16455. std::chrono::steady_clock::now() - start)
  16456. .count();
  16457. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  16458. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  16459. return ms;
  16460. };
  16461. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  16462. // Windows.
  16463. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  16464. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  16465. // Comparing the two sizes rather than checking an absolute duration keeps
  16466. // this meaningful across build types and CI load, both of which move the
  16467. // absolute numbers by more than an order of magnitude. Four times the bytes
  16468. // costs about four times the time when parsing is linear, and about sixteen
  16469. // times when the body is buffered and rescanned.
  16470. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  16471. EXPECT_LT(ms_16mb, ms_4mb * 10)
  16472. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  16473. << "ms, which suggests the body is being buffered and rescanned";
  16474. }
  16475. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  16476. // A boundary can only be followed by CRLF or by "--", so anything else is
  16477. // malformed no matter what comes next. The parser must say so right away
  16478. // instead of buffering the rest of the declared body.
  16479. Server svr;
  16480. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  16481. res.set_content("ok", "text/plain");
  16482. });
  16483. auto port = svr.bind_to_any_port(HOST);
  16484. thread t = thread([&] { svr.listen_after_bind(); });
  16485. auto se = detail::scope_exit([&] {
  16486. svr.stop();
  16487. t.join();
  16488. ASSERT_FALSE(svr.is_running());
  16489. });
  16490. svr.wait_until_ready();
  16491. // Announce a 1 MB body but send only the malformed prefix. A parser that
  16492. // buffers instead of failing would still be waiting for the remaining bytes.
  16493. const std::string body = "--zzzz\r\n"
  16494. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16495. "\r\n"
  16496. "text1"
  16497. "\r\n--zzzzXX";
  16498. const std::string req = "POST /post HTTP/1.1\r\n"
  16499. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16500. "Content-Length: 1048576\r\n"
  16501. "\r\n" +
  16502. body;
  16503. std::string response;
  16504. ASSERT_TRUE(send_request(3, req, &response, port));
  16505. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  16506. EXPECT_EQ("400", response.substr(9, 3));
  16507. }
  16508. // Posts a multipart body split into two writes, so that the server sees the
  16509. // split at whatever offset the caller chose, and expects the single "text1"
  16510. // field to come through.
  16511. static void expect_split_multipart_ok(const std::string &body1,
  16512. const std::string &body2) {
  16513. auto handled = false;
  16514. Server svr;
  16515. svr.Post("/post", [&](const Request &req, Response &) {
  16516. EXPECT_EQ(1u, req.form.fields.size());
  16517. EXPECT_EQ("text1", req.form.get_field("text1"));
  16518. handled = true;
  16519. });
  16520. auto port = svr.bind_to_any_port(HOST);
  16521. thread t = thread([&] { svr.listen_after_bind(); });
  16522. auto se = detail::scope_exit([&] {
  16523. svr.stop();
  16524. t.join();
  16525. ASSERT_FALSE(svr.is_running());
  16526. ASSERT_TRUE(handled);
  16527. });
  16528. svr.wait_until_ready();
  16529. // "Connection: close" makes the server close once it has answered, so the
  16530. // response drain ends immediately instead of idling until the read timeout.
  16531. const std::string head =
  16532. "POST /post HTTP/1.1\r\n"
  16533. "Host: localhost\r\n"
  16534. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  16535. "Connection: close\r\n"
  16536. "Content-Length: " +
  16537. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  16538. std::string response;
  16539. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  16540. ASSERT_GE(response.size(), 12u) << "no response";
  16541. EXPECT_EQ("200", response.substr(9, 3));
  16542. }
  16543. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  16544. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  16545. // ignored, including when it does not arrive in the same read as the
  16546. // close-delimiter itself.
  16547. expect_split_multipart_ok("--zzzz\r\n"
  16548. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16549. "\r\n"
  16550. "text1"
  16551. "\r\n--zzzz--",
  16552. "\r\nthis epilogue must be ignored\r\n");
  16553. }
  16554. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  16555. // The initial boundary may be preceded by a preamble of any length and may
  16556. // straddle a read boundary. Discarding data while waiting for it must not
  16557. // throw away a partial boundary sitting at the end of the buffer.
  16558. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  16559. "zz\r\n"
  16560. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16561. "\r\n"
  16562. "text1"
  16563. "\r\n--zzzz--\r\n");
  16564. }
  16565. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  16566. // The received boundary was only checked for being non-empty, so it could be
  16567. // as long as a header is allowed to be. The parser scans the body for
  16568. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  16569. // costs a nearly full comparison at nearly every position, making the
  16570. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  16571. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  16572. Server svr;
  16573. svr.Post("/post", [](const Request &req, Response &res) {
  16574. EXPECT_EQ(1u, req.form.fields.size());
  16575. EXPECT_EQ("text1", req.form.get_field("text1"));
  16576. res.set_content("ok", "text/plain");
  16577. });
  16578. auto port = svr.bind_to_any_port(HOST);
  16579. thread t = thread([&] { svr.listen_after_bind(); });
  16580. auto se = detail::scope_exit([&] {
  16581. svr.stop();
  16582. t.join();
  16583. ASSERT_FALSE(svr.is_running());
  16584. });
  16585. svr.wait_until_ready();
  16586. Client cli(HOST, port);
  16587. auto post_with_boundary_of_length = [&](size_t len) {
  16588. const std::string boundary(len, 'a');
  16589. const std::string body =
  16590. "--" + boundary +
  16591. "\r\n"
  16592. "Content-Disposition: form-data; name=\"text1\"\r\n"
  16593. "\r\n"
  16594. "text1"
  16595. "\r\n--" +
  16596. boundary + "--\r\n";
  16597. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  16598. };
  16599. auto res = post_with_boundary_of_length(70);
  16600. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16601. EXPECT_EQ(StatusCode::OK_200, res->status);
  16602. res = post_with_boundary_of_length(71);
  16603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16604. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  16605. }
  16606. TEST(MakeFileBodyTest, Basic) {
  16607. const std::string file_content(4096, 'Z');
  16608. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  16609. {
  16610. std::ofstream ofs(tmp_path, std::ios::binary);
  16611. ofs.write(file_content.data(),
  16612. static_cast<std::streamsize>(file_content.size()));
  16613. }
  16614. auto handled = false;
  16615. Server svr;
  16616. svr.Post("/upload", [&](const Request &req, Response &res) {
  16617. EXPECT_EQ(file_content, req.body);
  16618. handled = true;
  16619. res.status = StatusCode::OK_200;
  16620. });
  16621. auto port = svr.bind_to_any_port(HOST);
  16622. auto t = thread([&] { svr.listen_after_bind(); });
  16623. auto se = detail::scope_exit([&] {
  16624. svr.stop();
  16625. t.join();
  16626. ASSERT_FALSE(svr.is_running());
  16627. ASSERT_TRUE(handled);
  16628. std::remove(tmp_path.c_str());
  16629. });
  16630. svr.wait_until_ready();
  16631. auto fb = make_file_body(tmp_path);
  16632. ASSERT_GT(fb.first, 0u);
  16633. Client cli(HOST, port);
  16634. auto res =
  16635. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  16636. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16637. EXPECT_EQ(StatusCode::OK_200, res->status);
  16638. }
  16639. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  16640. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  16641. {
  16642. std::ofstream ofs(path, std::ios::binary);
  16643. const std::string content(100, 'A');
  16644. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16645. }
  16646. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16647. auto body = make_file_body(path);
  16648. ASSERT_EQ(100u, body.first);
  16649. ASSERT_TRUE(static_cast<bool>(body.second));
  16650. // Rewritten shorter after its length was measured - and, on a server, after
  16651. // that length has already gone out as Content-Length.
  16652. {
  16653. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  16654. const std::string content(10, 'A');
  16655. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16656. }
  16657. std::string written;
  16658. DataSink sink;
  16659. sink.write = [&](const char *d, size_t l) {
  16660. written.append(d, l);
  16661. return true;
  16662. };
  16663. // The provider has to report failure. write_content_with_progress() advances
  16664. // its offset only by what was written, so a provider that returns true
  16665. // without completing the length it promised is called again straight away,
  16666. // and again.
  16667. EXPECT_FALSE(body.second(0, body.first, sink));
  16668. EXPECT_EQ(std::string(10, 'A'), written);
  16669. }
  16670. TEST(MakeFileBodyTest, WholeFileIsSent) {
  16671. const std::string path = "./httplib_test_make_file_body_whole.bin";
  16672. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  16673. {
  16674. std::ofstream ofs(path, std::ios::binary);
  16675. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  16676. }
  16677. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  16678. auto body = make_file_body(path);
  16679. ASSERT_EQ(content.size(), body.first);
  16680. ASSERT_TRUE(static_cast<bool>(body.second));
  16681. std::string written;
  16682. DataSink sink;
  16683. sink.write = [&](const char *d, size_t l) {
  16684. written.append(d, l);
  16685. return true;
  16686. };
  16687. EXPECT_TRUE(body.second(0, body.first, sink));
  16688. EXPECT_EQ(content, written);
  16689. }
  16690. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  16691. static constexpr unsigned int number_of_tasks{1000000};
  16692. std::atomic_uint count{0};
  16693. std::unique_ptr<TaskQueue> task_queue{
  16694. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  16695. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16696. auto queued = task_queue->enqueue(
  16697. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  16698. EXPECT_TRUE(queued);
  16699. }
  16700. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16701. task_queue->shutdown();
  16702. #else
  16703. EXPECT_NO_THROW(task_queue->shutdown());
  16704. #endif
  16705. EXPECT_EQ(number_of_tasks, count.load());
  16706. }
  16707. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  16708. static constexpr unsigned int number_of_tasks{1000000};
  16709. static constexpr unsigned int qlimit{2};
  16710. unsigned int queued_count{0};
  16711. std::atomic_uint count{0};
  16712. std::unique_ptr<TaskQueue> task_queue{
  16713. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  16714. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  16715. if (task_queue->enqueue(
  16716. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  16717. queued_count++;
  16718. }
  16719. }
  16720. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16721. task_queue->shutdown();
  16722. #else
  16723. EXPECT_NO_THROW(task_queue->shutdown());
  16724. #endif
  16725. EXPECT_EQ(queued_count, count.load());
  16726. EXPECT_TRUE(queued_count <= number_of_tasks);
  16727. EXPECT_TRUE(queued_count >= qlimit);
  16728. }
  16729. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  16730. // Use a short idle timeout so a dynamic thread spawns, times out and
  16731. // exits during the test, and the pool keeps working afterwards.
  16732. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  16733. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  16734. /*idle_timeout_sec=*/1}};
  16735. std::atomic_uint count{0};
  16736. std::condition_variable cv;
  16737. std::mutex mtx;
  16738. bool release = false;
  16739. // Block the base thread so the second task spawns a dynamic thread.
  16740. EXPECT_TRUE(task_queue->enqueue([&] {
  16741. std::unique_lock<std::mutex> lock(mtx);
  16742. while (!release) {
  16743. cv.wait(lock);
  16744. }
  16745. count++;
  16746. }));
  16747. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16748. // Let the dynamic thread finish its task and exceed the idle timeout.
  16749. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  16750. {
  16751. std::unique_lock<std::mutex> lock(mtx);
  16752. release = true;
  16753. }
  16754. cv.notify_all();
  16755. // The pool must still accept and run tasks after the dynamic thread exited.
  16756. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  16757. task_queue->shutdown();
  16758. EXPECT_EQ(3u, count.load());
  16759. }
  16760. TEST(TaskQueueTest, BurstOfTasksGetsDynamicThreads) {
  16761. static constexpr size_t number_of_tasks{32};
  16762. std::unique_ptr<TaskQueue> task_queue{
  16763. new ThreadPool{/*num_threads=*/16, /*max_threads=*/64}};
  16764. // Let the base threads go idle so the burst below finds them waiting.
  16765. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16766. std::mutex mtx;
  16767. std::condition_variable cv;
  16768. size_t running = 0;
  16769. bool release = false;
  16770. for (size_t i = 0; i < number_of_tasks; i++) {
  16771. EXPECT_TRUE(task_queue->enqueue([&] {
  16772. std::unique_lock<std::mutex> lock(mtx);
  16773. running++;
  16774. cv.notify_all();
  16775. cv.wait(lock, [&] { return release; });
  16776. }));
  16777. }
  16778. {
  16779. std::unique_lock<std::mutex> lock(mtx);
  16780. EXPECT_TRUE(cv.wait_for(lock, std::chrono::seconds(5),
  16781. [&] { return running == number_of_tasks; }));
  16782. release = true;
  16783. }
  16784. cv.notify_all();
  16785. task_queue->shutdown();
  16786. }
  16787. TEST(TaskQueueTest, MaxQueuedRequests) {
  16788. static constexpr unsigned int qlimit{3};
  16789. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  16790. std::condition_variable sem_cv;
  16791. std::mutex sem_mtx;
  16792. int credits = 0;
  16793. bool queued;
  16794. /* Fill up the queue with tasks that will block until we give them credits to
  16795. * complete. */
  16796. for (unsigned int n = 0; n <= qlimit;) {
  16797. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  16798. std::unique_lock<std::mutex> lock(sem_mtx);
  16799. while (credits <= 0) {
  16800. sem_cv.wait(lock);
  16801. }
  16802. /* Consume the credit and signal the test code if they are all gone. */
  16803. if (--credits == 0) { sem_cv.notify_one(); }
  16804. });
  16805. if (n < qlimit) {
  16806. /* The first qlimit enqueues must succeed. */
  16807. EXPECT_TRUE(queued);
  16808. } else {
  16809. /* The last one will succeed only when the worker thread
  16810. * starts and dequeues the first blocking task. Although
  16811. * not necessary for the correctness of this test, we sleep for
  16812. * a short while to avoid busy waiting. */
  16813. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  16814. }
  16815. if (queued) { n++; }
  16816. }
  16817. /* Further enqueues must fail since the queue is full. */
  16818. for (auto i = 0; i < 4; i++) {
  16819. queued = task_queue->enqueue([] {});
  16820. EXPECT_FALSE(queued);
  16821. }
  16822. /* Give the credits to allow the previous tasks to complete. */
  16823. {
  16824. std::unique_lock<std::mutex> lock(sem_mtx);
  16825. credits += qlimit + 1;
  16826. }
  16827. sem_cv.notify_all();
  16828. /* Wait for all the credits to be consumed. */
  16829. {
  16830. std::unique_lock<std::mutex> lock(sem_mtx);
  16831. while (credits > 0) {
  16832. sem_cv.wait(lock);
  16833. }
  16834. }
  16835. /* Check that we are able again to enqueue at least qlimit tasks. */
  16836. for (unsigned int i = 0; i < qlimit; i++) {
  16837. queued = task_queue->enqueue([] {});
  16838. EXPECT_TRUE(queued);
  16839. }
  16840. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  16841. task_queue->shutdown();
  16842. #else
  16843. EXPECT_NO_THROW(task_queue->shutdown());
  16844. #endif
  16845. }
  16846. TEST(RedirectTest, SeeOtherDoesNotResendContentProviderBody) {
  16847. Server svr;
  16848. std::string method;
  16849. std::string body;
  16850. auto has_content_length = false;
  16851. auto has_transfer_encoding = false;
  16852. std::atomic<int> bad_requests{0};
  16853. // Leftover body bytes get parsed as a malformed request and answered with
  16854. // 400
  16855. svr.set_logger([&](const Request & /*req*/, const Response &res) {
  16856. if (res.status == StatusCode::BadRequest_400) { bad_requests++; }
  16857. });
  16858. svr.Post("/up", [](const Request & /*req*/, Response &res) {
  16859. res.set_redirect("/down", StatusCode::SeeOther_303);
  16860. });
  16861. svr.Get("/down", [&](const Request &req, Response &res) {
  16862. method = req.method;
  16863. body = req.body;
  16864. has_content_length = req.has_header("Content-Length");
  16865. has_transfer_encoding = req.has_header("Transfer-Encoding");
  16866. res.set_content("ok", "text/plain");
  16867. });
  16868. auto port = svr.bind_to_any_port(HOST);
  16869. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16870. auto se = detail::scope_exit([&] {
  16871. svr.stop();
  16872. thread.join();
  16873. ASSERT_FALSE(svr.is_running());
  16874. });
  16875. svr.wait_until_ready();
  16876. const std::string payload = "SECRET-BODY";
  16877. auto check = [&](Client &cli, const Result &res) {
  16878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16879. EXPECT_EQ(StatusCode::OK_200, res->status);
  16880. EXPECT_EQ("ok", res->body);
  16881. EXPECT_EQ("GET", method);
  16882. EXPECT_TRUE(body.empty());
  16883. EXPECT_FALSE(has_content_length);
  16884. EXPECT_FALSE(has_transfer_encoding);
  16885. // Nothing of the original body may be left on the connection
  16886. auto res2 = cli.Get("/down");
  16887. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  16888. EXPECT_EQ(StatusCode::OK_200, res2->status);
  16889. EXPECT_EQ("ok", res2->body);
  16890. EXPECT_EQ(0, bad_requests);
  16891. };
  16892. // With content length
  16893. {
  16894. Client cli(HOST, port);
  16895. cli.set_keep_alive(true);
  16896. cli.set_follow_location(true);
  16897. auto res = cli.Post(
  16898. "/up", payload.size(),
  16899. [&](size_t offset, size_t length, DataSink &sink) {
  16900. return sink.write(payload.data() + offset, length);
  16901. },
  16902. "text/plain");
  16903. check(cli, res);
  16904. }
  16905. // Without content length (chunked)
  16906. {
  16907. Client cli(HOST, port);
  16908. cli.set_keep_alive(true);
  16909. cli.set_follow_location(true);
  16910. auto res = cli.Post(
  16911. "/up",
  16912. [&](size_t /*offset*/, DataSink &sink) {
  16913. sink.write(payload.data(), payload.size());
  16914. sink.done();
  16915. return true;
  16916. },
  16917. "text/plain");
  16918. check(cli, res);
  16919. }
  16920. }
  16921. TEST(RedirectTest, LocationPathIsNotDecoded) {
  16922. Server svr;
  16923. std::string target;
  16924. svr.Get(R"(/start/.*)", [](const Request &req, Response &res) {
  16925. // Echo the still-encoded name back in the Location
  16926. const std::string prefix = "/start/";
  16927. res.status = StatusCode::Found_302;
  16928. res.set_header("Location", "/dest/" + req.target.substr(prefix.size()));
  16929. });
  16930. svr.Get(R"(/dest.*)", [&](const Request &req, Response &res) {
  16931. target = req.target;
  16932. res.set_content("ok", "text/plain");
  16933. });
  16934. auto port = svr.bind_to_any_port(HOST);
  16935. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16936. auto se = detail::scope_exit([&] {
  16937. svr.stop();
  16938. thread.join();
  16939. ASSERT_FALSE(svr.is_running());
  16940. });
  16941. svr.wait_until_ready();
  16942. // Decoding the Location path would turn the first four into a path
  16943. // separator, a query delimiter, a fragment delimiter and a different
  16944. // percent-encoded octet. The rest must keep reaching the server as they are.
  16945. const std::vector<std::string> names = {
  16946. "a%2Fb", "x%3Fy", "x%23y", "a%2520b", "a%20b", "%C3%BC", "a-b_c.d~e",
  16947. };
  16948. for (auto path_encode : {true, false}) {
  16949. Client cli(HOST, port);
  16950. cli.set_follow_location(true);
  16951. cli.set_path_encode(path_encode);
  16952. for (const auto &name : names) {
  16953. target.clear();
  16954. auto res = cli.Get("/start/" + name);
  16955. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16956. EXPECT_EQ(StatusCode::OK_200, res->status);
  16957. EXPECT_EQ("/dest/" + name, target);
  16958. }
  16959. }
  16960. }
  16961. TEST(RedirectTest, NotModifiedIsReturned) {
  16962. Server svr;
  16963. svr.Get("/cached", [](const Request &, Response &res) {
  16964. res.status = StatusCode::NotModified_304;
  16965. });
  16966. auto port = svr.bind_to_any_port(HOST);
  16967. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16968. auto se = detail::scope_exit([&] {
  16969. svr.stop();
  16970. thread.join();
  16971. ASSERT_FALSE(svr.is_running());
  16972. });
  16973. svr.wait_until_ready();
  16974. Client cli(HOST, port);
  16975. cli.set_follow_location(true);
  16976. auto res = cli.Get("/cached", Headers{{"If-None-Match", "\"v1\""}});
  16977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16978. EXPECT_EQ(StatusCode::NotModified_304, res->status);
  16979. }
  16980. TEST(RedirectTest, NoLocationIsReturned) {
  16981. Server svr;
  16982. svr.Get("/no-location", [](const Request &, Response &res) {
  16983. res.status = StatusCode::Found_302;
  16984. res.set_content("no location", "text/plain");
  16985. });
  16986. auto port = svr.bind_to_any_port(HOST);
  16987. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  16988. auto se = detail::scope_exit([&] {
  16989. svr.stop();
  16990. thread.join();
  16991. ASSERT_FALSE(svr.is_running());
  16992. });
  16993. svr.wait_until_ready();
  16994. Client cli(HOST, port);
  16995. cli.set_follow_location(true);
  16996. auto res = cli.Get("/no-location");
  16997. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16998. EXPECT_EQ(StatusCode::Found_302, res->status);
  16999. EXPECT_EQ("no location", res->body);
  17000. // The callbacks see the body of the response that is returned
  17001. auto handler_called = false;
  17002. auto progress_called = false;
  17003. std::string body;
  17004. auto res2 = cli.Get(
  17005. "/no-location",
  17006. [&](const Response &) {
  17007. handler_called = true;
  17008. return true;
  17009. },
  17010. [&](const char *data, size_t data_length) {
  17011. body.append(data, data_length);
  17012. return true;
  17013. },
  17014. [&](size_t, size_t) {
  17015. progress_called = true;
  17016. return true;
  17017. });
  17018. ASSERT_TRUE(res2) << "Error: " << to_string(res2.error());
  17019. EXPECT_EQ(StatusCode::Found_302, res2->status);
  17020. EXPECT_TRUE(handler_called);
  17021. EXPECT_TRUE(progress_called);
  17022. EXPECT_EQ("no location", body);
  17023. }
  17024. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  17025. Server svr;
  17026. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17027. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  17028. });
  17029. svr.Get("/hello", [](const Request &req, Response &res) {
  17030. res.set_content(req.get_param_value("key"), "text/plain");
  17031. });
  17032. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17033. auto se = detail::scope_exit([&] {
  17034. svr.stop();
  17035. thread.join();
  17036. ASSERT_FALSE(svr.is_running());
  17037. });
  17038. svr.wait_until_ready();
  17039. {
  17040. Client cli(HOST, PORT);
  17041. cli.set_follow_location(true);
  17042. auto res = cli.Get("/");
  17043. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17044. EXPECT_EQ(StatusCode::OK_200, res->status);
  17045. EXPECT_EQ("val&key2=val2", res->body);
  17046. }
  17047. }
  17048. #endif
  17049. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  17050. Server svr;
  17051. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17052. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  17053. });
  17054. svr.Get("/hello", [](const Request &req, Response &res) {
  17055. res.set_content(req.get_param_value("key"), "text/plain");
  17056. });
  17057. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17058. auto se = detail::scope_exit([&] {
  17059. svr.stop();
  17060. thread.join();
  17061. ASSERT_FALSE(svr.is_running());
  17062. });
  17063. svr.wait_until_ready();
  17064. {
  17065. Client cli(HOST, PORT);
  17066. cli.set_follow_location(true);
  17067. auto res = cli.Get("/");
  17068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17069. EXPECT_EQ(StatusCode::OK_200, res->status);
  17070. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  17071. }
  17072. }
  17073. TEST(RedirectTest, RedirectWithPlusInPath) {
  17074. Server svr;
  17075. svr.Get("/", [](const Request & /*req*/, Response &res) {
  17076. res.set_redirect("/a+b");
  17077. });
  17078. // Route pattern uses regex; escape + as \\+
  17079. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  17080. res.set_content(req.path, "text/plain");
  17081. });
  17082. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17083. auto se = detail::scope_exit([&] {
  17084. svr.stop();
  17085. thread.join();
  17086. ASSERT_FALSE(svr.is_running());
  17087. });
  17088. svr.wait_until_ready();
  17089. {
  17090. Client cli(HOST, PORT);
  17091. cli.set_follow_location(true);
  17092. auto res = cli.Get("/");
  17093. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17094. EXPECT_EQ(StatusCode::OK_200, res->status);
  17095. EXPECT_EQ("/a+b", res->body);
  17096. }
  17097. }
  17098. TEST(RedirectTest, ResolveRelativeLocation) {
  17099. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  17100. const std::vector<std::pair<std::string, std::string>> cases = {
  17101. {"g", "/b/c/g"},
  17102. {"./g", "/b/c/g"},
  17103. {"g/", "/b/c/g/"},
  17104. {"?y", "/b/c/d;p?y"},
  17105. {"g?y", "/b/c/g?y"},
  17106. {"#s", "/b/c/d;p?q#s"},
  17107. {"g#s", "/b/c/g#s"},
  17108. {"g?y#s", "/b/c/g?y#s"},
  17109. {";x", "/b/c/;x"},
  17110. {"g;x", "/b/c/g;x"},
  17111. {".", "/b/c/"},
  17112. {"./", "/b/c/"},
  17113. {"..", "/b/"},
  17114. {"../", "/b/"},
  17115. {"../g", "/b/g"},
  17116. {"../..", "/"},
  17117. {"../../", "/"},
  17118. {"../../g", "/g"},
  17119. {"../../../g", "/g"},
  17120. {"g.", "/b/c/g."},
  17121. {".g", "/b/c/.g"},
  17122. {"g..", "/b/c/g.."},
  17123. {"..g", "/b/c/..g"},
  17124. {"./../g", "/b/g"},
  17125. {"./g/.", "/b/c/g/"},
  17126. {"g/./h", "/b/c/g/h"},
  17127. {"g/../h", "/b/c/h"},
  17128. {"g;x=1/./y", "/b/c/g;x=1/y"},
  17129. {"g;x=1/../y", "/b/c/y"},
  17130. {"g?y/./x", "/b/c/g?y/./x"},
  17131. {"g#s/../x", "/b/c/g#s/../x"},
  17132. // Not relative-path references, so left for parse_url.
  17133. {"/g", "/g"},
  17134. {"//g", "//g"},
  17135. {"http://g/x", "http://g/x"},
  17136. {"g:h", "g:h"},
  17137. };
  17138. for (const auto &c : cases) {
  17139. EXPECT_EQ(c.second,
  17140. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  17141. << c.first;
  17142. }
  17143. }
  17144. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  17145. Server svr;
  17146. svr.Get("/dir/page", [](const Request &req, Response &res) {
  17147. res.set_redirect(req.get_param_value("to"));
  17148. });
  17149. svr.Get("/dir/next", [](const Request &req, Response &res) {
  17150. res.set_content(req.target, "text/plain");
  17151. });
  17152. svr.Get("/other", [](const Request &req, Response &res) {
  17153. res.set_content(req.target, "text/plain");
  17154. });
  17155. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17156. auto se = detail::scope_exit([&] {
  17157. svr.stop();
  17158. thread.join();
  17159. ASSERT_FALSE(svr.is_running());
  17160. });
  17161. svr.wait_until_ready();
  17162. const std::vector<std::pair<std::string, std::string>> cases = {
  17163. {"next", "/dir/next"},
  17164. {"./next?x=1", "/dir/next?x=1"},
  17165. {"../other", "/other"},
  17166. };
  17167. for (const auto &c : cases) {
  17168. Client cli(HOST, PORT);
  17169. cli.set_follow_location(true);
  17170. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  17171. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  17172. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  17173. EXPECT_EQ(c.second, res->body) << c.first;
  17174. }
  17175. }
  17176. #ifdef CPPHTTPLIB_SSL_ENABLED
  17177. TEST(RedirectTest, Issue2185_Online) {
  17178. SSLClient client("github.com");
  17179. client.set_follow_location(true);
  17180. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  17181. "Coollab-Windows.zip");
  17182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17183. EXPECT_EQ(StatusCode::OK_200, res->status);
  17184. EXPECT_EQ(9920427U, res->body.size());
  17185. }
  17186. #endif
  17187. TEST(VulnerabilityTest, CRLFInjection) {
  17188. Server svr;
  17189. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  17190. res.set_content("Hello 1", "text/plain");
  17191. });
  17192. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  17193. res.set_content("Hello 2", "text/plain");
  17194. });
  17195. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  17196. res.set_content("Hello 3", "text/plain");
  17197. });
  17198. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  17199. res.set_content("Hello 4", "text/plain");
  17200. });
  17201. svr.set_logger([](const Request &req, const Response & /*res*/) {
  17202. for (const auto &x : req.headers) {
  17203. auto key = x.first;
  17204. EXPECT_STRNE("evil", key.c_str());
  17205. }
  17206. });
  17207. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17208. auto se = detail::scope_exit([&] {
  17209. svr.stop();
  17210. thread.join();
  17211. ASSERT_FALSE(svr.is_running());
  17212. });
  17213. svr.wait_until_ready();
  17214. {
  17215. Client cli(HOST, PORT);
  17216. cli.Post("/test1", "A=B",
  17217. "application/x-www-form-urlencoded\r\nevil: hello1");
  17218. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  17219. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  17220. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  17221. }
  17222. }
  17223. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  17224. auto server_thread = std::thread([] {
  17225. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17226. default_socket_options(srv);
  17227. sockaddr_in addr{};
  17228. addr.sin_family = AF_INET;
  17229. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17230. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17231. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  17232. ::listen(srv, 1);
  17233. sockaddr_in cli_addr{};
  17234. socklen_t cli_len = sizeof(cli_addr);
  17235. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17236. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  17237. std::string buf_all;
  17238. char buf[2048];
  17239. ssize_t n;
  17240. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  17241. buf_all.append(buf, static_cast<size_t>(n));
  17242. size_t pos;
  17243. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  17244. auto request_block = buf_all.substr(0, pos + 4); // include separator
  17245. auto e = request_block.find("\r\n");
  17246. if (e != std::string::npos) {
  17247. auto request_line = request_block.substr(0, e);
  17248. std::string msg =
  17249. "CRLF injection detected in request line: '" + request_line + "'";
  17250. EXPECT_FALSE(true) << msg;
  17251. }
  17252. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  17253. ::send(cli,
  17254. #ifdef _WIN32
  17255. static_cast<const char *>(resp.c_str()),
  17256. static_cast<int>(resp.size()),
  17257. #else
  17258. resp.c_str(), resp.size(),
  17259. #endif
  17260. 0);
  17261. buf_all.erase(0, pos + 4);
  17262. }
  17263. }
  17264. detail::close_socket(cli);
  17265. detail::close_socket(srv);
  17266. });
  17267. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  17268. auto cli = Client("127.0.0.1", PORT + 1);
  17269. auto headers = Headers{
  17270. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  17271. {"Connection", "keep-alive"}};
  17272. auto res = cli.Get("/hi", headers);
  17273. EXPECT_FALSE(res);
  17274. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17275. server_thread.join();
  17276. }
  17277. // A request rejected before any byte reaches the socket must fail right away
  17278. // instead of waiting for a response the server will never send.
  17279. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  17280. // The kernel completes the TCP handshake from the listen backlog, so the
  17281. // client connects, but nothing ever reads, responds or closes.
  17282. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17283. default_socket_options(srv);
  17284. sockaddr_in addr{};
  17285. addr.sin_family = AF_INET;
  17286. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17287. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17288. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17289. ASSERT_EQ(0, ::listen(srv, 8));
  17290. auto cli = Client("127.0.0.1", PORT + 1);
  17291. cli.set_read_timeout(10, 0);
  17292. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  17293. return std::chrono::duration_cast<std::chrono::milliseconds>(
  17294. std::chrono::steady_clock::now() - start)
  17295. .count();
  17296. };
  17297. {
  17298. Request req;
  17299. req.method = "GE T";
  17300. req.path = "/";
  17301. auto start = std::chrono::steady_clock::now();
  17302. auto res = cli.send(req);
  17303. EXPECT_FALSE(res);
  17304. EXPECT_EQ(Error::Write, res.error());
  17305. EXPECT_LT(elapsed_ms(start), 1000);
  17306. }
  17307. {
  17308. auto start = std::chrono::steady_clock::now();
  17309. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  17310. EXPECT_FALSE(res);
  17311. EXPECT_EQ(Error::InvalidHeaders, res.error());
  17312. EXPECT_LT(elapsed_ms(start), 1000);
  17313. }
  17314. EXPECT_FALSE(cli.is_socket_open());
  17315. detail::close_socket(srv);
  17316. }
  17317. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  17318. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17319. default_socket_options(srv);
  17320. sockaddr_in addr{};
  17321. addr.sin_family = AF_INET;
  17322. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  17323. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17324. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  17325. ASSERT_EQ(0, ::listen(srv, 1));
  17326. std::string received;
  17327. auto server_thread = std::thread([&] {
  17328. auto sock = ::accept(srv, nullptr, nullptr);
  17329. if (sock == INVALID_SOCKET) { return; }
  17330. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  17331. char buf[2048];
  17332. ssize_t n;
  17333. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  17334. received.append(buf, static_cast<size_t>(n));
  17335. }
  17336. detail::close_socket(sock);
  17337. });
  17338. {
  17339. auto cli = Client("127.0.0.1", PORT + 1);
  17340. // "Z" sorts after the default headers, so writing straight to the socket
  17341. // would have sent the request line and those headers before the rejection.
  17342. auto handle =
  17343. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  17344. EXPECT_FALSE(handle.is_valid());
  17345. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  17346. }
  17347. server_thread.join();
  17348. detail::close_socket(srv);
  17349. EXPECT_TRUE(received.empty()) << received;
  17350. }
  17351. TEST(PathParamsTest, StaticMatch) {
  17352. const auto pattern = "/users/all";
  17353. detail::PathParamsMatcher matcher(pattern);
  17354. Request request;
  17355. request.path = "/users/all";
  17356. ASSERT_TRUE(matcher.match(request));
  17357. std::unordered_map<std::string, std::string> expected_params = {};
  17358. EXPECT_EQ(request.path_params, expected_params);
  17359. }
  17360. TEST(PathParamsTest, StaticMismatch) {
  17361. const auto pattern = "/users/all";
  17362. detail::PathParamsMatcher matcher(pattern);
  17363. Request request;
  17364. request.path = "/users/1";
  17365. ASSERT_FALSE(matcher.match(request));
  17366. }
  17367. TEST(PathParamsTest, SingleParamInTheMiddle) {
  17368. const auto pattern = "/users/:id/subscriptions";
  17369. detail::PathParamsMatcher matcher(pattern);
  17370. Request request;
  17371. request.path = "/users/42/subscriptions";
  17372. ASSERT_TRUE(matcher.match(request));
  17373. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17374. EXPECT_EQ(request.path_params, expected_params);
  17375. }
  17376. TEST(PathParamsTest, SingleParamInTheEnd) {
  17377. const auto pattern = "/users/:id";
  17378. detail::PathParamsMatcher matcher(pattern);
  17379. Request request;
  17380. request.path = "/users/24";
  17381. ASSERT_TRUE(matcher.match(request));
  17382. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  17383. EXPECT_EQ(request.path_params, expected_params);
  17384. }
  17385. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  17386. const auto pattern = "/users/:id/";
  17387. detail::PathParamsMatcher matcher(pattern);
  17388. Request request;
  17389. request.path = "/users/42/";
  17390. ASSERT_TRUE(matcher.match(request));
  17391. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  17392. EXPECT_EQ(request.path_params, expected_params);
  17393. }
  17394. TEST(PathParamsTest, EmptyParam) {
  17395. const auto pattern = "/users/:id/";
  17396. detail::PathParamsMatcher matcher(pattern);
  17397. Request request;
  17398. request.path = "/users//";
  17399. ASSERT_TRUE(matcher.match(request));
  17400. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  17401. EXPECT_EQ(request.path_params, expected_params);
  17402. }
  17403. TEST(PathParamsTest, FragmentMismatch) {
  17404. const auto pattern = "/users/:id/";
  17405. detail::PathParamsMatcher matcher(pattern);
  17406. Request request;
  17407. request.path = "/admins/24/";
  17408. ASSERT_FALSE(matcher.match(request));
  17409. }
  17410. TEST(PathParamsTest, ExtraFragments) {
  17411. const auto pattern = "/users/:id";
  17412. detail::PathParamsMatcher matcher(pattern);
  17413. Request request;
  17414. request.path = "/users/42/subscriptions";
  17415. ASSERT_FALSE(matcher.match(request));
  17416. }
  17417. TEST(PathParamsTest, MissingTrailingParam) {
  17418. const auto pattern = "/users/:id";
  17419. detail::PathParamsMatcher matcher(pattern);
  17420. Request request;
  17421. request.path = "/users";
  17422. ASSERT_FALSE(matcher.match(request));
  17423. }
  17424. TEST(PathParamsTest, MissingParamInTheMiddle) {
  17425. const auto pattern = "/users/:id/subscriptions";
  17426. detail::PathParamsMatcher matcher(pattern);
  17427. Request request;
  17428. request.path = "/users/subscriptions";
  17429. ASSERT_FALSE(matcher.match(request));
  17430. }
  17431. TEST(PathParamsTest, MultipleParams) {
  17432. const auto pattern = "/users/:userid/subscriptions/:subid";
  17433. detail::PathParamsMatcher matcher(pattern);
  17434. Request request;
  17435. request.path = "/users/42/subscriptions/2";
  17436. ASSERT_TRUE(matcher.match(request));
  17437. std::unordered_map<std::string, std::string> expected_params = {
  17438. {"userid", "42"}, {"subid", "2"}};
  17439. EXPECT_EQ(request.path_params, expected_params);
  17440. }
  17441. TEST(PathParamsTest, SequenceOfParams) {
  17442. const auto pattern = "/values/:x/:y/:z";
  17443. detail::PathParamsMatcher matcher(pattern);
  17444. Request request;
  17445. request.path = "/values/1/2/3";
  17446. ASSERT_TRUE(matcher.match(request));
  17447. std::unordered_map<std::string, std::string> expected_params = {
  17448. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  17449. EXPECT_EQ(request.path_params, expected_params);
  17450. }
  17451. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  17452. const auto pattern = "/prefix:suffix";
  17453. detail::PathParamsMatcher matcher(pattern);
  17454. Request request;
  17455. request.path = "/prefix:suffix";
  17456. ASSERT_TRUE(matcher.match(request));
  17457. const std::unordered_map<std::string, std::string> expected_params = {};
  17458. EXPECT_EQ(request.path_params, expected_params);
  17459. }
  17460. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  17461. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  17462. // calling thread's stack on a long enough path for a quantified pattern;
  17463. // RegexMatcher must refuse to run regex matching on paths beyond
  17464. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  17465. detail::RegexMatcher matcher("/files/(.*)");
  17466. Request within_limit;
  17467. within_limit.path = "/files/" + std::string(10, 'A');
  17468. EXPECT_TRUE(matcher.match(within_limit));
  17469. Request over_limit;
  17470. over_limit.path =
  17471. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  17472. EXPECT_FALSE(matcher.match(over_limit));
  17473. }
  17474. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  17475. Server svr;
  17476. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  17477. res.set_content("ok", "text/plain");
  17478. });
  17479. auto port = svr.bind_to_any_port(HOST);
  17480. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  17481. auto se = detail::scope_exit([&] {
  17482. svr.stop();
  17483. thread.join();
  17484. ASSERT_FALSE(svr.is_running());
  17485. });
  17486. svr.wait_until_ready();
  17487. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  17488. // request URI limit; this used to be able to crash the process.
  17489. std::string path =
  17490. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  17491. std::string req = "GET " + path +
  17492. " HTTP/1.1\r\n"
  17493. "Host: " +
  17494. std::string(HOST) + ":" + std::to_string(port) +
  17495. "\r\n"
  17496. "Connection: close\r\n"
  17497. "\r\n";
  17498. std::string response;
  17499. ASSERT_TRUE(send_request(5, req, &response, port));
  17500. EXPECT_NE(std::string::npos, response.find("404"));
  17501. }
  17502. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  17503. Server svr;
  17504. auto handler = [](const Request & /*req*/, Response &res) {
  17505. res.set_content("hit", "text/plain");
  17506. };
  17507. // No regex metacharacter, so this one is compared literally
  17508. svr.Get("/literal/route", handler);
  17509. // '.' is a regex metacharacter, so this one must keep regex semantics
  17510. svr.Get("/a.c", handler);
  17511. auto port = svr.bind_to_any_port(HOST);
  17512. std::thread t([&]() { svr.listen_after_bind(); });
  17513. auto se = detail::scope_exit([&] {
  17514. svr.stop();
  17515. t.join();
  17516. ASSERT_FALSE(svr.is_running());
  17517. });
  17518. svr.wait_until_ready();
  17519. Client cli(HOST, port);
  17520. struct {
  17521. const char *path;
  17522. int status;
  17523. } cases[] = {
  17524. {"/literal/route", StatusCode::OK_200},
  17525. {"/literal/routes", StatusCode::NotFound_404},
  17526. {"/literal/rout", StatusCode::NotFound_404},
  17527. {"/abc", StatusCode::OK_200},
  17528. {"/a.c", StatusCode::OK_200},
  17529. };
  17530. for (const auto &x : cases) {
  17531. auto res = cli.Get(x.path);
  17532. ASSERT_TRUE(res) << x.path;
  17533. EXPECT_EQ(x.status, res->status) << x.path;
  17534. }
  17535. }
  17536. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  17537. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  17538. // from exhausting the stack, so it must only constrain routes that actually
  17539. // run a regular expression. A literal route is matched by comparison and
  17540. // stays usable at any length.
  17541. Server svr;
  17542. const std::string pattern =
  17543. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  17544. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  17545. res.set_content("hit", "text/plain");
  17546. });
  17547. auto port = svr.bind_to_any_port(HOST);
  17548. std::thread t([&]() { svr.listen_after_bind(); });
  17549. auto se = detail::scope_exit([&] {
  17550. svr.stop();
  17551. t.join();
  17552. ASSERT_FALSE(svr.is_running());
  17553. });
  17554. svr.wait_until_ready();
  17555. Client cli(HOST, port);
  17556. auto res = cli.Get(pattern);
  17557. ASSERT_TRUE(res);
  17558. EXPECT_EQ(StatusCode::OK_200, res->status);
  17559. }
  17560. TEST(ParseUrlTest, VariousPatterns) {
  17561. {
  17562. detail::UrlComponents uc;
  17563. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  17564. EXPECT_EQ("http", uc.scheme);
  17565. EXPECT_EQ("example.com", uc.host);
  17566. EXPECT_EQ("8080", uc.port);
  17567. EXPECT_EQ("/path", uc.path);
  17568. EXPECT_EQ("?q=1", uc.query);
  17569. }
  17570. {
  17571. detail::UrlComponents uc;
  17572. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  17573. EXPECT_EQ("https", uc.scheme);
  17574. EXPECT_EQ("example.com", uc.host);
  17575. EXPECT_TRUE(uc.port.empty());
  17576. EXPECT_EQ("/path", uc.path);
  17577. }
  17578. {
  17579. detail::UrlComponents uc;
  17580. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  17581. EXPECT_EQ("::1", uc.host);
  17582. EXPECT_EQ("8080", uc.port);
  17583. EXPECT_EQ("/path", uc.path);
  17584. }
  17585. {
  17586. detail::UrlComponents uc;
  17587. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  17588. }
  17589. {
  17590. // Bytes after the IPv6 literal must be a delimiter, not folded into
  17591. // the path while the connection still targets the bracketed host.
  17592. detail::UrlComponents uc;
  17593. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  17594. }
  17595. {
  17596. detail::UrlComponents uc;
  17597. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  17598. }
  17599. {
  17600. detail::UrlComponents uc;
  17601. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  17602. EXPECT_EQ("::1", uc.host);
  17603. EXPECT_TRUE(uc.port.empty());
  17604. EXPECT_EQ("/path", uc.path);
  17605. }
  17606. {
  17607. detail::UrlComponents uc;
  17608. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  17609. EXPECT_TRUE(uc.scheme.empty());
  17610. EXPECT_EQ("example.com", uc.host);
  17611. EXPECT_EQ("/path", uc.path);
  17612. EXPECT_EQ("?q=1", uc.query);
  17613. }
  17614. {
  17615. detail::UrlComponents uc;
  17616. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  17617. EXPECT_TRUE(uc.host.empty());
  17618. EXPECT_EQ("/path", uc.path);
  17619. EXPECT_EQ("?q=1", uc.query);
  17620. }
  17621. {
  17622. detail::UrlComponents uc;
  17623. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  17624. EXPECT_EQ("example.com", uc.host);
  17625. EXPECT_EQ("8080", uc.port);
  17626. }
  17627. {
  17628. // Unix socket path — must not be parsed as host
  17629. detail::UrlComponents uc;
  17630. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  17631. EXPECT_TRUE(uc.host.empty());
  17632. }
  17633. {
  17634. detail::UrlComponents uc;
  17635. ASSERT_TRUE(detail::parse_url("", uc));
  17636. EXPECT_TRUE(uc.host.empty());
  17637. EXPECT_TRUE(uc.path.empty());
  17638. }
  17639. {
  17640. detail::UrlComponents uc;
  17641. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  17642. }
  17643. {
  17644. detail::UrlComponents uc;
  17645. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  17646. }
  17647. {
  17648. // Accepted by parse_url; callers restrict to http/https
  17649. detail::UrlComponents uc;
  17650. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  17651. EXPECT_EQ("ftp", uc.scheme);
  17652. }
  17653. {
  17654. detail::UrlComponents uc;
  17655. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  17656. }
  17657. {
  17658. detail::UrlComponents uc;
  17659. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  17660. }
  17661. }
  17662. TEST(ParseUrlTest, FragmentHandling) {
  17663. {
  17664. detail::UrlComponents uc;
  17665. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  17666. EXPECT_EQ("/path", uc.path);
  17667. EXPECT_TRUE(uc.query.empty());
  17668. }
  17669. {
  17670. detail::UrlComponents uc;
  17671. ASSERT_TRUE(detail::parse_url("#frag", uc));
  17672. EXPECT_TRUE(uc.path.empty());
  17673. EXPECT_TRUE(uc.query.empty());
  17674. }
  17675. }
  17676. TEST(ParseUrlTest, UserinfoHandling) {
  17677. // userinfo, and a backslash some parsers take for '/', are rejected: such
  17678. // parsers would see evil.com as the host.
  17679. const char *urls[] = {"http://user@evil.com/", "http://user:pass@evil.com/",
  17680. "http://evil.com\\@good.com/", "//user@evil.com/x"};
  17681. for (auto url : urls) {
  17682. detail::UrlComponents uc;
  17683. EXPECT_FALSE(detail::parse_url(url, uc)) << url;
  17684. }
  17685. }
  17686. TEST(ParseUrlTest, IPv6EdgeCases) {
  17687. {
  17688. detail::UrlComponents uc;
  17689. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  17690. EXPECT_TRUE(uc.scheme.empty());
  17691. EXPECT_EQ("::1", uc.host);
  17692. EXPECT_EQ("8080", uc.port);
  17693. }
  17694. {
  17695. // Zone ID '%25' is not in [a-fA-F0-9:]
  17696. detail::UrlComponents uc;
  17697. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  17698. }
  17699. }
  17700. TEST(ParseUrlTest, SchemeEdgeCases) {
  17701. {
  17702. detail::UrlComponents uc;
  17703. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  17704. }
  17705. {
  17706. detail::UrlComponents uc;
  17707. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  17708. }
  17709. {
  17710. detail::UrlComponents uc;
  17711. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  17712. }
  17713. }
  17714. TEST(ParseUrlTest, PortEdgeCases) {
  17715. {
  17716. detail::UrlComponents uc;
  17717. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  17718. EXPECT_TRUE(uc.port.empty());
  17719. EXPECT_EQ("/path", uc.path);
  17720. }
  17721. {
  17722. // parse_url accepts any port string; validation is done by parse_port
  17723. detail::UrlComponents uc;
  17724. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  17725. EXPECT_EQ("abc", uc.port);
  17726. }
  17727. }
  17728. TEST(ParseUrlTest, WebSocketPatterns) {
  17729. {
  17730. detail::UrlComponents uc;
  17731. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  17732. EXPECT_EQ("ws", uc.scheme);
  17733. EXPECT_EQ("echo.example.com", uc.host);
  17734. EXPECT_EQ("8080", uc.port);
  17735. EXPECT_EQ("/ws", uc.path);
  17736. }
  17737. {
  17738. detail::UrlComponents uc;
  17739. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  17740. EXPECT_EQ("wss", uc.scheme);
  17741. EXPECT_EQ("echo.example.com", uc.host);
  17742. EXPECT_TRUE(uc.port.empty());
  17743. EXPECT_EQ("/ws", uc.path);
  17744. }
  17745. }
  17746. TEST(ParseUrlTest, QueryOnly) {
  17747. detail::UrlComponents uc;
  17748. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  17749. EXPECT_TRUE(uc.host.empty());
  17750. EXPECT_TRUE(uc.path.empty());
  17751. EXPECT_EQ("?q=1&r=2", uc.query);
  17752. }
  17753. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  17754. detail::UrlComponents uc;
  17755. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  17756. EXPECT_TRUE(uc.scheme.empty());
  17757. EXPECT_EQ("example.com", uc.host);
  17758. EXPECT_EQ("443", uc.port);
  17759. EXPECT_EQ("/path", uc.path);
  17760. }
  17761. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  17762. // If ipv6 regex working, regex match codepath is taken.
  17763. // else port will default to 80 in Client impl
  17764. int clientImplMagicPort = 80;
  17765. int port = 4321;
  17766. // above ports must be different to avoid false negative
  17767. EXPECT_NE(clientImplMagicPort, port);
  17768. std::string ipV6TestURL = "http://[ff06::c3]";
  17769. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  17770. CLIENT_PRIVATE_KEY_FILE);
  17771. EXPECT_EQ(cli.port(), port);
  17772. }
  17773. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  17774. auto file_path = "./www/dir/index.html";
  17775. auto dir_path = "./www/dir";
  17776. detail::FileStat stat_file(file_path);
  17777. EXPECT_TRUE(stat_file.is_file());
  17778. EXPECT_FALSE(stat_file.is_dir());
  17779. detail::FileStat stat_dir(dir_path);
  17780. EXPECT_FALSE(stat_dir.is_file());
  17781. EXPECT_TRUE(stat_dir.is_dir());
  17782. }
  17783. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  17784. // IPv4 with default HTTP port (80)
  17785. EXPECT_EQ("example.com",
  17786. detail::make_host_and_port_string("example.com", 80, false));
  17787. // IPv4 with default HTTPS port (443)
  17788. EXPECT_EQ("example.com",
  17789. detail::make_host_and_port_string("example.com", 443, true));
  17790. // IPv4 with non-default HTTP port
  17791. EXPECT_EQ("example.com:8080",
  17792. detail::make_host_and_port_string("example.com", 8080, false));
  17793. // IPv4 with non-default HTTPS port
  17794. EXPECT_EQ("example.com:8443",
  17795. detail::make_host_and_port_string("example.com", 8443, true));
  17796. // IPv6 with default HTTP port (80)
  17797. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  17798. // IPv6 with default HTTPS port (443)
  17799. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  17800. // IPv6 with non-default HTTP port
  17801. EXPECT_EQ("[::1]:8080",
  17802. detail::make_host_and_port_string("::1", 8080, false));
  17803. // IPv6 with non-default HTTPS port
  17804. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  17805. // IPv6 full address with default port
  17806. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  17807. detail::make_host_and_port_string(
  17808. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  17809. // IPv6 full address with non-default port
  17810. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  17811. detail::make_host_and_port_string(
  17812. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  17813. // IPv6 localhost with non-default port
  17814. EXPECT_EQ("[::1]:3000",
  17815. detail::make_host_and_port_string("::1", 3000, false));
  17816. // IPv6 with zone ID (link-local address) with default port
  17817. EXPECT_EQ("[fe80::1%eth0]",
  17818. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  17819. // IPv6 with zone ID (link-local address) with non-default port
  17820. EXPECT_EQ("[fe80::1%eth0]:8080",
  17821. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  17822. // Edge case: Port 443 with is_ssl=false (should add port)
  17823. EXPECT_EQ("example.com:443",
  17824. detail::make_host_and_port_string("example.com", 443, false));
  17825. // Edge case: Port 80 with is_ssl=true (should add port)
  17826. EXPECT_EQ("example.com:80",
  17827. detail::make_host_and_port_string("example.com", 80, true));
  17828. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  17829. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  17830. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  17831. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  17832. // Security fix: Already bracketed IPv6 should not get double brackets
  17833. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  17834. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  17835. EXPECT_EQ("[::1]:8080",
  17836. detail::make_host_and_port_string("[::1]", 8080, false));
  17837. EXPECT_EQ("[2001:db8::1]:8080",
  17838. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  17839. EXPECT_EQ("[fe80::1%eth0]",
  17840. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  17841. EXPECT_EQ("[fe80::1%eth0]:8080",
  17842. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  17843. // Edge case: Empty host (should return as-is)
  17844. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  17845. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  17846. // This is a known limitation but shouldn't crash
  17847. EXPECT_EQ("[host:name]",
  17848. detail::make_host_and_port_string("host:name", 80, false));
  17849. // Port number edge cases (no validation, but should not crash)
  17850. EXPECT_EQ("example.com:0",
  17851. detail::make_host_and_port_string("example.com", 0, false));
  17852. EXPECT_EQ("example.com:-1",
  17853. detail::make_host_and_port_string("example.com", -1, false));
  17854. EXPECT_EQ("example.com:65535",
  17855. detail::make_host_and_port_string("example.com", 65535, false));
  17856. EXPECT_EQ("example.com:65536",
  17857. detail::make_host_and_port_string("example.com", 65536, false));
  17858. }
  17859. #ifdef CPPHTTPLIB_SSL_ENABLED
  17860. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  17861. httplib::SSLClient cli("roblox.com", 443);
  17862. cli.set_follow_location(true);
  17863. auto res = cli.Get("/");
  17864. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17865. EXPECT_EQ(StatusCode::OK_200, res->status);
  17866. }
  17867. #endif
  17868. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  17869. Server svr;
  17870. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  17871. EXPECT_EQ(res.status, 400);
  17872. });
  17873. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17874. auto se = detail::scope_exit([&] {
  17875. svr.stop();
  17876. thread.join();
  17877. ASSERT_FALSE(svr.is_running());
  17878. });
  17879. svr.wait_until_ready();
  17880. Client cli(HOST, PORT);
  17881. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  17882. }
  17883. TEST(InvalidHeaderCharsTest, is_field_name) {
  17884. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  17885. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  17886. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  17887. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  17888. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  17889. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  17890. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  17891. EXPECT_FALSE(detail::fields::is_field_name(""));
  17892. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  17893. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  17894. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  17895. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  17896. }
  17897. TEST(InvalidHeaderCharsTest, is_field_value) {
  17898. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  17899. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  17900. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  17901. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  17902. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  17903. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  17904. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  17905. EXPECT_TRUE(detail::fields::is_field_value(""));
  17906. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  17907. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  17908. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  17909. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  17910. EXPECT_TRUE(detail::fields::is_field_value("0"));
  17911. }
  17912. TEST(InvalidHeaderCharsTest, OnServer) {
  17913. Server svr;
  17914. svr.Get("/test_name", [&](const Request &req, Response &res) {
  17915. std::string header = "Not Set";
  17916. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17917. res.set_header(header, "value");
  17918. res.set_content("Page Content Page Content", "text/plain");
  17919. });
  17920. svr.Get("/test_value", [&](const Request &req, Response &res) {
  17921. std::string header = "Not Set";
  17922. if (req.has_param("header")) { header = req.get_param_value("header"); }
  17923. res.set_header("X-Test", header);
  17924. res.set_content("Page Content Page Content", "text/plain");
  17925. });
  17926. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  17927. auto se = detail::scope_exit([&] {
  17928. svr.stop();
  17929. thread.join();
  17930. ASSERT_FALSE(svr.is_running());
  17931. });
  17932. svr.wait_until_ready();
  17933. Client cli(HOST, PORT);
  17934. {
  17935. auto res = cli.Get(
  17936. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17938. EXPECT_EQ("Page Content Page Content", res->body);
  17939. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17940. }
  17941. {
  17942. auto res = cli.Get(
  17943. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  17944. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17945. EXPECT_EQ("Page Content Page Content", res->body);
  17946. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  17947. }
  17948. }
  17949. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  17950. auto handled = false;
  17951. Server svr;
  17952. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  17953. thread t = thread([&] { svr.listen(HOST, PORT); });
  17954. auto se = detail::scope_exit([&] {
  17955. svr.stop();
  17956. t.join();
  17957. ASSERT_FALSE(svr.is_running());
  17958. ASSERT_FALSE(handled);
  17959. });
  17960. svr.wait_until_ready();
  17961. auto req = "POST /test HTTP/1.1\r\n"
  17962. "Content-Length: x\r\n"
  17963. "\r\n";
  17964. std::string response;
  17965. ASSERT_TRUE(send_request(1, req, &response));
  17966. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  17967. response.substr(0, response.find("\r\n")));
  17968. }
  17969. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  17970. // case-insensitive, and a server that receives a 100-continue expectation in
  17971. // an HTTP/1.0 request MUST ignore it.
  17972. static void probe_expect(int port, const std::string &req, bool *got_100) {
  17973. std::string response;
  17974. ASSERT_TRUE(send_request(1, req, &response, port));
  17975. *got_100 = response.find("100 Continue") != std::string::npos;
  17976. }
  17977. class ExpectTokenTest : public ::testing::Test {
  17978. protected:
  17979. void SetUp() override {
  17980. svr_.Post("/p", [](const Request &, Response &res) {
  17981. res.set_content("ok", "text/plain");
  17982. });
  17983. port_ = svr_.bind_to_any_port(HOST);
  17984. thread_ = thread([&]() { svr_.listen_after_bind(); });
  17985. svr_.wait_until_ready();
  17986. }
  17987. void TearDown() override {
  17988. svr_.stop();
  17989. if (thread_.joinable()) { thread_.join(); }
  17990. }
  17991. std::string request(const char *version, const char *expect_value) const {
  17992. return std::string("POST /p ") + version +
  17993. "\r\n"
  17994. "Host: localhost\r\n"
  17995. "Content-Length: 2\r\n"
  17996. "Connection: close\r\n"
  17997. "Expect: " +
  17998. expect_value +
  17999. "\r\n"
  18000. "\r\n"
  18001. "hi";
  18002. }
  18003. Server svr_;
  18004. int port_ = 0;
  18005. thread thread_;
  18006. };
  18007. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  18008. bool got_100 = false;
  18009. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  18010. EXPECT_TRUE(got_100);
  18011. }
  18012. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  18013. bool got_100 = true;
  18014. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  18015. EXPECT_FALSE(got_100);
  18016. }
  18017. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  18018. bool got_100 = false;
  18019. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  18020. EXPECT_TRUE(got_100);
  18021. }
  18022. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  18023. bool got_100 = false;
  18024. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  18025. EXPECT_TRUE(got_100);
  18026. }
  18027. // `100 Continue` is sent only when the server starts reading the body, so a
  18028. // request rejected before that never invites the client to send it. The
  18029. // requests below carry the expectation but withhold the body, as a client
  18030. // waiting for `100 Continue` would.
  18031. // A POST that expects `100 Continue` and withholds its two-byte body.
  18032. static std::string expect_headers_only(const std::string &path) {
  18033. return "POST " + path +
  18034. " HTTP/1.1\r\n"
  18035. "Host: localhost\r\n"
  18036. "Content-Length: 2\r\n"
  18037. "Expect: 100-continue\r\n"
  18038. "\r\n";
  18039. }
  18040. class ExpectLazyContinueTest : public ::testing::Test {
  18041. protected:
  18042. void SetUp() override {
  18043. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  18044. if (req.path == "/pre-routing") {
  18045. res.status = StatusCode::Unauthorized_401;
  18046. return Server::HandlerResponse::Handled;
  18047. }
  18048. return Server::HandlerResponse::Unhandled;
  18049. });
  18050. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  18051. if (req.matched_route == "/pre-request") {
  18052. res.status = StatusCode::Forbidden_403;
  18053. return Server::HandlerResponse::Handled;
  18054. }
  18055. return Server::HandlerResponse::Unhandled;
  18056. });
  18057. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  18058. res.set_content("ok", "text/plain");
  18059. });
  18060. svr_.Post("/pre-request", [](const Request &, Response &res) {
  18061. res.set_content("ok", "text/plain");
  18062. });
  18063. svr_.Post("/reader-used", [](const Request &, Response &res,
  18064. const ContentReader &content_reader) {
  18065. std::string body;
  18066. content_reader([&](const char *data, size_t len) {
  18067. body.append(data, len);
  18068. return true;
  18069. });
  18070. res.set_content(body, "text/plain");
  18071. });
  18072. svr_.Post("/reader-unused",
  18073. [](const Request &, Response &res, const ContentReader &) {
  18074. res.set_content("ignored", "text/plain");
  18075. });
  18076. port_ = svr_.bind_to_any_port(HOST);
  18077. thread_ = thread([&]() { svr_.listen_after_bind(); });
  18078. svr_.wait_until_ready();
  18079. }
  18080. void TearDown() override {
  18081. svr_.stop();
  18082. if (thread_.joinable()) { thread_.join(); }
  18083. }
  18084. // Sends `req` and reads until the server closes the connection. Returns
  18085. // false if the read had to wait for the client-side timeout instead.
  18086. bool send_until_closed(const std::string &req, std::string *resp) const {
  18087. auto start = std::chrono::steady_clock::now();
  18088. if (!send_request(3, req, resp, port_)) { return false; }
  18089. auto elapsed = std::chrono::steady_clock::now() - start;
  18090. return elapsed < std::chrono::seconds(2);
  18091. }
  18092. // The final response comes without `100 Continue`, and the server closes
  18093. // the connection since the body may or may not follow.
  18094. void expect_final_without_interim(const std::string &path,
  18095. const char *status_line) const {
  18096. std::string resp;
  18097. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  18098. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  18099. EXPECT_EQ(0u, resp.find(status_line));
  18100. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18101. }
  18102. Server svr_;
  18103. int port_ = 0;
  18104. thread thread_;
  18105. };
  18106. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  18107. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  18108. }
  18109. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  18110. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  18111. }
  18112. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  18113. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  18114. }
  18115. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  18116. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  18117. }
  18118. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  18119. // The body follows once `100 Continue` has had time to arrive.
  18120. auto req = expect_headers_only("/reader-used");
  18121. req.insert(req.size() - 2, "Connection: close\r\n");
  18122. std::string resp;
  18123. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  18124. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  18125. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  18126. EXPECT_NE(std::string::npos, resp.find("hi"));
  18127. }
  18128. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  18129. // Large enough for the client to add `Expect: 100-continue` itself.
  18130. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  18131. std::atomic<bool> body_sent{false};
  18132. Client cli(HOST, port_);
  18133. auto res = cli.Post(
  18134. "/pre-request", length,
  18135. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  18136. body_sent = true;
  18137. std::string chunk(len, 'x');
  18138. sink.write(chunk.data(), chunk.size());
  18139. return true;
  18140. },
  18141. "application/octet-stream");
  18142. ASSERT_TRUE(res);
  18143. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  18144. EXPECT_FALSE(body_sent);
  18145. }
  18146. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  18147. Server svr;
  18148. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  18149. return StatusCode::ExpectationFailed_417;
  18150. });
  18151. svr.Post("/p", [](const Request &, Response &res) {
  18152. res.set_content("ok", "text/plain");
  18153. });
  18154. auto port = svr.bind_to_any_port(HOST);
  18155. thread t = thread([&] { svr.listen_after_bind(); });
  18156. auto se = detail::scope_exit([&] {
  18157. svr.stop();
  18158. t.join();
  18159. });
  18160. svr.wait_until_ready();
  18161. std::string resp;
  18162. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  18163. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  18164. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  18165. // Exactly one response: the route handler must not run after the 417.
  18166. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  18167. }
  18168. #ifndef _WIN32
  18169. TEST(Expect100ContinueTest, ServerClosesConnection) {
  18170. static constexpr char reject[] = "Unauthorized";
  18171. static constexpr char accept[] = "Upload accepted";
  18172. constexpr uint64_t total_size = 10 * 1024 * 1024 * 1024ULL;
  18173. Server svr;
  18174. svr.set_expect_100_continue_handler(
  18175. [](const Request & /*req*/, Response &res) {
  18176. res.status = StatusCode::Unauthorized_401;
  18177. res.set_content(reject, "text/plain");
  18178. return res.status;
  18179. });
  18180. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  18181. res.set_content(accept, "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. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  18192. curl_easy_init(), &curl_easy_cleanup};
  18193. ASSERT_NE(curl, nullptr);
  18194. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  18195. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  18196. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  18197. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  18198. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  18199. &curl_slist_free_all};
  18200. ASSERT_NE(list, nullptr);
  18201. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  18202. struct read_data {
  18203. uint64_t read_size;
  18204. uint64_t total_size;
  18205. } data = {0, total_size};
  18206. using read_callback_t =
  18207. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18208. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  18209. void *userdata) -> size_t {
  18210. read_data *d = (read_data *)userdata;
  18211. if (!userdata || d->read_size >= d->total_size) { return 0; }
  18212. std::fill_n(ptr, size * nmemb, 'A');
  18213. d->read_size += size * nmemb;
  18214. return size * nmemb;
  18215. };
  18216. curl_easy_setopt(curl.get(), CURLOPT_READDATA, &data);
  18217. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  18218. std::vector<char> buffer;
  18219. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  18220. using write_callback_t =
  18221. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  18222. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  18223. void *userdata) -> size_t {
  18224. std::vector<char> *buf = (std::vector<char> *)userdata;
  18225. buf->reserve(buf->size() + size * nmemb + 1);
  18226. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  18227. return size * nmemb;
  18228. };
  18229. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  18230. {
  18231. const auto res = curl_easy_perform(curl.get());
  18232. ASSERT_EQ(res, CURLE_OK);
  18233. }
  18234. {
  18235. auto response_code = long{};
  18236. const auto res =
  18237. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  18238. ASSERT_EQ(res, CURLE_OK);
  18239. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  18240. }
  18241. {
  18242. auto dl = curl_off_t{};
  18243. const auto res =
  18244. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  18245. ASSERT_EQ(res, CURLE_OK);
  18246. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  18247. }
  18248. {
  18249. buffer.push_back('\0');
  18250. ASSERT_STRCASEEQ(buffer.data(), reject);
  18251. }
  18252. }
  18253. }
  18254. #endif
  18255. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  18256. // Regression test for #2458.
  18257. //
  18258. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  18259. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  18260. // ticket can make the client socket spuriously readable during the
  18261. // 100-continue wait. If the readiness is mistaken for an incoming response,
  18262. // the client withholds the body and then blocks reading a response that never
  18263. // comes, failing with `Failed to read connection`.
  18264. //
  18265. // A correct client (like curl) sends the body once no `100 Continue` arrives
  18266. // within the timeout. This raw OpenSSL server deliberately never sends
  18267. // `100 Continue`; the client must still deliver the body and receive 200.
  18268. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  18269. signal(SIGPIPE, SIG_IGN);
  18270. const auto port = PORT + 4;
  18271. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  18272. ASSERT_NE(srv, INVALID_SOCKET);
  18273. int opt = 1;
  18274. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  18275. sockaddr_in addr{};
  18276. addr.sin_family = AF_INET;
  18277. addr.sin_port = htons(static_cast<uint16_t>(port));
  18278. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  18279. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  18280. ASSERT_EQ(0, ::listen(srv, 1));
  18281. std::atomic<size_t> server_body_bytes{0};
  18282. auto server_thread = std::thread([&] {
  18283. sockaddr_in cli_addr{};
  18284. socklen_t cli_len = sizeof(cli_addr);
  18285. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  18286. if (cli == INVALID_SOCKET) { return; }
  18287. // Bound the lifetime of the server side so a buggy client (which never
  18288. // sends the body) cannot make this thread block forever on join.
  18289. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  18290. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  18291. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  18292. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  18293. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  18294. SSL *ssl = SSL_new(ctx);
  18295. SSL_set_fd(ssl, static_cast<int>(cli));
  18296. if (SSL_accept(ssl) > 0) {
  18297. // Read the request headers. Reading here also flushes the TLS 1.3
  18298. // session tickets to the client. Deliberately do NOT send
  18299. // `100 Continue`.
  18300. std::string buf;
  18301. char tmp[1024];
  18302. while (buf.find("\r\n\r\n") == std::string::npos) {
  18303. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18304. if (n <= 0) { break; }
  18305. buf.append(tmp, static_cast<size_t>(n));
  18306. }
  18307. // A correct client sends the body now; count what arrives.
  18308. auto pos = buf.find("\r\n\r\n");
  18309. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  18310. while (body < 4096) {
  18311. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  18312. if (n <= 0) { break; }
  18313. body += static_cast<size_t>(n);
  18314. }
  18315. server_body_bytes = body;
  18316. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  18317. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  18318. SSL_shutdown(ssl);
  18319. }
  18320. SSL_free(ssl);
  18321. detail::close_socket(cli);
  18322. SSL_CTX_free(ctx);
  18323. });
  18324. auto se = detail::scope_exit([&] {
  18325. server_thread.join();
  18326. detail::close_socket(srv);
  18327. });
  18328. SSLClient cli("127.0.0.1", port);
  18329. cli.enable_server_certificate_verification(false);
  18330. cli.set_connection_timeout(5, 0);
  18331. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  18332. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  18333. std::string body(4096, 'A');
  18334. auto res = cli.Put("/api/test", body, "application/json");
  18335. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  18336. EXPECT_EQ(StatusCode::OK_200, res->status);
  18337. EXPECT_EQ(body.size(), server_body_bytes.load());
  18338. }
  18339. #endif
  18340. template <typename S, typename C>
  18341. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  18342. svr.Get("/stream", [&](const Request &, Response &res) {
  18343. auto data = new std::string("01234567890123456789");
  18344. res.set_content_provider(
  18345. data->size(), "text/plain",
  18346. [&, data](size_t offset, size_t length, DataSink &sink) {
  18347. const size_t DATA_CHUNK_SIZE = 4;
  18348. const auto &d = *data;
  18349. std::this_thread::sleep_for(std::chrono::seconds(1));
  18350. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  18351. return true;
  18352. },
  18353. [data](bool success) {
  18354. EXPECT_FALSE(success);
  18355. delete data;
  18356. });
  18357. });
  18358. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  18359. auto i = new size_t(0);
  18360. res.set_content_provider(
  18361. "text/plain",
  18362. [i](size_t, DataSink &sink) {
  18363. if (*i < 5) {
  18364. std::this_thread::sleep_for(std::chrono::seconds(1));
  18365. sink.write("abcd", 4);
  18366. (*i)++;
  18367. } else {
  18368. sink.done();
  18369. }
  18370. return true;
  18371. },
  18372. [i](bool success) {
  18373. EXPECT_FALSE(success);
  18374. delete i;
  18375. });
  18376. });
  18377. svr.Get("/chunked", [&](const Request &, Response &res) {
  18378. auto i = new size_t(0);
  18379. res.set_chunked_content_provider(
  18380. "text/plain",
  18381. [i](size_t, DataSink &sink) {
  18382. if (*i < 5) {
  18383. std::this_thread::sleep_for(std::chrono::seconds(1));
  18384. sink.os << "abcd";
  18385. (*i)++;
  18386. } else {
  18387. sink.done();
  18388. }
  18389. return true;
  18390. },
  18391. [i](bool success) {
  18392. EXPECT_FALSE(success);
  18393. delete i;
  18394. });
  18395. });
  18396. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  18397. auto se = detail::scope_exit([&] {
  18398. svr.stop();
  18399. listen_thread.join();
  18400. ASSERT_FALSE(svr.is_running());
  18401. });
  18402. svr.wait_until_ready();
  18403. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  18404. {
  18405. auto start = std::chrono::steady_clock::now();
  18406. auto res = cli.Get("/stream");
  18407. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18408. std::chrono::steady_clock::now() - start)
  18409. .count();
  18410. ASSERT_FALSE(res);
  18411. EXPECT_EQ(Error::Read, res.error());
  18412. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18413. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18414. }
  18415. {
  18416. auto start = std::chrono::steady_clock::now();
  18417. auto res = cli.Get("/stream_without_length");
  18418. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18419. std::chrono::steady_clock::now() - start)
  18420. .count();
  18421. ASSERT_FALSE(res);
  18422. EXPECT_EQ(Error::Read, res.error());
  18423. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18424. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18425. }
  18426. {
  18427. auto start = std::chrono::steady_clock::now();
  18428. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  18429. EXPECT_EQ("abcd", string(data, data_length));
  18430. return true;
  18431. });
  18432. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  18433. std::chrono::steady_clock::now() - start)
  18434. .count();
  18435. ASSERT_FALSE(res);
  18436. EXPECT_EQ(Error::Read, res.error());
  18437. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  18438. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  18439. }
  18440. }
  18441. TEST(MaxTimeoutTest, ContentStream) {
  18442. time_t timeout = 2000;
  18443. time_t threshold = 200;
  18444. Server svr;
  18445. Client cli("localhost", PORT);
  18446. max_timeout_test(svr, cli, timeout, threshold);
  18447. }
  18448. #ifdef CPPHTTPLIB_SSL_ENABLED
  18449. TEST(MaxTimeoutTest, ContentStreamSSL) {
  18450. time_t timeout = 2000;
  18451. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  18452. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  18453. SSLClient cli("localhost", PORT);
  18454. cli.enable_server_certificate_verification(false);
  18455. max_timeout_test(svr, cli, timeout, threshold);
  18456. }
  18457. #endif
  18458. class EventDispatcher {
  18459. public:
  18460. EventDispatcher() {}
  18461. bool wait_event(DataSink *sink) {
  18462. unique_lock<mutex> lk(m_);
  18463. int id = id_;
  18464. // Wait with timeout to prevent hanging if client disconnects
  18465. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  18466. [&] { return cid_ == id; })) {
  18467. return false; // Timeout occurred
  18468. }
  18469. sink->write(message_.data(), message_.size());
  18470. return true;
  18471. }
  18472. void send_event(const string &message) {
  18473. lock_guard<mutex> lk(m_);
  18474. cid_ = id_++;
  18475. message_ = message;
  18476. cv_.notify_all();
  18477. }
  18478. private:
  18479. mutex m_;
  18480. condition_variable cv_;
  18481. atomic_int id_{0};
  18482. atomic_int cid_{-1};
  18483. string message_;
  18484. };
  18485. TEST(ClientInThreadTest, Issue2068) {
  18486. EventDispatcher ed;
  18487. Server svr;
  18488. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  18489. res.set_chunked_content_provider("text/event-stream",
  18490. [&](size_t /*offset*/, DataSink &sink) {
  18491. return ed.wait_event(&sink);
  18492. });
  18493. });
  18494. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  18495. svr.wait_until_ready();
  18496. thread event_thread([&] {
  18497. int id = 0;
  18498. while (svr.is_running()) {
  18499. this_thread::sleep_for(chrono::milliseconds(500));
  18500. std::stringstream ss;
  18501. ss << "data: " << id << "\n\n";
  18502. ed.send_event(ss.str());
  18503. id++;
  18504. }
  18505. });
  18506. auto se = detail::scope_exit([&] {
  18507. svr.stop();
  18508. listen_thread.join();
  18509. event_thread.join();
  18510. ASSERT_FALSE(svr.is_running());
  18511. });
  18512. {
  18513. auto client = detail::make_unique<Client>(HOST, PORT);
  18514. client->set_read_timeout(std::chrono::minutes(10));
  18515. std::atomic<bool> stop{false};
  18516. std::thread t([&] {
  18517. client->Get("/event1",
  18518. [&](const char *, size_t) -> bool { return !stop; });
  18519. });
  18520. std::this_thread::sleep_for(std::chrono::seconds(2));
  18521. stop = true;
  18522. client->stop();
  18523. t.join();
  18524. // Reset client after thread has finished
  18525. client.reset();
  18526. }
  18527. }
  18528. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  18529. auto handled = false;
  18530. Server svr;
  18531. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  18532. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18533. auto se = detail::scope_exit([&] {
  18534. svr.stop();
  18535. t.join();
  18536. ASSERT_FALSE(svr.is_running());
  18537. ASSERT_FALSE(handled);
  18538. });
  18539. svr.wait_until_ready();
  18540. // Two Content-Length headers with different values — must be rejected
  18541. auto req = "POST /test HTTP/1.1\r\n"
  18542. "Content-Length: 5\r\n"
  18543. "Content-Length: 10\r\n"
  18544. "\r\n"
  18545. "hello";
  18546. std::string response;
  18547. ASSERT_TRUE(send_request(1, req, &response));
  18548. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  18549. response.substr(0, response.find("\r\n")));
  18550. }
  18551. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  18552. auto handled = false;
  18553. Server svr;
  18554. svr.Post("/test", [&](const Request &, Response &res) {
  18555. handled = true;
  18556. res.set_content("ok", "text/plain");
  18557. });
  18558. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18559. auto se = detail::scope_exit([&] {
  18560. svr.stop();
  18561. t.join();
  18562. ASSERT_FALSE(svr.is_running());
  18563. ASSERT_TRUE(handled);
  18564. });
  18565. svr.wait_until_ready();
  18566. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  18567. auto req = "POST /test HTTP/1.1\r\n"
  18568. "Host: localhost\r\n"
  18569. "Content-Length: 5\r\n"
  18570. "Content-Length: 5\r\n"
  18571. "\r\n"
  18572. "hello";
  18573. std::string response;
  18574. ASSERT_TRUE(send_request(1, req, &response));
  18575. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  18576. }
  18577. TEST(HostHeaderValidationTest, AmbiguousOrInvalidHostRejected) {
  18578. Server svr;
  18579. svr.Get("/test", [](const Request &, Response &res) {
  18580. res.set_content("ok", "text/plain");
  18581. });
  18582. auto port = svr.bind_to_any_port(HOST);
  18583. thread t = thread([&] { svr.listen_after_bind(); });
  18584. auto se = detail::scope_exit([&] {
  18585. svr.stop();
  18586. t.join();
  18587. ASSERT_FALSE(svr.is_running());
  18588. });
  18589. svr.wait_until_ready();
  18590. auto status_line = [&](const std::string &host_lines) {
  18591. std::string res;
  18592. send_request(
  18593. 5, "GET /test HTTP/1.1\r\n" + host_lines + "Connection: close\r\n\r\n",
  18594. &res, port);
  18595. return res.substr(0, res.find("\r\n"));
  18596. };
  18597. const char *accepted[] = {
  18598. "Host: localhost\r\n",
  18599. "Host: a.example:8080\r\n",
  18600. "Host: my_service\r\n",
  18601. "Host: [::1]:8080\r\n",
  18602. "Host: [fe80::1%25eth0]\r\n",
  18603. "Host: \r\n", // RFC 9112 §3.2: the target URI has no authority
  18604. };
  18605. for (auto host_lines : accepted) {
  18606. EXPECT_EQ("HTTP/1.1 200 OK", status_line(host_lines)) << host_lines;
  18607. }
  18608. const char *rejected[] = {
  18609. "Host: a.example\r\nHost: b.example\r\n",
  18610. "Host: a.example\r\nHost: a.example\r\n",
  18611. "Host: a@b.example\r\n",
  18612. "Host: a.example/b\r\n",
  18613. "Host: a.example\\b\r\n",
  18614. "Host: a.example?b\r\n",
  18615. "Host: a.example#b\r\n",
  18616. "Host: a.example b.example\r\n",
  18617. };
  18618. for (auto host_lines : rejected) {
  18619. EXPECT_EQ("HTTP/1.1 400 Bad Request", status_line(host_lines))
  18620. << host_lines;
  18621. }
  18622. }
  18623. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  18624. Server svr;
  18625. svr.Get("/", [](const Request &req, Response &res) {
  18626. EXPECT_EQ(2U, req.trailers.size());
  18627. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  18628. // Denied
  18629. EXPECT_FALSE(req.has_trailer("Content-Length"));
  18630. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  18631. // Accepted
  18632. EXPECT_TRUE(req.has_trailer("X-Hello"));
  18633. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  18634. EXPECT_TRUE(req.has_trailer("X-World"));
  18635. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  18636. res.set_content("ok", "text/plain");
  18637. });
  18638. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18639. auto se = detail::scope_exit([&] {
  18640. svr.stop();
  18641. t.join();
  18642. ASSERT_FALSE(svr.is_running());
  18643. });
  18644. svr.wait_until_ready();
  18645. const std::string req = "GET / HTTP/1.1\r\n"
  18646. "Transfer-Encoding: chunked\r\n"
  18647. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  18648. "\r\n"
  18649. "0\r\n"
  18650. "Content-Length: 10\r\n"
  18651. "Host: internal.local\r\n"
  18652. "Content-Type: malicious/content\r\n"
  18653. "Cookie: any\r\n"
  18654. "Set-Cookie: any\r\n"
  18655. "X-Forwarded-For: attacker.com\r\n"
  18656. "X-Real-Ip: 1.1.1.1\r\n"
  18657. "X-Hello: hello\r\n"
  18658. "X-World: world\r\n"
  18659. "\r\n";
  18660. std::string res;
  18661. ASSERT_TRUE(send_request(1, req, &res));
  18662. }
  18663. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  18664. // several field lines, and the combined value is what has to be parsed. A
  18665. // Trailer field split across lines therefore declares every name it lists;
  18666. // reading only the first line silently drops the trailers the later lines
  18667. // declare. The prohibited-trailer filter still applies to every line.
  18668. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  18669. Server svr;
  18670. size_t observed_trailer_count = 0;
  18671. std::string observed_hello;
  18672. std::string observed_world;
  18673. bool observed_content_length = true;
  18674. svr.Get("/", [&](const Request &req, Response &res) {
  18675. observed_trailer_count = req.trailers.size();
  18676. observed_hello = req.get_trailer_value("X-Hello");
  18677. observed_world = req.get_trailer_value("X-World");
  18678. observed_content_length = req.has_trailer("Content-Length");
  18679. res.set_content("ok", "text/plain");
  18680. });
  18681. auto port = svr.bind_to_any_port(HOST);
  18682. thread t = thread([&]() { svr.listen_after_bind(); });
  18683. auto se = detail::scope_exit([&] {
  18684. svr.stop();
  18685. t.join();
  18686. ASSERT_FALSE(svr.is_running());
  18687. });
  18688. svr.wait_until_ready();
  18689. const std::string req = "GET / HTTP/1.1\r\n"
  18690. "Host: localhost\r\n"
  18691. "Transfer-Encoding: chunked\r\n"
  18692. "Trailer: X-Hello\r\n"
  18693. "Trailer: X-World, Content-Length\r\n"
  18694. "\r\n"
  18695. "0\r\n"
  18696. "X-Hello: hello\r\n"
  18697. "X-World: world\r\n"
  18698. "Content-Length: 10\r\n"
  18699. "\r\n";
  18700. std::string res;
  18701. ASSERT_TRUE(send_request(1, req, &res, port));
  18702. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  18703. // Accepted: both field lines contribute to the declared set
  18704. EXPECT_EQ(2U, observed_trailer_count);
  18705. EXPECT_EQ(observed_hello, "hello");
  18706. EXPECT_EQ(observed_world, "world");
  18707. // Denied: a prohibited name stays prohibited on a later field line
  18708. EXPECT_FALSE(observed_content_length);
  18709. }
  18710. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  18711. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  18712. // unbounded run of fields that are never declared, because the counter would
  18713. // only advance for declared fields.
  18714. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  18715. Server svr;
  18716. bool handler_called = false;
  18717. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  18718. handler_called = true;
  18719. res.set_content("ok", "text/plain");
  18720. });
  18721. auto port = svr.bind_to_any_port(HOST);
  18722. thread t = thread([&]() { svr.listen_after_bind(); });
  18723. auto se = detail::scope_exit([&] {
  18724. svr.stop();
  18725. t.join();
  18726. ASSERT_FALSE(svr.is_running());
  18727. });
  18728. svr.wait_until_ready();
  18729. // Declare nothing, then send far more undeclared trailer fields than the
  18730. // header-count limit. Parsing must stop and reject the request rather than
  18731. // read every line.
  18732. std::string req = "GET / HTTP/1.1\r\n"
  18733. "Transfer-Encoding: chunked\r\n"
  18734. "\r\n"
  18735. "0\r\n";
  18736. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  18737. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  18738. }
  18739. req += "\r\n";
  18740. std::string res;
  18741. ASSERT_TRUE(send_request(1, req, &res, port));
  18742. // The request is rejected before the handler runs.
  18743. EXPECT_FALSE(handler_called);
  18744. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  18745. }
  18746. // The set of declared trailer names is capped so a peer cannot grow it without
  18747. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  18748. // declared past the cap is not honored, even if the field is actually sent.
  18749. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  18750. Server svr;
  18751. // One name inside the cap and one past it, so the test tracks the cap rather
  18752. // than a fixed count.
  18753. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  18754. const std::string within_cap_name = "X-T-0";
  18755. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  18756. bool observed_within_cap = false;
  18757. bool observed_past_cap = false;
  18758. svr.Get("/", [&](const Request &req, Response &res) {
  18759. observed_within_cap = req.has_trailer(within_cap_name);
  18760. observed_past_cap = req.has_trailer(past_cap_name);
  18761. res.set_content("ok", "text/plain");
  18762. });
  18763. auto port = svr.bind_to_any_port(HOST);
  18764. thread t = thread([&]() { svr.listen_after_bind(); });
  18765. auto se = detail::scope_exit([&] {
  18766. svr.stop();
  18767. t.join();
  18768. ASSERT_FALSE(svr.is_running());
  18769. });
  18770. svr.wait_until_ready();
  18771. // Declare more trailer names than the cap in a single Trailer field, then
  18772. // actually send the first (within the cap) and the last (past it).
  18773. std::string trailer_decl = "Trailer: ";
  18774. for (int i = 0; i < declared_count; i++) {
  18775. if (i != 0) { trailer_decl += ", "; }
  18776. trailer_decl += "X-T-" + std::to_string(i);
  18777. }
  18778. trailer_decl += "\r\n";
  18779. const std::string req = "GET / HTTP/1.1\r\n"
  18780. "Host: localhost\r\n"
  18781. "Transfer-Encoding: chunked\r\n" +
  18782. trailer_decl +
  18783. "\r\n"
  18784. "0\r\n" +
  18785. within_cap_name + ": a\r\n" + past_cap_name +
  18786. ": b\r\n"
  18787. "\r\n";
  18788. std::string res;
  18789. ASSERT_TRUE(send_request(1, req, &res, port));
  18790. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  18791. // A name within the cap is honored; one declared past the cap is dropped.
  18792. EXPECT_TRUE(observed_within_cap);
  18793. EXPECT_FALSE(observed_past_cap);
  18794. }
  18795. // A direct client that is not listed in trusted_proxies must not be able to
  18796. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  18797. // the peer address on the actual TCP connection determines whether the
  18798. // header is honored.
  18799. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  18800. Server svr;
  18801. // Deliberately does NOT include the loopback address the test client
  18802. // actually connects from, so the direct connection is not a trusted proxy.
  18803. svr.set_trusted_proxies({"203.0.113.66"});
  18804. std::string observed_remote_addr;
  18805. svr.Get("/ip", [&](const Request &req, Response &res) {
  18806. observed_remote_addr = req.remote_addr;
  18807. res.set_content("ok", "text/plain");
  18808. });
  18809. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18810. auto se = detail::scope_exit([&] {
  18811. svr.stop();
  18812. t.join();
  18813. ASSERT_FALSE(svr.is_running());
  18814. });
  18815. svr.wait_until_ready();
  18816. Client cli(HOST, PORT);
  18817. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  18818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18819. EXPECT_EQ(StatusCode::OK_200, res->status);
  18820. // The connecting peer is not a trusted proxy, so the spoofed header must be
  18821. // ignored entirely and the real connection-level address retained.
  18822. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18823. observed_remote_addr == "127.0.0.1");
  18824. }
  18825. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  18826. Server svr;
  18827. std::string observed_remote_addr;
  18828. std::string observed_xff;
  18829. svr.Get("/ip", [&](const Request &req, Response &res) {
  18830. observed_remote_addr = req.remote_addr;
  18831. observed_xff = req.get_header_value("X-Forwarded-For");
  18832. res.set_content("ok", "text/plain");
  18833. });
  18834. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18835. auto se = detail::scope_exit([&] {
  18836. svr.stop();
  18837. t.join();
  18838. ASSERT_FALSE(svr.is_running());
  18839. });
  18840. svr.wait_until_ready();
  18841. Client cli(HOST, PORT);
  18842. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  18843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18844. EXPECT_EQ(StatusCode::OK_200, res->status);
  18845. EXPECT_EQ(observed_xff, "203.0.113.66");
  18846. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18847. observed_remote_addr == "127.0.0.1");
  18848. }
  18849. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  18850. Server svr;
  18851. svr.set_trusted_proxies({"203.0.113.66"});
  18852. std::string observed_remote_addr;
  18853. std::string observed_xff;
  18854. svr.Get("/ip", [&](const Request &req, Response &res) {
  18855. observed_remote_addr = req.remote_addr;
  18856. observed_xff = req.get_header_value("X-Forwarded-For");
  18857. res.set_content("ok", "text/plain");
  18858. });
  18859. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18860. auto se = detail::scope_exit([&] {
  18861. svr.stop();
  18862. t.join();
  18863. ASSERT_FALSE(svr.is_running());
  18864. });
  18865. svr.wait_until_ready();
  18866. Client cli(HOST, PORT);
  18867. auto res = cli.Get("/ip");
  18868. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18869. EXPECT_EQ(StatusCode::OK_200, res->status);
  18870. EXPECT_EQ(observed_xff, "");
  18871. EXPECT_TRUE(observed_remote_addr == "::1" ||
  18872. observed_remote_addr == "127.0.0.1");
  18873. }
  18874. // A server listening on both IPv4 and IPv6 sees an IPv4 peer as an
  18875. // IPv4-mapped IPv6 address, which still matches the proxy's IPv4 address
  18876. TEST(ForwardedHeadersTest, IPv4MappedPeerMatchesIPv4Proxy) {
  18877. Server svr;
  18878. svr.set_trusted_proxies({"127.0.0.1"});
  18879. svr.Get("/ip", [](const Request &req, Response &res) {
  18880. res.set_content(req.remote_addr, "text/plain");
  18881. });
  18882. auto port = svr.bind_to_any_port("::");
  18883. if (port <= 0) { GTEST_SKIP() << "no IPv6 on this host"; }
  18884. thread t = thread([&] { svr.listen_after_bind(); });
  18885. auto se = detail::scope_exit([&] {
  18886. svr.stop();
  18887. t.join();
  18888. ASSERT_FALSE(svr.is_running());
  18889. });
  18890. svr.wait_until_ready();
  18891. Client cli("127.0.0.1", port);
  18892. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "198.51.100.23"}});
  18893. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18894. EXPECT_EQ("198.51.100.23", res->body);
  18895. }
  18896. TEST(ForwardedHeadersTest, IPv4MappedHopMatchesIPv4Proxy) {
  18897. Server svr;
  18898. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18899. svr.Get("/ip", [](const Request &req, Response &res) {
  18900. res.set_content(req.remote_addr, "text/plain");
  18901. });
  18902. auto port = svr.bind_to_any_port(HOST);
  18903. ASSERT_GT(port, 0);
  18904. thread t = thread([&] { svr.listen_after_bind(); });
  18905. auto se = detail::scope_exit([&] {
  18906. svr.stop();
  18907. t.join();
  18908. ASSERT_FALSE(svr.is_running());
  18909. });
  18910. svr.wait_until_ready();
  18911. Client cli(HOST, port);
  18912. auto res = cli.Get(
  18913. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, ::ffff:192.0.2.45"}});
  18914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18915. EXPECT_EQ("198.51.100.23", res->body);
  18916. }
  18917. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  18918. Server svr;
  18919. // Include the loopback address the test client actually connects from, so
  18920. // the direct connection itself is recognized as the trusted proxy hop.
  18921. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  18922. std::string observed_remote_addr;
  18923. std::string observed_xff;
  18924. svr.Get("/ip", [&](const Request &req, Response &res) {
  18925. observed_remote_addr = req.remote_addr;
  18926. observed_xff = req.get_header_value("X-Forwarded-For");
  18927. res.set_content("ok", "text/plain");
  18928. });
  18929. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18930. auto se = detail::scope_exit([&] {
  18931. svr.stop();
  18932. t.join();
  18933. ASSERT_FALSE(svr.is_running());
  18934. });
  18935. svr.wait_until_ready();
  18936. Client cli(HOST, PORT);
  18937. auto res = cli.Get(
  18938. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  18939. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18940. EXPECT_EQ(StatusCode::OK_200, res->status);
  18941. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  18942. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18943. }
  18944. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  18945. Server svr;
  18946. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  18947. std::string observed_remote_addr;
  18948. std::string observed_xff;
  18949. svr.Get("/ip", [&](const Request &req, Response &res) {
  18950. observed_remote_addr = req.remote_addr;
  18951. observed_xff = req.get_header_value("X-Forwarded-For");
  18952. res.set_content("ok", "text/plain");
  18953. });
  18954. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18955. auto se = detail::scope_exit([&] {
  18956. svr.stop();
  18957. t.join();
  18958. ASSERT_FALSE(svr.is_running());
  18959. });
  18960. svr.wait_until_ready();
  18961. Client cli(HOST, PORT);
  18962. auto res = cli.Get(
  18963. "/ip",
  18964. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  18965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18966. EXPECT_EQ(StatusCode::OK_200, res->status);
  18967. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  18968. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  18969. }
  18970. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  18971. Server svr;
  18972. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  18973. std::string observed_remote_addr;
  18974. std::string observed_xff;
  18975. svr.Get("/ip", [&](const Request &req, Response &res) {
  18976. observed_remote_addr = req.remote_addr;
  18977. observed_xff = req.get_header_value("X-Forwarded-For");
  18978. res.set_content("ok", "text/plain");
  18979. });
  18980. thread t = thread([&]() { svr.listen(HOST, PORT); });
  18981. auto se = detail::scope_exit([&] {
  18982. svr.stop();
  18983. t.join();
  18984. ASSERT_FALSE(svr.is_running());
  18985. });
  18986. svr.wait_until_ready();
  18987. Client cli(HOST, PORT);
  18988. auto res = cli.Get(
  18989. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  18990. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  18991. EXPECT_EQ(StatusCode::OK_200, res->status);
  18992. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  18993. // by the closest hop) is used. The leftmost entry is fully client-controlled
  18994. // and must not be selected.
  18995. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  18996. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  18997. }
  18998. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  18999. Server svr;
  19000. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  19001. std::string observed_remote_addr;
  19002. svr.Get("/ip", [&](const Request &req, Response &res) {
  19003. observed_remote_addr = req.remote_addr;
  19004. res.set_content("ok", "text/plain");
  19005. });
  19006. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19007. auto se = detail::scope_exit([&] {
  19008. svr.stop();
  19009. t.join();
  19010. ASSERT_FALSE(svr.is_running());
  19011. });
  19012. svr.wait_until_ready();
  19013. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  19014. // a forged address and the trusted proxy's own address; the forged value must
  19015. // not win over the address the trusted proxy actually recorded.
  19016. Client cli(HOST, PORT);
  19017. auto res = cli.Get(
  19018. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  19019. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19020. EXPECT_EQ(StatusCode::OK_200, res->status);
  19021. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  19022. }
  19023. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  19024. Server svr;
  19025. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19026. std::string observed_remote_addr;
  19027. std::string observed_xff;
  19028. svr.Get("/ip", [&](const Request &req, Response &res) {
  19029. observed_remote_addr = req.remote_addr;
  19030. observed_xff = req.get_header_value("X-Forwarded-For");
  19031. res.set_content("ok", "text/plain");
  19032. });
  19033. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19034. auto se = detail::scope_exit([&] {
  19035. svr.stop();
  19036. t.join();
  19037. ASSERT_FALSE(svr.is_running());
  19038. });
  19039. svr.wait_until_ready();
  19040. Client cli(HOST, PORT);
  19041. auto res = cli.Get(
  19042. "/ip",
  19043. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  19044. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19045. EXPECT_EQ(StatusCode::OK_200, res->status);
  19046. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  19047. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19048. }
  19049. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  19050. Server svr;
  19051. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19052. std::string observed_remote_addr;
  19053. std::string observed_xff;
  19054. svr.Get("/ip", [&](const Request &req, Response &res) {
  19055. observed_remote_addr = req.remote_addr;
  19056. observed_xff = req.get_header_value("X-Forwarded-For");
  19057. res.set_content("ok", "text/plain");
  19058. });
  19059. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19060. auto se = detail::scope_exit([&] {
  19061. svr.stop();
  19062. t.join();
  19063. ASSERT_FALSE(svr.is_running());
  19064. });
  19065. svr.wait_until_ready();
  19066. std::string raw_req =
  19067. "GET /ip HTTP/1.1\r\n"
  19068. "Host: localhost\r\n"
  19069. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  19070. "Connection: close\r\n"
  19071. "\r\n";
  19072. std::string out;
  19073. ASSERT_TRUE(send_request(5, raw_req, &out));
  19074. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19075. // Header parser trims surrounding whitespace of the header value
  19076. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  19077. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  19078. }
  19079. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  19080. // one comma-joined value, in the order received. Proxies such as HAProxy append
  19081. // their own X-Forwarded-For as a separate field line rather than extending the
  19082. // one the client sent, so every occurrence has to be taken into account.
  19083. // Reading only the first one hands back the address the client chose.
  19084. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  19085. Server svr;
  19086. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  19087. std::string observed_remote_addr;
  19088. size_t observed_xff_count = 0;
  19089. svr.Get("/ip", [&](const Request &req, Response &res) {
  19090. observed_remote_addr = req.remote_addr;
  19091. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  19092. res.set_content("ok", "text/plain");
  19093. });
  19094. auto port = svr.bind_to_any_port(HOST);
  19095. thread t = thread([&]() { svr.listen_after_bind(); });
  19096. auto se = detail::scope_exit([&] {
  19097. svr.stop();
  19098. t.join();
  19099. ASSERT_FALSE(svr.is_running());
  19100. });
  19101. svr.wait_until_ready();
  19102. // The client supplies the first field line; the trusted proxy appends the
  19103. // address it observed as a second one.
  19104. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  19105. "Host: localhost\r\n"
  19106. "X-Forwarded-For: 1.2.3.4\r\n"
  19107. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  19108. "Connection: close\r\n"
  19109. "\r\n";
  19110. std::string out;
  19111. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19112. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19113. EXPECT_EQ(observed_xff_count, 2U);
  19114. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19115. // The same chain spread over one field line per hop derives the same client
  19116. // address, i.e. the split and the comma-joined representations agree.
  19117. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  19118. "Host: localhost\r\n"
  19119. "X-Forwarded-For: 1.2.3.4\r\n"
  19120. "X-Forwarded-For: 198.51.100.23\r\n"
  19121. "X-Forwarded-For: 192.0.2.45\r\n"
  19122. "Connection: close\r\n"
  19123. "\r\n";
  19124. out.clear();
  19125. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  19126. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19127. EXPECT_EQ(observed_xff_count, 3U);
  19128. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  19129. }
  19130. // An X-Forwarded-For header whose value parses to zero IP segments must not
  19131. // crash the server (it used to call front() on an empty vector inside
  19132. // get_client_ip). The connection-level remote address must be retained instead.
  19133. static void run_malformed_xff_test(const std::string &xff_value) {
  19134. Server svr;
  19135. svr.set_trusted_proxies({"192.0.2.45"});
  19136. std::string observed_remote_addr;
  19137. svr.Get("/ip", [&](const Request &req, Response &res) {
  19138. observed_remote_addr = req.remote_addr;
  19139. res.set_content("ok", "text/plain");
  19140. });
  19141. int port = 0;
  19142. thread t = thread([&]() {
  19143. port = svr.bind_to_any_port(HOST);
  19144. svr.listen_after_bind();
  19145. });
  19146. auto se = detail::scope_exit([&] {
  19147. svr.stop();
  19148. t.join();
  19149. ASSERT_FALSE(svr.is_running());
  19150. });
  19151. svr.wait_until_ready();
  19152. Client cli(HOST, port);
  19153. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  19154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19155. EXPECT_EQ(StatusCode::OK_200, res->status);
  19156. EXPECT_TRUE(observed_remote_addr == "::1" ||
  19157. observed_remote_addr == "127.0.0.1");
  19158. }
  19159. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  19160. run_malformed_xff_test("");
  19161. }
  19162. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  19163. run_malformed_xff_test(",");
  19164. }
  19165. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  19166. run_malformed_xff_test(", , ,");
  19167. }
  19168. // The same rule applies to Accept: a request whose acceptable types are spread
  19169. // over several field lines must be negotiated against all of them.
  19170. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  19171. // case-insensitive connection options. Comparing the whole field value against
  19172. // one option misses a client that sends several of them, and misses every
  19173. // casing but the one written in the comparison.
  19174. //
  19175. // Sends req, reads the response, then reuses the same socket for a second
  19176. // request to find out whether the server kept the connection.
  19177. static void probe_connection_reuse(int port, const std::string &req,
  19178. bool *announced_close, bool *reusable) {
  19179. auto error = Error::Success;
  19180. auto sock = detail::create_client_socket(
  19181. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  19182. /*connection_timeout_sec=*/5, 0,
  19183. /*read_timeout_sec=*/1, 0,
  19184. /*write_timeout_sec=*/5, 0, std::string(), error);
  19185. ASSERT_NE(sock, INVALID_SOCKET);
  19186. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  19187. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  19188. "Host: localhost\r\n"
  19189. "Connection: close\r\n"
  19190. "\r\n";
  19191. std::string first_response;
  19192. std::string second_response;
  19193. detail::process_client_socket(
  19194. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  19195. [&](Stream &strm) {
  19196. if (strm.write(req.data(), req.size()) !=
  19197. static_cast<ssize_t>(req.size())) {
  19198. return false;
  19199. }
  19200. char buf[512];
  19201. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  19202. // Headers plus the two-byte body of the handler below
  19203. while (reader.getline()) {
  19204. first_response += reader.ptr();
  19205. if (first_response.find("ok") != std::string::npos) { break; }
  19206. }
  19207. if (strm.write(second.data(), second.size()) !=
  19208. static_cast<ssize_t>(second.size())) {
  19209. return true;
  19210. }
  19211. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  19212. while (reader2.getline()) {
  19213. second_response += reader2.ptr();
  19214. if (second_response.find("ok") != std::string::npos) { break; }
  19215. }
  19216. return true;
  19217. });
  19218. *announced_close =
  19219. first_response.find("Connection: close") != std::string::npos;
  19220. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  19221. }
  19222. class ConnectionTokenTest : public ::testing::Test {
  19223. protected:
  19224. void SetUp() override {
  19225. svr_.Get("/keepalive", [](const Request &, Response &res) {
  19226. res.set_content("ok", "text/plain");
  19227. });
  19228. port_ = svr_.bind_to_any_port(HOST);
  19229. thread_ = thread([&]() { svr_.listen_after_bind(); });
  19230. svr_.wait_until_ready();
  19231. }
  19232. void TearDown() override {
  19233. svr_.stop();
  19234. if (thread_.joinable()) { thread_.join(); }
  19235. }
  19236. Server svr_;
  19237. int port_ = 0;
  19238. thread thread_;
  19239. };
  19240. // "close" alongside another option still closes the connection, and the
  19241. // response says so rather than leaving the peer to discover it.
  19242. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  19243. bool announced_close = false;
  19244. bool reusable = true;
  19245. probe_connection_reuse(port_,
  19246. "GET /keepalive HTTP/1.1\r\n"
  19247. "Host: localhost\r\n"
  19248. "Connection: keep-alive, close\r\n"
  19249. "\r\n",
  19250. &announced_close, &reusable);
  19251. EXPECT_TRUE(announced_close);
  19252. EXPECT_FALSE(reusable);
  19253. }
  19254. // "close" split over two field lines is the same list, so it is honored too.
  19255. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  19256. bool announced_close = false;
  19257. bool reusable = true;
  19258. probe_connection_reuse(port_,
  19259. "GET /keepalive HTTP/1.1\r\n"
  19260. "Host: localhost\r\n"
  19261. "Connection: keep-alive\r\n"
  19262. "Connection: close\r\n"
  19263. "\r\n",
  19264. &announced_close, &reusable);
  19265. EXPECT_TRUE(announced_close);
  19266. EXPECT_FALSE(reusable);
  19267. }
  19268. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  19269. // keep-alive in the spelling everyone actually sends keeps its connection.
  19270. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  19271. bool announced_close = false;
  19272. bool reusable = false;
  19273. probe_connection_reuse(port_,
  19274. "GET /keepalive HTTP/1.0\r\n"
  19275. "Host: localhost\r\n"
  19276. "Connection: keep-alive\r\n"
  19277. "\r\n",
  19278. &announced_close, &reusable);
  19279. EXPECT_FALSE(announced_close);
  19280. EXPECT_TRUE(reusable);
  19281. }
  19282. // A token the value merely contains is not the token itself.
  19283. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  19284. bool announced_close = false;
  19285. bool reusable = false;
  19286. probe_connection_reuse(port_,
  19287. "GET /keepalive HTTP/1.1\r\n"
  19288. "Host: localhost\r\n"
  19289. "Connection: notclose\r\n"
  19290. "\r\n",
  19291. &announced_close, &reusable);
  19292. EXPECT_FALSE(announced_close);
  19293. EXPECT_TRUE(reusable);
  19294. }
  19295. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  19296. Server svr;
  19297. std::vector<std::string> observed_types;
  19298. svr.Get("/", [&](const Request &req, Response &res) {
  19299. observed_types = req.accept_content_types;
  19300. res.set_content("ok", "text/plain");
  19301. });
  19302. auto port = svr.bind_to_any_port(HOST);
  19303. thread t = thread([&]() { svr.listen_after_bind(); });
  19304. auto se = detail::scope_exit([&] {
  19305. svr.stop();
  19306. t.join();
  19307. ASSERT_FALSE(svr.is_running());
  19308. });
  19309. svr.wait_until_ready();
  19310. Client cli(HOST, port);
  19311. Headers headers;
  19312. headers.emplace("Accept", "text/plain;q=0.5");
  19313. headers.emplace("Accept", "application/json");
  19314. auto res = cli.Get("/", headers);
  19315. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19316. EXPECT_EQ(StatusCode::OK_200, res->status);
  19317. // Sorted by q-value, so the second field line's type comes first
  19318. ASSERT_EQ(2U, observed_types.size());
  19319. EXPECT_EQ("application/json", observed_types[0]);
  19320. EXPECT_EQ("text/plain", observed_types[1]);
  19321. }
  19322. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  19323. // empty field line must not contribute a bare comma to the combined value.
  19324. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  19325. Server svr;
  19326. std::vector<std::string> observed_types;
  19327. svr.Get("/", [&](const Request &req, Response &res) {
  19328. observed_types = req.accept_content_types;
  19329. res.set_content("ok", "text/plain");
  19330. });
  19331. auto port = svr.bind_to_any_port(HOST);
  19332. thread t = thread([&]() { svr.listen_after_bind(); });
  19333. auto se = detail::scope_exit([&] {
  19334. svr.stop();
  19335. t.join();
  19336. ASSERT_FALSE(svr.is_running());
  19337. });
  19338. svr.wait_until_ready();
  19339. // Empty first field line, then a real one
  19340. std::string raw_req = "GET / HTTP/1.1\r\n"
  19341. "Host: localhost\r\n"
  19342. "Accept:\r\n"
  19343. "Accept: application/json\r\n"
  19344. "Connection: close\r\n"
  19345. "\r\n";
  19346. std::string out;
  19347. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  19348. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  19349. ASSERT_EQ(1U, observed_types.size());
  19350. EXPECT_EQ("application/json", observed_types[0]);
  19351. }
  19352. // The skip in get_combined_header_value() is what keeps an empty field line
  19353. // from contributing a bare comma. Only a trailing empty field line exercises
  19354. // it: a leading one is already covered by the "combined is still empty" check,
  19355. // and parse_accept_header() now ignores the empty element either way, so the
  19356. // request-level test above can no longer tell the two apart.
  19357. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  19358. Headers headers;
  19359. headers.emplace("Accept", "text/html");
  19360. headers.emplace("Accept", "");
  19361. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  19362. headers.clear();
  19363. headers.emplace("Accept", "");
  19364. headers.emplace("Accept", "application/json");
  19365. EXPECT_EQ("application/json",
  19366. detail::get_combined_header_value(headers, "Accept"));
  19367. }
  19368. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19369. // An encoding offered on a later Accept-Encoding field line is still offered.
  19370. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  19371. Server svr;
  19372. svr.Get("/", [](const Request & /*req*/, Response &res) {
  19373. res.set_content(std::string(1024, 'x'), "text/plain");
  19374. });
  19375. auto port = svr.bind_to_any_port(HOST);
  19376. thread t = thread([&]() { svr.listen_after_bind(); });
  19377. auto se = detail::scope_exit([&] {
  19378. svr.stop();
  19379. t.join();
  19380. ASSERT_FALSE(svr.is_running());
  19381. });
  19382. svr.wait_until_ready();
  19383. Client cli(HOST, port);
  19384. cli.set_decompress(false);
  19385. Headers headers;
  19386. headers.emplace("Accept-Encoding", "identity");
  19387. headers.emplace("Accept-Encoding", "gzip");
  19388. auto res = cli.Get("/", headers);
  19389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19390. EXPECT_EQ(StatusCode::OK_200, res->status);
  19391. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  19392. }
  19393. #endif
  19394. // RFC 9112 6.3: whatever follows a request with neither Content-Length nor
  19395. // Transfer-Encoding is not its body.
  19396. TEST(ServerRequestParsingTest, BytesAfterUnframedRequestAreNotItsBody) {
  19397. Server svr;
  19398. svr.set_payload_max_length(8);
  19399. svr.Post("/test", [](const Request &, Response &res) {
  19400. res.set_content("ok", "text/plain");
  19401. });
  19402. auto port = svr.bind_to_any_port(HOST);
  19403. ASSERT_GT(port, 0);
  19404. thread t = thread([&] { svr.listen_after_bind(); });
  19405. auto se = detail::scope_exit([&] {
  19406. svr.stop();
  19407. t.join();
  19408. ASSERT_FALSE(svr.is_running());
  19409. });
  19410. svr.wait_until_ready();
  19411. std::string resp;
  19412. ASSERT_TRUE(send_request(1,
  19413. "POST /test HTTP/1.1\r\n"
  19414. "Host: localhost\r\n"
  19415. "Connection: close\r\n"
  19416. "\r\n" +
  19417. std::string(16, 'X'),
  19418. &resp, port));
  19419. EXPECT_EQ("HTTP/1.1 200 OK", resp.substr(0, resp.find("\r\n")));
  19420. }
  19421. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  19422. Server svr;
  19423. svr.Post("/post", [&](const Request &req, Response &res) {
  19424. res.set_content(req.body, "text/plain");
  19425. });
  19426. svr.Put("/put", [&](const Request &req, Response &res) {
  19427. res.set_content(req.body, "text/plain");
  19428. });
  19429. svr.Patch("/patch", [&](const Request &req, Response &res) {
  19430. res.set_content(req.body, "text/plain");
  19431. });
  19432. svr.Delete("/delete", [&](const Request &req, Response &res) {
  19433. res.set_content(req.body, "text/plain");
  19434. });
  19435. thread t = thread([&]() { svr.listen(HOST, PORT); });
  19436. auto se = detail::scope_exit([&] {
  19437. svr.stop();
  19438. t.join();
  19439. ASSERT_FALSE(svr.is_running());
  19440. });
  19441. svr.wait_until_ready();
  19442. std::string resp;
  19443. // POST without Content-Length
  19444. ASSERT_TRUE(send_request(5,
  19445. "POST /post HTTP/1.1\r\n"
  19446. "Host: localhost\r\n"
  19447. "Connection: close\r\n"
  19448. "\r\n",
  19449. &resp));
  19450. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19451. // PUT without Content-Length
  19452. resp.clear();
  19453. ASSERT_TRUE(send_request(5,
  19454. "PUT /put HTTP/1.1\r\n"
  19455. "Host: localhost\r\n"
  19456. "Connection: close\r\n"
  19457. "\r\n",
  19458. &resp));
  19459. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19460. // PATCH without Content-Length
  19461. resp.clear();
  19462. ASSERT_TRUE(send_request(5,
  19463. "PATCH /patch HTTP/1.1\r\n"
  19464. "Host: localhost\r\n"
  19465. "Connection: close\r\n"
  19466. "\r\n",
  19467. &resp));
  19468. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19469. // DELETE without Content-Length
  19470. resp.clear();
  19471. ASSERT_TRUE(send_request(5,
  19472. "DELETE /delete HTTP/1.1\r\n"
  19473. "Host: localhost\r\n"
  19474. "Connection: close\r\n"
  19475. "\r\n",
  19476. &resp));
  19477. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  19478. }
  19479. //==============================================================================
  19480. // open_stream() Tests
  19481. //==============================================================================
  19482. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  19483. std::string result;
  19484. char buf[8192];
  19485. ssize_t n;
  19486. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  19487. result.append(buf, static_cast<size_t>(n));
  19488. }
  19489. return result;
  19490. }
  19491. // Mock stream for unit tests
  19492. class MockStream : public Stream {
  19493. public:
  19494. std::string data;
  19495. size_t pos = 0;
  19496. ssize_t error_after = -1; // -1 = no error
  19497. explicit MockStream(const std::string &d, ssize_t err = -1)
  19498. : data(d), error_after(err) {}
  19499. bool is_readable() const override { return true; }
  19500. bool wait_readable() const override { return true; }
  19501. bool wait_writable() const override { return true; }
  19502. ssize_t read(char *ptr, size_t size) override {
  19503. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  19504. if (pos >= data.size()) return 0;
  19505. size_t limit =
  19506. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  19507. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  19508. std::memcpy(ptr, data.data() + pos, to_read);
  19509. pos += to_read;
  19510. return static_cast<ssize_t>(to_read);
  19511. }
  19512. ssize_t write(const char *, size_t) override { return -1; }
  19513. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  19514. ip = "127.0.0.1";
  19515. port = 0;
  19516. }
  19517. void get_local_ip_and_port(std::string &ip, int &port) const override {
  19518. ip = "127.0.0.1";
  19519. port = 0;
  19520. }
  19521. socket_t socket() const override { return INVALID_SOCKET; }
  19522. time_t duration() const override { return 0; }
  19523. };
  19524. TEST(StreamHandleTest, Basic) {
  19525. ClientImpl::StreamHandle handle;
  19526. EXPECT_FALSE(handle.is_valid());
  19527. handle.response = detail::make_unique<Response>();
  19528. handle.error = Error::Connection;
  19529. EXPECT_FALSE(handle.is_valid());
  19530. handle.error = Error::Success;
  19531. EXPECT_TRUE(handle.is_valid());
  19532. }
  19533. TEST(BodyReaderTest, Basic) {
  19534. MockStream stream("Hello, World!");
  19535. detail::BodyReader reader;
  19536. reader.stream = &stream;
  19537. reader.content_length = 13;
  19538. char buf[32];
  19539. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  19540. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  19541. EXPECT_TRUE(reader.eof);
  19542. }
  19543. TEST(BodyReaderTest, NoStream) {
  19544. detail::BodyReader reader;
  19545. char buf[32];
  19546. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19547. EXPECT_EQ(Error::Connection, reader.last_error);
  19548. }
  19549. TEST(BodyReaderTest, Error) {
  19550. MockStream stream("Hello, World!", 5);
  19551. detail::BodyReader reader;
  19552. reader.stream = &stream;
  19553. reader.content_length = 13;
  19554. char buf[32];
  19555. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  19556. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  19557. EXPECT_EQ(Error::Read, reader.last_error);
  19558. }
  19559. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  19560. // Mock-based StreamHandle tests relying on private internals are removed.
  19561. class OpenStreamTest : public ::testing::Test {
  19562. protected:
  19563. void SetUp() override {
  19564. svr_.Get("/hello", [](const Request &, Response &res) {
  19565. res.set_content("Hello World!", "text/plain");
  19566. });
  19567. svr_.Get("/large", [](const Request &, Response &res) {
  19568. res.set_content(std::string(10000, 'X'), "text/plain");
  19569. });
  19570. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  19571. res.set_content("Hello World!", "image/jpeg");
  19572. res.set_header("Content-Encoding", "UTF-8");
  19573. });
  19574. svr_.Get("/chunked", [](const Request &, Response &res) {
  19575. res.set_chunked_content_provider("text/plain",
  19576. [](size_t offset, DataSink &sink) {
  19577. if (offset < 15) {
  19578. sink.write("chunk", 5);
  19579. return true;
  19580. }
  19581. sink.done();
  19582. return true;
  19583. });
  19584. });
  19585. svr_.Get("/compressible", [](const Request &, Response &res) {
  19586. res.set_chunked_content_provider("text/plain", [](size_t offset,
  19587. DataSink &sink) {
  19588. if (offset < 100 * 1024) {
  19589. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  19590. sink.write(chunk.data(), chunk.size());
  19591. return true;
  19592. }
  19593. sink.done();
  19594. return true;
  19595. });
  19596. });
  19597. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  19598. [](const Request & /*req*/, Response &res) {
  19599. auto i = new int(0);
  19600. res.set_header("Trailer", "Content-Length, X-Allowed");
  19601. res.set_chunked_content_provider(
  19602. "text/plain",
  19603. [i](size_t /*offset*/, DataSink &sink) {
  19604. switch (*i) {
  19605. case 0: sink.os << "123"; break;
  19606. case 1: sink.os << "456"; break;
  19607. case 2: sink.os << "789"; break;
  19608. case 3: {
  19609. sink.done_with_trailer(
  19610. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  19611. } break;
  19612. }
  19613. (*i)++;
  19614. return true;
  19615. },
  19616. [i](bool success) {
  19617. EXPECT_TRUE(success);
  19618. delete i;
  19619. });
  19620. });
  19621. // Echo headers endpoint for header-related tests
  19622. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  19623. std::string body;
  19624. for (const auto &h : req.headers) {
  19625. body.append(h.first);
  19626. body.push_back(':');
  19627. body.append(h.second);
  19628. body.push_back('\n');
  19629. }
  19630. res.set_content(body, "text/plain");
  19631. });
  19632. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  19633. std::string body;
  19634. for (const auto &h : req.headers) {
  19635. body.append(h.first);
  19636. body.push_back(':');
  19637. body.append(h.second);
  19638. body.push_back('\n');
  19639. }
  19640. res.set_content(body, "text/plain");
  19641. });
  19642. port_ = svr_.bind_to_any_port("127.0.0.1");
  19643. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  19644. svr_.wait_until_ready();
  19645. }
  19646. void TearDown() override {
  19647. svr_.stop();
  19648. if (thread_.joinable()) thread_.join();
  19649. }
  19650. Server svr_;
  19651. std::thread thread_;
  19652. int port_ = 0;
  19653. };
  19654. TEST_F(OpenStreamTest, Basic) {
  19655. Client cli("127.0.0.1", port_);
  19656. auto handle = cli.open_stream("GET", "/hello");
  19657. EXPECT_TRUE(handle.is_valid());
  19658. EXPECT_EQ("Hello World!", read_all(handle));
  19659. }
  19660. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  19661. Client cli("127.0.0.1", port_);
  19662. auto handle = cli.open_stream("GET", "/unknown-encoding");
  19663. ASSERT_TRUE(handle.is_valid());
  19664. EXPECT_EQ("Hello World!", read_all(handle));
  19665. }
  19666. TEST_F(OpenStreamTest, SmallBuffer) {
  19667. Client cli("127.0.0.1", port_);
  19668. auto handle = cli.open_stream("GET", "/hello");
  19669. std::string result;
  19670. char buf[4];
  19671. ssize_t n;
  19672. while ((n = handle.read(buf, sizeof(buf))) > 0)
  19673. result.append(buf, static_cast<size_t>(n));
  19674. EXPECT_EQ("Hello World!", result);
  19675. }
  19676. TEST_F(OpenStreamTest, DefaultHeaders) {
  19677. Client cli("127.0.0.1", port_);
  19678. // open_stream GET should include Host, User-Agent and Accept-Encoding
  19679. {
  19680. auto handle = cli.open_stream("GET", "/echo-headers");
  19681. ASSERT_TRUE(handle.is_valid());
  19682. auto body = read_all(handle);
  19683. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  19684. std::string::npos);
  19685. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  19686. std::string::npos);
  19687. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  19688. }
  19689. // open_stream POST with body and no explicit content_type should NOT add
  19690. // text/plain Content-Type (behavior differs from non-streaming path), but
  19691. // should include Content-Length
  19692. {
  19693. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  19694. ASSERT_TRUE(handle.is_valid());
  19695. auto body = read_all(handle);
  19696. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  19697. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  19698. }
  19699. // open_stream POST with explicit Content-Type should preserve it
  19700. {
  19701. auto handle = cli.open_stream("POST", "/echo-headers", {},
  19702. {{"Content-Type", "application/custom"}},
  19703. "{}", "application/custom");
  19704. ASSERT_TRUE(handle.is_valid());
  19705. auto body = read_all(handle);
  19706. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  19707. }
  19708. // User-specified User-Agent must not be overwritten for stream API
  19709. {
  19710. auto handle = cli.open_stream("GET", "/echo-headers", {},
  19711. {{"User-Agent", "MyAgent/1.2"}});
  19712. ASSERT_TRUE(handle.is_valid());
  19713. auto body = read_all(handle);
  19714. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  19715. }
  19716. }
  19717. TEST_F(OpenStreamTest, Large) {
  19718. Client cli("127.0.0.1", port_);
  19719. auto handle = cli.open_stream("GET", "/large");
  19720. EXPECT_EQ(10000u, read_all(handle).size());
  19721. }
  19722. TEST_F(OpenStreamTest, ConnectionError) {
  19723. Client cli("127.0.0.1", 9999);
  19724. auto handle = cli.open_stream("GET", "/hello");
  19725. EXPECT_FALSE(handle.is_valid());
  19726. }
  19727. TEST_F(OpenStreamTest, Chunked) {
  19728. Client cli("127.0.0.1", port_);
  19729. auto handle = cli.open_stream("GET", "/chunked");
  19730. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  19731. "Transfer-Encoding") == "chunked");
  19732. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  19733. }
  19734. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  19735. Client cli("127.0.0.1", port_);
  19736. auto handle =
  19737. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  19738. ASSERT_TRUE(handle.is_valid());
  19739. // Consume body to allow trailers to be received/parsed
  19740. auto body = read_all(handle);
  19741. // Explicitly parse trailers (ensure trailers are available for assertion)
  19742. handle.parse_trailers_if_needed();
  19743. EXPECT_EQ(std::string("123456789"), body);
  19744. // The response should include a Trailer header declaring both names
  19745. ASSERT_TRUE(handle.response);
  19746. EXPECT_TRUE(handle.response->has_header("Trailer"));
  19747. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  19748. handle.response->get_header_value("Trailer"));
  19749. // Prohibited trailer must not be present
  19750. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  19751. // Allowed trailer should be present
  19752. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  19753. EXPECT_EQ(std::string("yes"),
  19754. handle.response->get_trailer_value("X-Allowed"));
  19755. // Verify trailers are NOT present as regular headers
  19756. EXPECT_EQ(std::string(""),
  19757. handle.response->get_header_value("Content-Length"));
  19758. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  19759. }
  19760. // Accepts one connection on an OS-assigned port, which it hands over through
  19761. // port_promise, reads the request head and sends back response. after_send,
  19762. // if given, runs on the connection before it is closed.
  19763. static std::thread
  19764. serve_single_response(std::promise<int> &port_promise,
  19765. const std::string &response,
  19766. std::function<void(socket_t)> after_send = nullptr) {
  19767. return std::thread([&port_promise, response, after_send] {
  19768. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  19769. default_socket_options(srv);
  19770. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  19771. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  19772. sockaddr_in addr{};
  19773. addr.sin_family = AF_INET;
  19774. addr.sin_port = htons(0); // Let OS assign a free port
  19775. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  19776. int opt = 1;
  19777. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  19778. #ifdef _WIN32
  19779. reinterpret_cast<const char *>(&opt),
  19780. #else
  19781. &opt,
  19782. #endif
  19783. sizeof(opt));
  19784. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  19785. ::listen(srv, 1) != 0) {
  19786. port_promise.set_value(-1);
  19787. detail::close_socket(srv);
  19788. return;
  19789. }
  19790. socklen_t addr_len = sizeof(addr);
  19791. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  19792. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  19793. sockaddr_in cli_addr{};
  19794. socklen_t cli_len = sizeof(cli_addr);
  19795. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  19796. if (cli != INVALID_SOCKET) {
  19797. // Read the complete HTTP request (until the blank line that terminates
  19798. // headers) before sending the response. If the server closes the socket
  19799. // while the client's request data is still unread in the kernel receive
  19800. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  19801. // connection on both sides: it discards the client's receive buffer
  19802. // (which already holds our response) and causes any in-progress write on
  19803. // the client to fail with ECONNRESET. Reading all request data first
  19804. // ensures close() emits a graceful FIN.
  19805. {
  19806. char rbuf[256];
  19807. std::string req;
  19808. while (req.find("\r\n\r\n") == std::string::npos) {
  19809. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  19810. if (n <= 0) { break; }
  19811. req.append(rbuf, static_cast<size_t>(n));
  19812. }
  19813. }
  19814. ::send(cli,
  19815. #ifdef _WIN32
  19816. static_cast<const char *>(response.c_str()),
  19817. static_cast<int>(response.size()),
  19818. #else
  19819. response.c_str(), response.size(),
  19820. #endif
  19821. 0);
  19822. if (after_send) { after_send(cli); }
  19823. detail::close_socket(cli);
  19824. }
  19825. detail::close_socket(srv);
  19826. });
  19827. }
  19828. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  19829. #ifndef _WIN32
  19830. signal(SIGPIPE, SIG_IGN);
  19831. #endif
  19832. std::promise<int> port_promise;
  19833. auto port_future = port_promise.get_future();
  19834. auto server_thread =
  19835. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  19836. "Content-Type: text/plain\r\n"
  19837. "Content-Length: not-a-number\r\n"
  19838. "Connection: close\r\n"
  19839. "\r\n"
  19840. "hello");
  19841. auto port = port_future.get();
  19842. ASSERT_GT(port, 0);
  19843. Client cli("127.0.0.1", port);
  19844. auto handle = cli.open_stream("GET", "/");
  19845. EXPECT_FALSE(handle.is_valid());
  19846. server_thread.join();
  19847. }
  19848. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  19849. #ifndef _WIN32
  19850. signal(SIGPIPE, SIG_IGN);
  19851. #endif
  19852. std::promise<int> port_promise;
  19853. auto port_future = port_promise.get_future();
  19854. auto server_thread = serve_single_response(
  19855. port_promise, "HTTP/1.1 200 OK\r\n"
  19856. "Content-Type: text/plain\r\n"
  19857. "Content-Length: 99999999999999999999999999\r\n"
  19858. "Connection: close\r\n"
  19859. "\r\n"
  19860. "hello");
  19861. auto port = port_future.get();
  19862. ASSERT_GT(port, 0);
  19863. // Historically std::stoull would throw std::out_of_range here and crash
  19864. // the process, then parsing silently clamped to a bogus framing length and
  19865. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  19866. // so the stream fails to open, matching the not-a-number case above. The
  19867. // process still must NOT terminate.
  19868. Client cli("127.0.0.1", port);
  19869. auto handle = cli.open_stream("GET", "/");
  19870. EXPECT_FALSE(handle.is_valid());
  19871. server_thread.join();
  19872. }
  19873. // Serves `response` to the single request `fn` makes with a fresh client.
  19874. template <typename Fn>
  19875. static void with_single_response(const std::string &response, Fn fn) {
  19876. #ifndef _WIN32
  19877. signal(SIGPIPE, SIG_IGN);
  19878. #endif
  19879. std::promise<int> port_promise;
  19880. auto port_future = port_promise.get_future();
  19881. auto server_thread = serve_single_response(port_promise, response);
  19882. auto se = detail::scope_exit([&] { server_thread.join(); });
  19883. auto port = port_future.get();
  19884. ASSERT_GT(port, 0);
  19885. Client cli("127.0.0.1", port);
  19886. fn(cli);
  19887. }
  19888. TEST(StreamBodyEndTest, BodyEndingAtConnectionClose) {
  19889. // Neither Content-Length nor chunked: the body ends at the close
  19890. const char *close_delimited = "HTTP/1.1 200 OK\r\n"
  19891. "Connection: close\r\n"
  19892. "\r\n"
  19893. "hello";
  19894. with_single_response(close_delimited, [](Client &cli) {
  19895. auto handle = cli.open_stream("GET", "/");
  19896. ASSERT_TRUE(handle.is_valid());
  19897. EXPECT_EQ("hello", read_all(handle));
  19898. EXPECT_FALSE(handle.has_read_error());
  19899. });
  19900. // A close before the end of the Content-Length is still an error
  19901. const char *short_content_length = "HTTP/1.1 200 OK\r\n"
  19902. "Content-Length: 10\r\n"
  19903. "\r\n"
  19904. "hello";
  19905. with_single_response(short_content_length, [](Client &cli) {
  19906. auto handle = cli.open_stream("GET", "/");
  19907. ASSERT_TRUE(handle.is_valid());
  19908. read_all(handle);
  19909. EXPECT_EQ(Error::ConnectionClosed, handle.get_read_error());
  19910. });
  19911. // So is a close before the last chunk
  19912. const char *short_chunked = "HTTP/1.1 200 OK\r\n"
  19913. "Transfer-Encoding: chunked\r\n"
  19914. "\r\n"
  19915. "5\r\nhello\r\n";
  19916. with_single_response(short_chunked, [](Client &cli) {
  19917. auto handle = cli.open_stream("GET", "/");
  19918. ASSERT_TRUE(handle.is_valid());
  19919. read_all(handle);
  19920. EXPECT_TRUE(handle.has_read_error());
  19921. });
  19922. }
  19923. TEST(InterimResponseTest, SkippedWithTheirHeaderFields) {
  19924. const char *responses[] = {
  19925. "HTTP/1.1 103 Early Hints\r\n"
  19926. "Link: </style.css>; rel=preload\r\n"
  19927. "\r\n"
  19928. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19929. "HTTP/1.1 100 Continue\r\n"
  19930. "X-Note: interim\r\n"
  19931. "\r\n"
  19932. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok",
  19933. };
  19934. for (auto response : responses) {
  19935. with_single_response(response, [](Client &cli) {
  19936. auto res = cli.Get("/");
  19937. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19938. EXPECT_EQ(StatusCode::OK_200, res->status);
  19939. EXPECT_EQ("ok", res->body);
  19940. });
  19941. }
  19942. }
  19943. TEST(InterimResponseTest, OnlySoManyAreSkipped) {
  19944. const std::string interim = "HTTP/1.1 102 Processing\r\n\r\n";
  19945. const std::string final_response =
  19946. "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  19947. std::string interims;
  19948. for (auto i = 0; i < CPPHTTPLIB_INTERIM_RESPONSE_MAX_COUNT; i++) {
  19949. interims += interim;
  19950. }
  19951. with_single_response(interims + final_response, [](Client &cli) {
  19952. auto res = cli.Get("/");
  19953. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19954. EXPECT_EQ("ok", res->body);
  19955. });
  19956. with_single_response(interims + interim + final_response, [](Client &cli) {
  19957. auto res = cli.Get("/");
  19958. ASSERT_FALSE(res);
  19959. EXPECT_EQ(Error::Read, res.error());
  19960. });
  19961. }
  19962. TEST(ExpectContinueTest, EarlyFinalResponseClosesConnection) {
  19963. #ifndef _WIN32
  19964. signal(SIGPIPE, SIG_IGN);
  19965. #endif
  19966. // The server answers the head without asking for the body. Bytes it then
  19967. // reads on the connection would be taken for the body the request declared.
  19968. auto closed_by_client = false;
  19969. std::promise<int> port_promise;
  19970. auto server_thread = serve_single_response(
  19971. port_promise, "HTTP/1.1 401 Unauthorized\r\nContent-Length: 0\r\n\r\n",
  19972. [&](socket_t sock) {
  19973. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  19974. char buf[256];
  19975. closed_by_client = ::recv(sock, buf, sizeof(buf), 0) == 0;
  19976. });
  19977. Client cli("127.0.0.1", port_promise.get_future().get());
  19978. cli.set_keep_alive(true);
  19979. cli.set_read_timeout(1, 0);
  19980. // Long enough for the client to send Expect: 100-continue.
  19981. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19982. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19983. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  19984. cli.Get("/second");
  19985. server_thread.join();
  19986. EXPECT_TRUE(closed_by_client);
  19987. }
  19988. TEST(InterimResponseTest, SkippedWhileWaitingForContinue) {
  19989. // Long enough for the client to send Expect: 100-continue
  19990. with_single_response(
  19991. "HTTP/1.1 103 Early Hints\r\n"
  19992. "Link: </style.css>; rel=preload\r\n"
  19993. "\r\n"
  19994. "HTTP/1.1 401 Unauthorized\r\n"
  19995. "Content-Length: 0\r\n\r\n",
  19996. [](Client &cli) {
  19997. cli.set_read_timeout(2, 0);
  19998. auto res = cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  19999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20000. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20001. });
  20002. }
  20003. #ifdef CPPHTTPLIB_SSL_ENABLED
  20004. TEST(ExpectContinueTest, AuthRetryAfterEarlyResponseUsesANewConnection) {
  20005. #ifndef _WIN32
  20006. signal(SIGPIPE, SIG_IGN);
  20007. #endif
  20008. auto reused = false;
  20009. std::promise<int> port_promise;
  20010. auto server_thread = serve_single_response(
  20011. port_promise,
  20012. "HTTP/1.1 401 Unauthorized\r\n"
  20013. "WWW-Authenticate: Digest realm=\"r\", nonce=\"n\", qop=\"auth\"\r\n"
  20014. "Content-Length: 0\r\n\r\n",
  20015. [&](socket_t sock) {
  20016. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 3, 0);
  20017. char buf[256];
  20018. reused = ::recv(sock, buf, sizeof(buf), 0) > 0;
  20019. });
  20020. Client cli("127.0.0.1", port_promise.get_future().get());
  20021. cli.set_keep_alive(true);
  20022. cli.set_digest_auth("user", "pass");
  20023. cli.set_read_timeout(1, 0);
  20024. cli.Post("/upload", std::string(2048, 'B'), "text/plain");
  20025. server_thread.join();
  20026. EXPECT_FALSE(reused);
  20027. }
  20028. TEST(ProxyConnectTest, OnlyAProxyAuthChallengeIsPassedOn) {
  20029. // Any other answer to CONNECT would read as the origin's response.
  20030. struct {
  20031. const char *response;
  20032. bool passed_on;
  20033. } cases[] = {
  20034. {"HTTP/1.1 201 Created\r\n"
  20035. "Set-Cookie: session=from-proxy\r\n"
  20036. "Content-Length: 0\r\n\r\n",
  20037. false},
  20038. {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n", false},
  20039. {"HTTP/1.1 407 Proxy Authentication Required\r\n"
  20040. "Content-Length: 0\r\n\r\n",
  20041. true},
  20042. };
  20043. for (const auto &c : cases) {
  20044. std::promise<int> port_promise;
  20045. auto server_thread = serve_single_response(port_promise, c.response);
  20046. SSLClient cli("example.com", 443);
  20047. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20048. auto res = cli.Get("/");
  20049. server_thread.join();
  20050. EXPECT_EQ(Error::ProxyConnection, res.error()) << c.response;
  20051. ASSERT_EQ(c.passed_on, static_cast<bool>(res)) << c.response;
  20052. if (res) {
  20053. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  20054. }
  20055. }
  20056. }
  20057. #endif
  20058. // Records the client's error logger calls as "error METHOD path", or
  20059. // "error null" for a call without a request
  20060. static ErrorLogger record_errors(std::vector<std::string> &log) {
  20061. return [&log](const Error &err, const Request *req) {
  20062. log.push_back(to_string(err) + " " +
  20063. (req ? req->method + " " + req->path : "null"));
  20064. };
  20065. }
  20066. // A failed request is reported once, with the request the caller made
  20067. TEST(ClientErrorLoggerTest, CancelIsLoggedOnce) {
  20068. Server svr;
  20069. svr.Get("/big", [](const Request &, Response &res) {
  20070. res.set_content(std::string(100000, 'b'), "text/plain");
  20071. });
  20072. auto port = svr.bind_to_any_port(HOST);
  20073. std::thread t([&]() { svr.listen_after_bind(); });
  20074. auto se = detail::scope_exit([&] {
  20075. svr.stop();
  20076. t.join();
  20077. });
  20078. svr.wait_until_ready();
  20079. Client cli(HOST, port);
  20080. std::vector<std::string> log;
  20081. cli.set_error_logger(record_errors(log));
  20082. std::vector<std::string> expected{to_string(Error::Canceled) + " GET /big"};
  20083. cli.Get("/big", [](const char *, size_t) { return false; });
  20084. EXPECT_EQ(expected, log);
  20085. log.clear();
  20086. cli.Get("/big", [](size_t, size_t) { return false; });
  20087. EXPECT_EQ(expected, log);
  20088. }
  20089. TEST(ClientErrorLoggerTest, RedirectFailureIsLoggedWithTheCallersRequest) {
  20090. // Fails while the body is read
  20091. auto broken = [](const Request &, Response &res) {
  20092. res.set_content_provider(10, "text/plain",
  20093. [](size_t, size_t, DataSink &) { return false; });
  20094. };
  20095. Server other;
  20096. other.Get("/broken", broken);
  20097. auto other_port = other.bind_to_any_port(HOST);
  20098. std::thread other_t([&]() { other.listen_after_bind(); });
  20099. auto other_se = detail::scope_exit([&] {
  20100. other.stop();
  20101. other_t.join();
  20102. });
  20103. other.wait_until_ready();
  20104. Server svr;
  20105. svr.Get("/broken", broken);
  20106. svr.Get("/same-origin",
  20107. [](const Request &, Response &res) { res.set_redirect("/broken"); });
  20108. svr.Get("/cross-origin", [&](const Request &, Response &res) {
  20109. res.set_redirect("http://" + std::string(HOST) + ":" +
  20110. std::to_string(other_port) + "/broken");
  20111. });
  20112. auto port = svr.bind_to_any_port(HOST);
  20113. std::thread t([&]() { svr.listen_after_bind(); });
  20114. auto se = detail::scope_exit([&] {
  20115. svr.stop();
  20116. t.join();
  20117. });
  20118. svr.wait_until_ready();
  20119. Client cli(HOST, port);
  20120. cli.set_follow_location(true);
  20121. std::vector<std::string> log;
  20122. cli.set_error_logger(record_errors(log));
  20123. for (auto path : {"/same-origin", "/cross-origin"}) {
  20124. log.clear();
  20125. auto res = cli.Get(path);
  20126. ASSERT_FALSE(res);
  20127. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET " + path},
  20128. log);
  20129. }
  20130. }
  20131. TEST(ClientErrorLoggerTest, StreamOpenFailureIsLoggedOnce) {
  20132. with_single_response("garbage\r\n\r\n", [](Client &cli) {
  20133. std::vector<std::string> log;
  20134. cli.set_error_logger(record_errors(log));
  20135. auto handle = cli.open_stream("GET", "/x");
  20136. EXPECT_FALSE(handle.is_valid());
  20137. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"},
  20138. log);
  20139. });
  20140. }
  20141. #ifdef CPPHTTPLIB_SSL_ENABLED
  20142. TEST(ClientErrorLoggerTest, TlsSetupFailureIsLoggedOnce) {
  20143. // Not a TLS server, so the handshake fails. It waits for a request line in
  20144. // the handshake bytes, so a short read timeout lets it close quickly.
  20145. Server svr;
  20146. svr.set_read_timeout(0, 100000);
  20147. svr.Get("/x", [](const Request &, Response &res) {
  20148. res.set_content("x", "text/plain");
  20149. });
  20150. auto port = svr.bind_to_any_port(HOST);
  20151. std::thread t([&]() { svr.listen_after_bind(); });
  20152. auto se = detail::scope_exit([&] {
  20153. svr.stop();
  20154. t.join();
  20155. });
  20156. svr.wait_until_ready();
  20157. std::vector<std::string> log;
  20158. SSLClient cli(HOST, port);
  20159. cli.enable_server_certificate_verification(false);
  20160. cli.set_error_logger(record_errors(log));
  20161. auto res = cli.Get("/x");
  20162. ASSERT_FALSE(res);
  20163. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20164. log.clear();
  20165. auto handle = cli.open_stream("GET", "/x");
  20166. EXPECT_FALSE(handle.is_valid());
  20167. EXPECT_EQ(std::vector<std::string>{to_string(handle.error) + " GET /x"}, log);
  20168. log.clear();
  20169. SSLClient no_ca(HOST, port);
  20170. no_ca.set_ca_cert_path("./no-such-ca.pem");
  20171. no_ca.set_error_logger(record_errors(log));
  20172. res = no_ca.Get("/x");
  20173. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  20174. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /x"}, log);
  20175. }
  20176. TEST(ClientErrorLoggerTest, ProxyConnectFailureIsLoggedOnce) {
  20177. #ifndef _WIN32
  20178. signal(SIGPIPE, SIG_IGN);
  20179. #endif
  20180. // Refused, answered with a challenge, or closed without an answer
  20181. for (auto response : {"HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n",
  20182. "HTTP/1.1 407 Proxy Authentication Required\r\n"
  20183. "Content-Length: 0\r\n\r\n",
  20184. ""}) {
  20185. std::promise<int> port_promise;
  20186. auto server_thread = serve_single_response(port_promise, response);
  20187. SSLClient cli("example.com", 443);
  20188. cli.set_proxy("127.0.0.1", port_promise.get_future().get());
  20189. std::vector<std::string> log;
  20190. cli.set_error_logger(record_errors(log));
  20191. auto res = cli.Get("/");
  20192. server_thread.join();
  20193. EXPECT_EQ(std::vector<std::string>{to_string(res.error()) + " GET /"}, log)
  20194. << response;
  20195. }
  20196. }
  20197. #endif
  20198. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  20199. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  20200. // the chunked coding and drop Content-Length, so a front-end that trusts
  20201. // Content-Length would disagree about where the body ends (response
  20202. // smuggling). The client must reject such a response.
  20203. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  20204. for (const char *te : {"chunked", "gzip, chunked"}) {
  20205. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  20206. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  20207. "\r\n" + "Connection: close\r\n" + "\r\n" +
  20208. "5\r\nhello\r\n0\r\n\r\n";
  20209. with_single_response(response, [&](Client &cli) {
  20210. auto res = cli.Get("/");
  20211. EXPECT_FALSE(static_cast<bool>(res)) << te;
  20212. EXPECT_EQ(Error::Read, res.error()) << te;
  20213. });
  20214. with_single_response(response, [&](Client &cli) {
  20215. auto handle = cli.open_stream("GET", "/");
  20216. EXPECT_FALSE(handle.is_valid()) << te;
  20217. EXPECT_EQ(Error::Read, handle.error) << te;
  20218. });
  20219. }
  20220. }
  20221. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  20222. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  20223. // closing the connection (unlike a request, which must be rejected).
  20224. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  20225. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20226. "Transfer-Encoding: chunked\r\n"
  20227. "Connection: close\r\n"
  20228. "\r\n"
  20229. "5\r\nhello\r\n0\r\n\r\n",
  20230. "HTTP/1.1 200 OK\r\n"
  20231. "Transfer-Encoding: gzip\r\n"
  20232. "Connection: close\r\n"
  20233. "\r\n"
  20234. "hello"}) {
  20235. with_single_response(response, [&](Client &cli) {
  20236. auto res = cli.Get("/");
  20237. ASSERT_TRUE(static_cast<bool>(res)) << response;
  20238. EXPECT_EQ("hello", res->body);
  20239. });
  20240. with_single_response(response, [&](Client &cli) {
  20241. auto handle = cli.open_stream("GET", "/");
  20242. ASSERT_TRUE(handle.is_valid()) << response;
  20243. EXPECT_EQ("hello", read_all(handle));
  20244. });
  20245. }
  20246. }
  20247. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  20248. // framing headers describe nothing to read and must not be rejected.
  20249. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  20250. const std::string framing = "Content-Length: 5\r\n"
  20251. "Transfer-Encoding: chunked\r\n"
  20252. "Connection: close\r\n"
  20253. "\r\n";
  20254. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20255. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  20256. });
  20257. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  20258. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  20259. });
  20260. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  20261. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  20262. with_single_response(response, [&](Client &cli) {
  20263. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  20264. });
  20265. with_single_response(response, [&](Client &cli) {
  20266. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  20267. });
  20268. }
  20269. }
  20270. // RFC 9112 6.3: a response to HEAD, and a 204 or 304 response, ends with its
  20271. // header section, so a stream opened on one has nothing to read, whatever
  20272. // framing or coding headers it carries.
  20273. TEST(ClientResponseSmugglingTest, BodylessResponseStreamEndsAtOnce) {
  20274. struct Case {
  20275. const char *method;
  20276. const char *status;
  20277. };
  20278. // A reader of the declared body reports an early close when nothing
  20279. // follows, and hands back what does.
  20280. struct Framing {
  20281. const char *headers;
  20282. const char *after;
  20283. };
  20284. for (const auto &c : {Case{"HEAD", "200 OK"}, Case{"GET", "204 No Content"},
  20285. Case{"GET", "304 Not Modified"}}) {
  20286. for (const auto &f :
  20287. {Framing{"Content-Length: 5\r\n", ""},
  20288. Framing{"Content-Length: 5\r\n", "hello"},
  20289. Framing{"Transfer-Encoding: chunked\r\n", ""},
  20290. Framing{"Transfer-Encoding: chunked\r\n", "5\r\nhello\r\n0\r\n\r\n"},
  20291. // Not decoded, so a build without Brotli opens it too
  20292. Framing{"Content-Encoding: br\r\n", ""}}) {
  20293. auto response = std::string("HTTP/1.1 ") + c.status + "\r\n" + f.headers +
  20294. "Connection: close\r\n"
  20295. "\r\n" +
  20296. f.after;
  20297. with_single_response(response, [&](Client &cli) {
  20298. auto handle = cli.open_stream(c.method, "/");
  20299. ASSERT_TRUE(handle.is_valid()) << c.method << ' ' << response;
  20300. EXPECT_EQ("", read_all(handle)) << c.method << ' ' << response;
  20301. EXPECT_FALSE(handle.has_read_error()) << c.method << ' ' << response;
  20302. });
  20303. }
  20304. }
  20305. }
  20306. // RFC 9112 6.1: Transfer-Encoding next to a Content-Length, or in an HTTP/1.0
  20307. // response, is faulty framing, so the connection is not reused after it.
  20308. TEST(ClientResponseSmugglingTest, FaultyTransferEncodingClosesConnection) {
  20309. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20310. "Content-Length: 0\r\n"
  20311. "Transfer-Encoding: chunked\r\n"
  20312. "\r\n"
  20313. "5\r\nhello\r\n0\r\n\r\n",
  20314. "HTTP/1.0 200 Connection established\r\n"
  20315. "Connection: keep-alive\r\n"
  20316. "Transfer-Encoding: chunked\r\n"
  20317. "\r\n"
  20318. "5\r\nhello\r\n0\r\n\r\n"}) {
  20319. with_single_response(response, [&](Client &cli) {
  20320. cli.set_keep_alive(true);
  20321. auto res = cli.Get("/");
  20322. ASSERT_TRUE(res) << response;
  20323. EXPECT_EQ("hello", res->body);
  20324. EXPECT_FALSE(cli.is_socket_open()) << response;
  20325. });
  20326. }
  20327. }
  20328. // A payload max length of 0 means no limit, however the body is framed.
  20329. TEST(PayloadMaxLengthZeroTest, ClientReadsChunkedAndUnframedResponse) {
  20330. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  20331. "Transfer-Encoding: chunked\r\n"
  20332. "\r\n"
  20333. "5\r\nhello\r\n0\r\n\r\n",
  20334. "HTTP/1.1 200 OK\r\n"
  20335. "Connection: close\r\n"
  20336. "\r\n"
  20337. "hello"}) {
  20338. with_single_response(response, [&](Client &cli) {
  20339. cli.set_payload_max_length(0);
  20340. auto res = cli.Get("/");
  20341. ASSERT_TRUE(res) << response;
  20342. EXPECT_EQ("hello", res->body) << response;
  20343. });
  20344. }
  20345. }
  20346. TEST(PayloadMaxLengthZeroTest, ServerReadsChunkedRequest) {
  20347. Server svr;
  20348. svr.set_payload_max_length(0);
  20349. svr.Post("/echo", [](const Request &req, Response &res) {
  20350. res.set_content(req.body, "text/plain");
  20351. });
  20352. auto port = svr.bind_to_any_port(HOST);
  20353. thread t = thread([&] { svr.listen_after_bind(); });
  20354. auto se = detail::scope_exit([&] {
  20355. svr.stop();
  20356. t.join();
  20357. ASSERT_FALSE(svr.is_running());
  20358. });
  20359. svr.wait_until_ready();
  20360. Client cli(HOST, port);
  20361. auto res = cli.Post(
  20362. "/echo",
  20363. [](size_t /*offset*/, DataSink &sink) {
  20364. sink.write("hello", 5);
  20365. sink.done();
  20366. return true;
  20367. },
  20368. "text/plain");
  20369. ASSERT_TRUE(res);
  20370. EXPECT_EQ(StatusCode::OK_200, res->status);
  20371. EXPECT_EQ("hello", res->body);
  20372. }
  20373. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20374. TEST_F(OpenStreamTest, Gzip) {
  20375. Client cli("127.0.0.1", port_);
  20376. auto handle = cli.open_stream("GET", "/compressible", {},
  20377. {{"Accept-Encoding", "gzip"}});
  20378. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20379. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20380. }
  20381. TEST_F(OpenStreamTest, TrailersWithGzip) {
  20382. Client cli("127.0.0.1", port_);
  20383. auto handle =
  20384. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer", {},
  20385. {{"Accept-Encoding", "gzip"}});
  20386. ASSERT_TRUE(handle.is_valid());
  20387. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  20388. EXPECT_EQ("123456789", read_all(handle));
  20389. EXPECT_EQ("yes", handle.response->get_trailer_value("X-Allowed"));
  20390. }
  20391. #endif
  20392. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20393. TEST_F(OpenStreamTest, Brotli) {
  20394. Client cli("127.0.0.1", port_);
  20395. auto handle =
  20396. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  20397. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  20398. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20399. }
  20400. #endif
  20401. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20402. TEST_F(OpenStreamTest, Zstd) {
  20403. Client cli("127.0.0.1", port_);
  20404. auto handle = cli.open_stream("GET", "/compressible", {},
  20405. {{"Accept-Encoding", "zstd"}});
  20406. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  20407. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  20408. }
  20409. #endif
  20410. #ifdef CPPHTTPLIB_SSL_ENABLED
  20411. class SSLOpenStreamTest : public ::testing::Test {
  20412. protected:
  20413. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  20414. void SetUp() override {
  20415. svr_.Get("/hello", [](const Request &, Response &res) {
  20416. res.set_content("Hello SSL World!", "text/plain");
  20417. });
  20418. svr_.Get("/chunked", [](const Request &, Response &res) {
  20419. res.set_chunked_content_provider("text/plain",
  20420. [](size_t offset, DataSink &sink) {
  20421. if (offset < 15) {
  20422. sink.write("chunk", 5);
  20423. return true;
  20424. }
  20425. sink.done();
  20426. return true;
  20427. });
  20428. });
  20429. svr_.Post("/echo", [](const Request &req, Response &res) {
  20430. res.set_content(req.body, req.get_header_value("Content-Type"));
  20431. });
  20432. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  20433. std::string body = req.body;
  20434. res.set_chunked_content_provider(
  20435. "text/plain", [body](size_t offset, DataSink &sink) {
  20436. if (offset < body.size()) {
  20437. sink.write(body.data() + offset, body.size() - offset);
  20438. }
  20439. sink.done();
  20440. return true;
  20441. });
  20442. });
  20443. port_ = svr_.bind_to_any_port("127.0.0.1");
  20444. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20445. svr_.wait_until_ready();
  20446. }
  20447. void TearDown() override {
  20448. svr_.stop();
  20449. if (thread_.joinable()) thread_.join();
  20450. }
  20451. SSLServer svr_;
  20452. std::thread thread_;
  20453. int port_ = 0;
  20454. };
  20455. TEST_F(SSLOpenStreamTest, Basic) {
  20456. SSLClient cli("127.0.0.1", port_);
  20457. cli.enable_server_certificate_verification(false);
  20458. auto handle = cli.open_stream("GET", "/hello");
  20459. ASSERT_TRUE(handle.is_valid());
  20460. EXPECT_EQ("Hello SSL World!", read_all(handle));
  20461. }
  20462. TEST_F(SSLOpenStreamTest, Chunked) {
  20463. SSLClient cli("127.0.0.1", port_);
  20464. cli.enable_server_certificate_verification(false);
  20465. auto handle = cli.open_stream("GET", "/chunked");
  20466. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20467. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  20468. "Transfer-Encoding") == "chunked");
  20469. auto body = read_all(handle);
  20470. EXPECT_EQ("chunkchunkchunk", body);
  20471. }
  20472. TEST_F(SSLOpenStreamTest, Post) {
  20473. SSLClient cli("127.0.0.1", port_);
  20474. cli.enable_server_certificate_verification(false);
  20475. auto handle =
  20476. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  20477. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  20478. EXPECT_EQ(200, handle.response->status);
  20479. auto body = read_all(handle);
  20480. EXPECT_EQ("Hello SSL POST", body);
  20481. }
  20482. TEST_F(SSLOpenStreamTest, PostChunked) {
  20483. SSLClient cli("127.0.0.1", port_);
  20484. cli.enable_server_certificate_verification(false);
  20485. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  20486. "Chunked SSL Data", "text/plain");
  20487. ASSERT_TRUE(handle.is_valid());
  20488. EXPECT_EQ(200, handle.response->status);
  20489. auto body = read_all(handle);
  20490. EXPECT_EQ("Chunked SSL Data", body);
  20491. }
  20492. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  20493. // Content-Length is terminated by the server closing the connection. When the
  20494. // SSL peer sends a close_notify after the body, the client must treat it as a
  20495. // clean EOF and return a successful response rather than an error.
  20496. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  20497. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20498. ASSERT_TRUE(svr.is_valid());
  20499. svr.set_keep_alive_max_count(1);
  20500. const std::string expected_body = "Hello from connection-close response!";
  20501. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  20502. res.set_content_provider("text/plain",
  20503. [&](size_t offset, DataSink &sink) -> bool {
  20504. if (offset < expected_body.size()) {
  20505. sink.write(expected_body.data() + offset,
  20506. expected_body.size() - offset);
  20507. }
  20508. sink.done();
  20509. return true;
  20510. });
  20511. });
  20512. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  20513. auto se = detail::scope_exit([&] {
  20514. svr.stop();
  20515. listen_thread.join();
  20516. ASSERT_FALSE(svr.is_running());
  20517. });
  20518. svr.wait_until_ready();
  20519. SSLClient cli(HOST, PORT);
  20520. cli.enable_server_certificate_verification(false);
  20521. auto res = cli.Get("/no-content-length");
  20522. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  20523. EXPECT_EQ(StatusCode::OK_200, res->status);
  20524. EXPECT_EQ(expected_body, res->body);
  20525. }
  20526. #endif // CPPHTTPLIB_SSL_ENABLED
  20527. //==============================================================================
  20528. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  20529. // results for various scenarios.
  20530. //==============================================================================
  20531. TEST(ParityTest, GetVsOpenStream) {
  20532. Server svr;
  20533. const std::string path = "/parity";
  20534. const std::string content = "Parity test content: hello world";
  20535. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20536. res.set_content(content, "text/plain");
  20537. });
  20538. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  20539. auto se = detail::scope_exit([&] {
  20540. svr.stop();
  20541. t.join();
  20542. ASSERT_FALSE(svr.is_running());
  20543. });
  20544. svr.wait_until_ready();
  20545. Client cli(HOST, PORT);
  20546. // Non-stream path
  20547. auto r1 = cli.Get(path);
  20548. ASSERT_TRUE(r1);
  20549. EXPECT_EQ(StatusCode::OK_200, r1->status);
  20550. // Stream path
  20551. auto h = cli.open_stream("GET", path);
  20552. ASSERT_TRUE(h.is_valid());
  20553. EXPECT_EQ(r1->body, read_all(h));
  20554. }
  20555. // Helper to compress data with provided compressor type T
  20556. template <typename Compressor>
  20557. static std::string compress_payload_for_parity(const std::string &in) {
  20558. std::string out;
  20559. Compressor compressor;
  20560. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  20561. [&](const char *data, size_t n) {
  20562. out.append(data, n);
  20563. return true;
  20564. });
  20565. EXPECT_TRUE(ok);
  20566. return out;
  20567. }
  20568. // Helper function for compression parity tests
  20569. template <typename Compressor>
  20570. static void test_compression_parity(const std::string &original,
  20571. const std::string &path,
  20572. const std::string &encoding) {
  20573. const std::string compressed =
  20574. compress_payload_for_parity<Compressor>(original);
  20575. Server svr;
  20576. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  20577. res.set_content(compressed, "application/octet-stream");
  20578. res.set_header("Content-Encoding", encoding);
  20579. });
  20580. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  20581. auto se = detail::scope_exit([&] {
  20582. svr.stop();
  20583. t.join();
  20584. ASSERT_FALSE(svr.is_running());
  20585. });
  20586. svr.wait_until_ready();
  20587. Client cli(HOST, PORT);
  20588. // Non-streaming
  20589. {
  20590. auto res = cli.Get(path);
  20591. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  20592. EXPECT_EQ(StatusCode::OK_200, res->status);
  20593. EXPECT_EQ(original, res->body);
  20594. }
  20595. // Streaming
  20596. {
  20597. auto h = cli.open_stream("GET", path);
  20598. ASSERT_TRUE(h.is_valid());
  20599. EXPECT_EQ(original, read_all(h));
  20600. }
  20601. }
  20602. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20603. TEST(ParityTest, Gzip) {
  20604. test_compression_parity<detail::gzip_compressor>(
  20605. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  20606. }
  20607. #endif
  20608. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  20609. TEST(ParityTest, Brotli) {
  20610. test_compression_parity<detail::brotli_compressor>(
  20611. "Hello, brotli parity test payload", "/parity-br", "br");
  20612. }
  20613. #endif
  20614. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  20615. TEST(ParityTest, Zstd) {
  20616. test_compression_parity<detail::zstd_compressor>(
  20617. "Zstandard parity test payload", "/parity-zstd", "zstd");
  20618. }
  20619. #endif
  20620. //==============================================================================
  20621. // New Stream API Tests
  20622. //==============================================================================
  20623. inline std::string read_body(httplib::stream::Result &result) {
  20624. std::string body;
  20625. while (result.next()) {
  20626. body.append(result.data(), result.size());
  20627. }
  20628. return body;
  20629. }
  20630. TEST(ClientConnectionTest, Basic) {
  20631. httplib::ClientConnection conn;
  20632. EXPECT_FALSE(conn.is_open());
  20633. conn.sock = 1;
  20634. EXPECT_TRUE(conn.is_open());
  20635. httplib::ClientConnection conn2(std::move(conn));
  20636. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  20637. conn2.sock = INVALID_SOCKET;
  20638. }
  20639. // Unified test server for all stream::* tests
  20640. class StreamApiTest : public ::testing::Test {
  20641. protected:
  20642. void SetUp() override {
  20643. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20644. res.set_content("Hello World!", "text/plain");
  20645. });
  20646. svr_.Get("/echo-params",
  20647. [](const httplib::Request &req, httplib::Response &res) {
  20648. std::string r;
  20649. for (const auto &p : req.params) {
  20650. if (!r.empty()) r += "&";
  20651. r += p.first + "=" + p.second;
  20652. }
  20653. res.set_content(r, "text/plain");
  20654. });
  20655. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20656. res.set_content(req.body, req.get_header_value("Content-Type"));
  20657. });
  20658. svr_.Post("/echo-headers",
  20659. [](const httplib::Request &req, httplib::Response &res) {
  20660. std::string r;
  20661. for (const auto &h : req.headers)
  20662. r += h.first + ": " + h.second + "\n";
  20663. res.set_content(r, "text/plain");
  20664. });
  20665. svr_.Post("/echo-params",
  20666. [](const httplib::Request &req, httplib::Response &res) {
  20667. std::string r = "params:";
  20668. for (const auto &p : req.params)
  20669. r += p.first + "=" + p.second + ";";
  20670. res.set_content(r + " body:" + req.body, "text/plain");
  20671. });
  20672. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  20673. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  20674. });
  20675. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20676. res.set_content("PUT:" + req.body, "text/plain");
  20677. });
  20678. svr_.Patch("/echo",
  20679. [](const httplib::Request &req, httplib::Response &res) {
  20680. res.set_content("PATCH:" + req.body, "text/plain");
  20681. });
  20682. svr_.Delete(
  20683. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  20684. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  20685. "text/plain");
  20686. });
  20687. svr_.Get("/head-test",
  20688. [](const httplib::Request &, httplib::Response &res) {
  20689. res.set_content("body for HEAD", "text/plain");
  20690. });
  20691. svr_.Options("/options",
  20692. [](const httplib::Request &, httplib::Response &res) {
  20693. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  20694. });
  20695. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  20696. svr_.wait_until_ready();
  20697. }
  20698. void TearDown() override {
  20699. svr_.stop();
  20700. if (thread_.joinable()) thread_.join();
  20701. }
  20702. httplib::Server svr_;
  20703. std::thread thread_;
  20704. };
  20705. // stream::Get tests
  20706. TEST_F(StreamApiTest, GetBasic) {
  20707. httplib::Client cli(HOST, PORT);
  20708. auto result = httplib::stream::Get(cli, "/hello");
  20709. ASSERT_TRUE(result.is_valid());
  20710. EXPECT_EQ(200, result.status());
  20711. EXPECT_EQ("Hello World!", read_body(result));
  20712. }
  20713. TEST_F(StreamApiTest, GetWithParams) {
  20714. httplib::Client cli(HOST, PORT);
  20715. httplib::Params params{{"foo", "bar"}};
  20716. auto result = httplib::stream::Get(cli, "/echo-params", params);
  20717. ASSERT_TRUE(result.is_valid());
  20718. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  20719. }
  20720. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  20721. TEST_F(StreamApiTest, GetCompressedWithNoPayloadLimit) {
  20722. httplib::Client cli(HOST, PORT);
  20723. cli.set_payload_max_length(0);
  20724. auto result = httplib::stream::Get(cli, "/hello");
  20725. ASSERT_TRUE(result.is_valid());
  20726. EXPECT_FALSE(result.get_header_value("Content-Encoding").empty());
  20727. EXPECT_EQ("Hello World!", read_body(result));
  20728. }
  20729. #endif
  20730. TEST_F(StreamApiTest, GetConnectionError) {
  20731. httplib::Client cli(HOST, 9999);
  20732. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  20733. }
  20734. TEST_F(StreamApiTest, Get404) {
  20735. httplib::Client cli(HOST, PORT);
  20736. auto result = httplib::stream::Get(cli, "/nonexistent");
  20737. EXPECT_TRUE(result.is_valid());
  20738. EXPECT_EQ(404, result.status());
  20739. }
  20740. // stream::Post tests
  20741. TEST_F(StreamApiTest, PostBasic) {
  20742. httplib::Client cli(HOST, PORT);
  20743. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  20744. "application/json");
  20745. ASSERT_TRUE(result.is_valid());
  20746. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  20747. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  20748. }
  20749. TEST_F(StreamApiTest, PostWithHeaders) {
  20750. httplib::Client cli(HOST, PORT);
  20751. httplib::Headers headers{{"X-Custom", "value"}};
  20752. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  20753. "text/plain");
  20754. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  20755. }
  20756. TEST_F(StreamApiTest, PostWithParams) {
  20757. httplib::Client cli(HOST, PORT);
  20758. httplib::Params params{{"k", "v"}};
  20759. auto result =
  20760. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  20761. auto body = read_body(result);
  20762. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  20763. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  20764. }
  20765. TEST_F(StreamApiTest, PostLarge) {
  20766. httplib::Client cli(HOST, PORT);
  20767. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  20768. size_t total = 0;
  20769. while (result.next()) {
  20770. total += result.size();
  20771. }
  20772. EXPECT_EQ(100u * 1024u, total);
  20773. }
  20774. // stream::Put/Patch tests
  20775. TEST_F(StreamApiTest, PutAndPatch) {
  20776. httplib::Client cli(HOST, PORT);
  20777. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  20778. EXPECT_EQ("PUT:test", read_body(put));
  20779. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  20780. EXPECT_EQ("PATCH:test", read_body(patch));
  20781. }
  20782. // stream::Delete tests
  20783. TEST_F(StreamApiTest, Delete) {
  20784. httplib::Client cli(HOST, PORT);
  20785. auto del1 = httplib::stream::Delete(cli, "/resource");
  20786. EXPECT_EQ("Deleted", read_body(del1));
  20787. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  20788. EXPECT_EQ("Deleted:data", read_body(del2));
  20789. }
  20790. // stream::Head/Options tests
  20791. TEST_F(StreamApiTest, HeadAndOptions) {
  20792. httplib::Client cli(HOST, PORT);
  20793. auto head = httplib::stream::Head(cli, "/head-test");
  20794. EXPECT_TRUE(head.is_valid());
  20795. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  20796. auto opts = httplib::stream::Options(cli, "/options");
  20797. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  20798. }
  20799. // SSL stream::* tests
  20800. #ifdef CPPHTTPLIB_SSL_ENABLED
  20801. class SSLStreamApiTest : public ::testing::Test {
  20802. protected:
  20803. void SetUp() override {
  20804. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  20805. res.set_content("Hello SSL!", "text/plain");
  20806. });
  20807. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  20808. res.set_content(req.body, "text/plain");
  20809. });
  20810. port_ = svr_.bind_to_any_port("127.0.0.1");
  20811. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  20812. svr_.wait_until_ready();
  20813. }
  20814. void TearDown() override {
  20815. svr_.stop();
  20816. if (thread_.joinable()) thread_.join();
  20817. }
  20818. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  20819. std::thread thread_;
  20820. int port_ = 0;
  20821. };
  20822. TEST_F(SSLStreamApiTest, GetAndPost) {
  20823. httplib::SSLClient cli("127.0.0.1", port_);
  20824. cli.enable_server_certificate_verification(false);
  20825. auto get = httplib::stream::Get(cli, "/hello");
  20826. EXPECT_EQ("Hello SSL!", read_body(get));
  20827. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  20828. EXPECT_EQ("test", read_body(post));
  20829. }
  20830. #endif
  20831. // Tests for Error::Timeout and Error::ConnectionClosed error types
  20832. // These errors are set in SocketStream/SSLSocketStream and propagated through
  20833. // BodyReader
  20834. TEST(ErrorHandlingTest, StreamReadTimeout) {
  20835. // Test that read timeout during streaming is detected
  20836. // Use a large content-length response where server delays mid-stream
  20837. Server svr;
  20838. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20839. // Send a large response with delay in the middle
  20840. res.set_content_provider(
  20841. 1000, // content_length
  20842. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  20843. if (offset < 100) {
  20844. // Send first 100 bytes immediately
  20845. std::string data(100, 'A');
  20846. sink.write(data.c_str(), data.size());
  20847. return true;
  20848. }
  20849. // Then delay longer than client timeout
  20850. std::this_thread::sleep_for(std::chrono::seconds(3));
  20851. std::string data(900, 'B');
  20852. sink.write(data.c_str(), data.size());
  20853. return true;
  20854. });
  20855. });
  20856. auto port = 8091;
  20857. std::thread t([&]() { svr.listen("localhost", port); });
  20858. svr.wait_until_ready();
  20859. Client cli("localhost", port);
  20860. cli.set_read_timeout(1, 0); // 1 second timeout
  20861. auto handle = cli.open_stream("GET", "/slow-stream");
  20862. ASSERT_TRUE(handle.is_valid());
  20863. char buf[256];
  20864. ssize_t total = 0;
  20865. ssize_t n;
  20866. bool got_error = false;
  20867. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20868. total += n;
  20869. }
  20870. if (n < 0) {
  20871. got_error = true;
  20872. // Should be timeout or read error
  20873. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20874. handle.get_read_error() == Error::Read)
  20875. << "Actual error: " << to_string(handle.get_read_error());
  20876. }
  20877. // Either we got an error, or we got less data than expected
  20878. EXPECT_TRUE(got_error || total < 1000)
  20879. << "Expected timeout but got all " << total << " bytes";
  20880. svr.stop();
  20881. t.join();
  20882. }
  20883. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  20884. // Test connection closed detection via BodyReader
  20885. Server svr;
  20886. std::atomic<bool> close_now{false};
  20887. svr.Get("/will-close", [&](const Request &, Response &res) {
  20888. res.set_content_provider(
  20889. 10000, // Large content_length that we won't fully send
  20890. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20891. if (offset < 100) {
  20892. std::string data(100, 'X');
  20893. sink.write(data.c_str(), data.size());
  20894. return true;
  20895. }
  20896. // Wait for signal then abort
  20897. while (!close_now) {
  20898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20899. }
  20900. return false; // Abort - server will close connection
  20901. });
  20902. });
  20903. auto port = 8092;
  20904. std::thread t([&]() { svr.listen("localhost", port); });
  20905. svr.wait_until_ready();
  20906. Client cli("localhost", port);
  20907. auto handle = cli.open_stream("GET", "/will-close");
  20908. ASSERT_TRUE(handle.is_valid());
  20909. char buf[256];
  20910. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  20911. EXPECT_GT(n, 0) << "First read should succeed";
  20912. // Signal server to close
  20913. close_now = true;
  20914. // Keep reading until error or EOF
  20915. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20916. // Keep reading
  20917. }
  20918. // Should get an error since content_length wasn't satisfied
  20919. if (n < 0) {
  20920. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  20921. handle.get_read_error() == Error::Read)
  20922. << "Actual error: " << to_string(handle.get_read_error());
  20923. }
  20924. svr.stop();
  20925. t.join();
  20926. }
  20927. #ifdef CPPHTTPLIB_SSL_ENABLED
  20928. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  20929. // Test that read timeout during SSL streaming is detected
  20930. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20931. svr.Get("/slow-stream", [](const Request &, Response &res) {
  20932. res.set_content_provider(
  20933. 1000, "text/plain",
  20934. [](size_t offset, size_t /*length*/, DataSink &sink) {
  20935. if (offset < 100) {
  20936. std::string data(100, 'A');
  20937. sink.write(data.c_str(), data.size());
  20938. return true;
  20939. }
  20940. std::this_thread::sleep_for(std::chrono::seconds(3));
  20941. std::string data(900, 'B');
  20942. sink.write(data.c_str(), data.size());
  20943. return true;
  20944. });
  20945. });
  20946. auto port = 8093;
  20947. std::thread t([&]() { svr.listen("localhost", port); });
  20948. svr.wait_until_ready();
  20949. SSLClient cli("localhost", port);
  20950. cli.enable_server_certificate_verification(false);
  20951. cli.set_read_timeout(1, 0); // 1 second timeout
  20952. auto handle = cli.open_stream("GET", "/slow-stream");
  20953. ASSERT_TRUE(handle.is_valid());
  20954. char buf[256];
  20955. ssize_t total = 0;
  20956. ssize_t n;
  20957. bool got_error = false;
  20958. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  20959. total += n;
  20960. }
  20961. if (n < 0) {
  20962. got_error = true;
  20963. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  20964. handle.get_read_error() == Error::Read)
  20965. << "Actual error: " << to_string(handle.get_read_error());
  20966. }
  20967. EXPECT_TRUE(got_error || total < 1000)
  20968. << "Expected timeout but got all " << total << " bytes";
  20969. svr.stop();
  20970. t.join();
  20971. }
  20972. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  20973. // Test SSL connection closed detection
  20974. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20975. std::atomic<bool> close_now{false};
  20976. svr.Get("/will-close", [&](const Request &, Response &res) {
  20977. res.set_content_provider(
  20978. 10000, "text/plain",
  20979. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  20980. if (offset < 100) {
  20981. std::string data(100, 'X');
  20982. sink.write(data.c_str(), data.size());
  20983. return true;
  20984. }
  20985. while (!close_now) {
  20986. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20987. }
  20988. return false;
  20989. });
  20990. });
  20991. auto port = 8094;
  20992. std::thread t([&]() { svr.listen("localhost", port); });
  20993. svr.wait_until_ready();
  20994. SSLClient cli("localhost", port);
  20995. cli.enable_server_certificate_verification(false);
  20996. auto handle = cli.open_stream("GET", "/will-close");
  20997. ASSERT_TRUE(handle.is_valid());
  20998. char buf[256];
  20999. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  21000. EXPECT_GT(n, 0);
  21001. // Signal server to close
  21002. close_now = true;
  21003. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  21004. // Keep reading
  21005. }
  21006. if (n < 0) {
  21007. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  21008. handle.get_read_error() == Error::Read)
  21009. << "Actual error: " << to_string(handle.get_read_error());
  21010. }
  21011. svr.stop();
  21012. t.join();
  21013. }
  21014. #endif
  21015. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  21016. using namespace httplib;
  21017. // Create a test file
  21018. const char *fname = "etag_testfile.txt";
  21019. const char *content = "etag-content";
  21020. {
  21021. std::ofstream ofs(fname);
  21022. ofs << content;
  21023. ASSERT_TRUE(ofs.good());
  21024. }
  21025. Server svr;
  21026. svr.set_mount_point("/static", ".");
  21027. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21028. svr.wait_until_ready();
  21029. Client cli(HOST, PORT);
  21030. // First request: should get 200 with ETag header
  21031. auto res1 = cli.Get("/static/etag_testfile.txt");
  21032. ASSERT_TRUE(res1);
  21033. ASSERT_EQ(200, res1->status);
  21034. ASSERT_TRUE(res1->has_header("ETag"));
  21035. std::string etag = res1->get_header_value("ETag");
  21036. EXPECT_FALSE(etag.empty());
  21037. // Verify ETag format: W/"hex-hex"
  21038. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  21039. EXPECT_EQ('W', etag[0]);
  21040. EXPECT_EQ('/', etag[1]);
  21041. EXPECT_EQ('"', etag[2]);
  21042. EXPECT_EQ('"', etag.back());
  21043. // Exact match: expect 304 Not Modified
  21044. Headers h2 = {{"If-None-Match", etag}};
  21045. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  21046. ASSERT_TRUE(res2);
  21047. EXPECT_EQ(304, res2->status);
  21048. // Wildcard match: expect 304 Not Modified
  21049. Headers h3 = {{"If-None-Match", "*"}};
  21050. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  21051. ASSERT_TRUE(res3);
  21052. EXPECT_EQ(304, res3->status);
  21053. // Non-matching ETag: expect 200
  21054. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  21055. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  21056. ASSERT_TRUE(res4);
  21057. EXPECT_EQ(200, res4->status);
  21058. // Multiple ETags with one matching: expect 304
  21059. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  21060. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  21061. ASSERT_TRUE(res5);
  21062. EXPECT_EQ(304, res5->status);
  21063. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  21064. // that equivalent to the single comma-separated list above, so the match on
  21065. // the second line must still be found.
  21066. Headers h6;
  21067. h6.emplace("If-None-Match", "W/\"other\"");
  21068. h6.emplace("If-None-Match", etag);
  21069. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  21070. ASSERT_TRUE(res6);
  21071. EXPECT_EQ(304, res6->status);
  21072. svr.stop();
  21073. t.join();
  21074. std::remove(fname);
  21075. }
  21076. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  21077. using namespace httplib;
  21078. Server svr;
  21079. svr.set_mount_point("/static", ".");
  21080. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21081. svr.wait_until_ready();
  21082. Client cli(HOST, PORT);
  21083. // Send If-None-Match: * to a non-existent file
  21084. Headers h = {{"If-None-Match", "*"}};
  21085. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  21086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21087. EXPECT_EQ(404, res->status);
  21088. svr.stop();
  21089. t.join();
  21090. }
  21091. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  21092. using namespace httplib;
  21093. // Create a test file
  21094. const char *fname = "etag_boundary_testfile.txt";
  21095. const char *content = "boundary-test";
  21096. {
  21097. std::ofstream ofs(fname);
  21098. ofs << content;
  21099. ASSERT_TRUE(ofs.good());
  21100. }
  21101. Server svr;
  21102. svr.set_mount_point("/static", ".");
  21103. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  21104. svr.wait_until_ready();
  21105. Client cli(HOST, PORT);
  21106. // Get the actual ETag
  21107. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  21108. ASSERT_TRUE(res1);
  21109. ASSERT_EQ(200, res1->status);
  21110. ASSERT_TRUE(res1->has_header("ETag"));
  21111. std::string etag = res1->get_header_value("ETag");
  21112. // Test 1: Very long ETag value (longer than actual ETag)
  21113. // Should NOT match and return 200 (not trigger out-of-bounds read)
  21114. Headers h1 = {{"If-None-Match", "W/"
  21115. "\"very-long-etag-value-that-is-much-longer-"
  21116. "than-the-actual-etag-value\""}};
  21117. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  21118. ASSERT_TRUE(res2);
  21119. EXPECT_EQ(200, res2->status); // Should not match
  21120. // Test 2: Long string followed by wildcard
  21121. // Should match on "*" and return 304 (without out-of-bounds read on the long
  21122. // string)
  21123. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  21124. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  21125. ASSERT_TRUE(res3);
  21126. EXPECT_EQ(304, res3->status); // Should match on "*"
  21127. // Test 3: Wildcard followed by long string
  21128. // Should match on "*" immediately and return 304
  21129. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  21130. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  21131. ASSERT_TRUE(res4);
  21132. EXPECT_EQ(304, res4->status); // Should match on "*"
  21133. // Test 4: Multiple long non-matching values
  21134. // Should NOT match and return 200 (test that all comparisons are safe)
  21135. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  21136. "W/\"second-long-non-matching-value\", "
  21137. "W/\"third-long-non-matching-value\""}};
  21138. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  21139. ASSERT_TRUE(res5);
  21140. EXPECT_EQ(200, res5->status); // Should not match
  21141. // Test 5: Single character that is not "*" (edge case)
  21142. Headers h5 = {{"If-None-Match", "X"}};
  21143. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  21144. ASSERT_TRUE(res6);
  21145. EXPECT_EQ(200, res6->status); // Should not match
  21146. svr.stop();
  21147. t.join();
  21148. std::remove(fname);
  21149. }
  21150. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  21151. using namespace httplib;
  21152. // Create a test file
  21153. const char *fname = "ims_testfile.txt";
  21154. const char *content = "if-modified-since-test";
  21155. {
  21156. std::ofstream ofs(fname);
  21157. ofs << content;
  21158. ASSERT_TRUE(ofs.good());
  21159. }
  21160. Server svr;
  21161. svr.set_mount_point("/static", ".");
  21162. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21163. svr.wait_until_ready();
  21164. Client cli(HOST, PORT);
  21165. // First request: should get 200 with Last-Modified header
  21166. auto res1 = cli.Get("/static/ims_testfile.txt");
  21167. ASSERT_TRUE(res1);
  21168. ASSERT_EQ(200, res1->status);
  21169. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21170. std::string last_modified = res1->get_header_value("Last-Modified");
  21171. EXPECT_FALSE(last_modified.empty());
  21172. // If-Modified-Since with same time: expect 304
  21173. Headers h2 = {{"If-Modified-Since", last_modified}};
  21174. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  21175. ASSERT_TRUE(res2);
  21176. EXPECT_EQ(304, res2->status);
  21177. // If-Modified-Since with future time: expect 304
  21178. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21179. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  21180. ASSERT_TRUE(res3);
  21181. EXPECT_EQ(304, res3->status);
  21182. // If-Modified-Since with past time: expect 200
  21183. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21184. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  21185. ASSERT_TRUE(res4);
  21186. EXPECT_EQ(200, res4->status);
  21187. // If-None-Match takes precedence over If-Modified-Since
  21188. // (send matching ETag with old If-Modified-Since -> should still be 304)
  21189. ASSERT_TRUE(res1->has_header("ETag"));
  21190. std::string etag = res1->get_header_value("ETag");
  21191. Headers h5 = {{"If-None-Match", etag},
  21192. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21193. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  21194. ASSERT_TRUE(res5);
  21195. EXPECT_EQ(304, res5->status);
  21196. svr.stop();
  21197. t.join();
  21198. std::remove(fname);
  21199. }
  21200. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  21201. using namespace httplib;
  21202. Server svr;
  21203. // Endpoint that returns compressible content
  21204. svr.Get("/compressible", [](const Request &, Response &res) {
  21205. // Return a large enough body to trigger compression
  21206. std::string body(1000, 'a');
  21207. res.set_content(body, "text/plain");
  21208. });
  21209. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21210. svr.wait_until_ready();
  21211. Client cli(HOST, PORT);
  21212. // Request with gzip support: should get Vary header when compressed
  21213. cli.set_compress(true);
  21214. auto res1 = cli.Get("/compressible");
  21215. ASSERT_TRUE(res1);
  21216. EXPECT_EQ(200, res1->status);
  21217. // If Content-Encoding is set, Vary should also be set
  21218. if (res1->has_header("Content-Encoding")) {
  21219. EXPECT_TRUE(res1->has_header("Vary"));
  21220. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  21221. }
  21222. // Request without Accept-Encoding header: should not have compression
  21223. Headers h_no_compress;
  21224. auto res2 = cli.Get("/compressible", h_no_compress);
  21225. ASSERT_TRUE(res2);
  21226. EXPECT_EQ(200, res2->status);
  21227. // Verify Vary header is present when compression is applied
  21228. // (the exact behavior depends on server configuration)
  21229. svr.stop();
  21230. t.join();
  21231. }
  21232. TEST(ETagTest, IfRangeWithETag) {
  21233. using namespace httplib;
  21234. // Create a test file with known content
  21235. const char *fname = "if_range_testfile.txt";
  21236. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  21237. {
  21238. std::ofstream ofs(fname);
  21239. ofs << content;
  21240. ASSERT_TRUE(ofs.good());
  21241. }
  21242. Server svr;
  21243. svr.set_mount_point("/static", ".");
  21244. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21245. svr.wait_until_ready();
  21246. Client cli(HOST, PORT);
  21247. // First request: get ETag
  21248. auto res1 = cli.Get("/static/if_range_testfile.txt");
  21249. ASSERT_TRUE(res1);
  21250. ASSERT_EQ(200, res1->status);
  21251. ASSERT_TRUE(res1->has_header("ETag"));
  21252. std::string etag = res1->get_header_value("ETag");
  21253. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  21254. // Since our server generates weak ETags (W/"..."), If-Range with our
  21255. // ETag should NOT result in partial content - it should return full content.
  21256. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  21257. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  21258. ASSERT_TRUE(res2);
  21259. // Weak ETag in If-Range -> full content (200), not partial (206)
  21260. EXPECT_EQ(200, res2->status);
  21261. EXPECT_EQ(content, res2->body);
  21262. EXPECT_FALSE(res2->has_header("Content-Range"));
  21263. // Range request with non-matching If-Range (ETag): should get 200 (full
  21264. // content)
  21265. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  21266. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  21267. ASSERT_TRUE(res3);
  21268. EXPECT_EQ(200, res3->status);
  21269. EXPECT_EQ(content, res3->body);
  21270. EXPECT_FALSE(res3->has_header("Content-Range"));
  21271. // Range request with strong ETag (hypothetical - our server doesn't generate
  21272. // strong ETags, but if client sends a strong ETag that doesn't match, it
  21273. // should return full content)
  21274. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  21275. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  21276. ASSERT_TRUE(res4);
  21277. EXPECT_EQ(200, res4->status);
  21278. EXPECT_EQ(content, res4->body);
  21279. EXPECT_FALSE(res4->has_header("Content-Range"));
  21280. svr.stop();
  21281. t.join();
  21282. std::remove(fname);
  21283. }
  21284. TEST(ETagTest, IfRangeWithDate) {
  21285. using namespace httplib;
  21286. // Create a test file
  21287. const char *fname = "if_range_date_testfile.txt";
  21288. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  21289. {
  21290. std::ofstream ofs(fname);
  21291. ofs << content;
  21292. ASSERT_TRUE(ofs.good());
  21293. }
  21294. Server svr;
  21295. svr.set_mount_point("/static", ".");
  21296. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21297. svr.wait_until_ready();
  21298. Client cli(HOST, PORT);
  21299. // First request: get Last-Modified
  21300. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  21301. ASSERT_TRUE(res1);
  21302. ASSERT_EQ(200, res1->status);
  21303. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21304. std::string last_modified = res1->get_header_value("Last-Modified");
  21305. // Range request with matching If-Range (date): should get 206
  21306. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  21307. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  21308. ASSERT_TRUE(res2);
  21309. EXPECT_EQ(206, res2->status);
  21310. EXPECT_EQ("FGHIJ", res2->body);
  21311. // Range request with old If-Range date: should get 200 (full content)
  21312. Headers h3 = {{"Range", "bytes=5-9"},
  21313. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  21314. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  21315. ASSERT_TRUE(res3);
  21316. EXPECT_EQ(200, res3->status);
  21317. EXPECT_EQ(content, res3->body);
  21318. // Range request with future If-Range date: should get 206
  21319. Headers h4 = {{"Range", "bytes=0-4"},
  21320. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  21321. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  21322. ASSERT_TRUE(res4);
  21323. EXPECT_EQ(206, res4->status);
  21324. EXPECT_EQ("ABCDE", res4->body);
  21325. svr.stop();
  21326. t.join();
  21327. std::remove(fname);
  21328. }
  21329. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  21330. using namespace httplib;
  21331. const char *fname = "etag_malformed.txt";
  21332. const char *content = "malformed-etag";
  21333. {
  21334. std::ofstream ofs(fname);
  21335. ofs << content;
  21336. ASSERT_TRUE(ofs.good());
  21337. }
  21338. Server svr;
  21339. svr.set_mount_point("/static", ".");
  21340. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21341. svr.wait_until_ready();
  21342. Client cli(HOST, PORT);
  21343. // baseline: should get 200 and an ETag
  21344. auto res1 = cli.Get("/static/etag_malformed.txt");
  21345. ASSERT_TRUE(res1);
  21346. ASSERT_EQ(200, res1->status);
  21347. ASSERT_TRUE(res1->has_header("ETag"));
  21348. // Malformed ETag value (missing quotes) should be treated as non-matching
  21349. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  21350. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  21351. ASSERT_TRUE(res_bad);
  21352. EXPECT_EQ(200, res_bad->status);
  21353. // Whitespace-only header value should be considered invalid / non-matching
  21354. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  21355. "Host: localhost\r\n"
  21356. "If-None-Match: \r\n"
  21357. "Connection: close\r\n"
  21358. "\r\n";
  21359. std::string out;
  21360. ASSERT_TRUE(send_request(5, raw_req, &out));
  21361. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  21362. svr.stop();
  21363. t.join();
  21364. std::remove(fname);
  21365. }
  21366. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  21367. using namespace httplib;
  21368. const char *fname = "ims_invalid_format.txt";
  21369. const char *content = "ims-bad-format";
  21370. {
  21371. std::ofstream ofs(fname);
  21372. ofs << content;
  21373. ASSERT_TRUE(ofs.good());
  21374. }
  21375. Server svr;
  21376. svr.set_mount_point("/static", ".");
  21377. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21378. svr.wait_until_ready();
  21379. Client cli(HOST, PORT);
  21380. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  21381. ASSERT_TRUE(res1);
  21382. ASSERT_EQ(200, res1->status);
  21383. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21384. // If-Modified-Since with invalid format should not result in 304
  21385. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  21386. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  21387. ASSERT_TRUE(res_bad);
  21388. EXPECT_EQ(200, res_bad->status);
  21389. // If-Range with invalid date format should be treated as mismatch -> full
  21390. // content (200)
  21391. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  21392. {"If-Range", "invalid-date"}};
  21393. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  21394. ASSERT_TRUE(res_ifrange);
  21395. EXPECT_EQ(200, res_ifrange->status);
  21396. svr.stop();
  21397. t.join();
  21398. std::remove(fname);
  21399. }
  21400. TEST(ETagTest, IfRangeWithMalformedETag) {
  21401. using namespace httplib;
  21402. const char *fname = "ifrange_malformed.txt";
  21403. const std::string content = "0123456789";
  21404. {
  21405. std::ofstream ofs(fname);
  21406. ofs << content;
  21407. ASSERT_TRUE(ofs.good());
  21408. }
  21409. Server svr;
  21410. svr.set_mount_point("/static", ".");
  21411. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21412. svr.wait_until_ready();
  21413. Client cli(HOST, PORT);
  21414. // First request: get ETag
  21415. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  21416. ASSERT_TRUE(res1);
  21417. ASSERT_EQ(200, res1->status);
  21418. ASSERT_TRUE(res1->has_header("ETag"));
  21419. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  21420. // full content (200)
  21421. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  21422. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  21423. ASSERT_TRUE(res2);
  21424. EXPECT_EQ(200, res2->status);
  21425. EXPECT_EQ(content, res2->body);
  21426. svr.stop();
  21427. t.join();
  21428. std::remove(fname);
  21429. }
  21430. TEST(ETagTest, ExtremeLargeDateValues) {
  21431. using namespace httplib;
  21432. const char *fname = "ims_extreme_date.txt";
  21433. const char *content = "ims-extreme-date";
  21434. {
  21435. std::ofstream ofs(fname);
  21436. ofs << content;
  21437. ASSERT_TRUE(ofs.good());
  21438. }
  21439. Server svr;
  21440. svr.set_mount_point("/static", ".");
  21441. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21442. svr.wait_until_ready();
  21443. Client cli(HOST, PORT);
  21444. auto res1 = cli.Get(std::string("/static/") + fname);
  21445. ASSERT_TRUE(res1);
  21446. ASSERT_EQ(200, res1->status);
  21447. ASSERT_TRUE(res1->has_header("Last-Modified"));
  21448. // Extremely large year that may overflow date parsing routines.
  21449. Headers h_large_date = {
  21450. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21451. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  21452. ASSERT_TRUE(res_bad);
  21453. // Expect server to treat this as invalid/mismatch and return full content
  21454. EXPECT_EQ(200, res_bad->status);
  21455. // If-Range with extremely large date should be treated as mismatch -> full
  21456. // content (200)
  21457. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  21458. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21459. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  21460. ASSERT_TRUE(res_ifrange);
  21461. EXPECT_EQ(200, res_ifrange->status);
  21462. svr.stop();
  21463. t.join();
  21464. std::remove(fname);
  21465. }
  21466. TEST(ETagTest, NegativeFileModificationTime) {
  21467. using namespace httplib;
  21468. const char *fname = "ims_negative_mtime.txt";
  21469. const std::string content = "negative-mtime";
  21470. {
  21471. std::ofstream ofs(fname);
  21472. ofs << content;
  21473. ASSERT_TRUE(ofs.good());
  21474. }
  21475. // Try to set file mtime to a negative value. This may fail on some
  21476. // platforms/filesystems; if it fails, the test will still verify server
  21477. // behaves safely by performing a regular conditional request.
  21478. #if defined(__APPLE__) || defined(__linux__)
  21479. bool set_negative = false;
  21480. do {
  21481. struct timeval times[2];
  21482. // access time: now
  21483. times[0].tv_sec = time(nullptr);
  21484. times[0].tv_usec = 0;
  21485. // modification time: negative (e.g., -1)
  21486. times[1].tv_sec = -1;
  21487. times[1].tv_usec = 0;
  21488. if (utimes(fname, times) == 0) { set_negative = true; }
  21489. } while (0);
  21490. #else
  21491. bool set_negative = false;
  21492. #endif
  21493. Server svr;
  21494. svr.set_mount_point("/static", ".");
  21495. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  21496. svr.wait_until_ready();
  21497. Client cli(HOST, PORT);
  21498. auto res1 = cli.Get(std::string("/static/") + fname);
  21499. ASSERT_TRUE(res1);
  21500. ASSERT_EQ(200, res1->status);
  21501. bool has_last_modified = res1->has_header("Last-Modified");
  21502. std::string last_modified;
  21503. if (has_last_modified) {
  21504. last_modified = res1->get_header_value("Last-Modified");
  21505. }
  21506. if (set_negative) {
  21507. // If we successfully set a negative mtime, ensure server returns a
  21508. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  21509. // with an old date and ensure server handles it without crash.
  21510. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  21511. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  21512. ASSERT_TRUE(res2);
  21513. // Behavior may vary; at minimum ensure server responds (200 or 304).
  21514. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  21515. } else {
  21516. // Could not set negative mtime on this platform; fall back to verifying
  21517. // that normal invalid/malformed dates are treated safely (non-304).
  21518. Headers h_bad_date = {
  21519. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  21520. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  21521. ASSERT_TRUE(res_bad);
  21522. EXPECT_EQ(200, res_bad->status);
  21523. }
  21524. svr.stop();
  21525. t.join();
  21526. std::remove(fname);
  21527. }
  21528. //==============================================================================
  21529. // Integration Tests with Server
  21530. //==============================================================================
  21531. class SSEIntegrationTest : public ::testing::Test {
  21532. protected:
  21533. void SetUp() override {
  21534. stop_server_.store(false);
  21535. events_.clear();
  21536. server_ = httplib::detail::make_unique<Server>();
  21537. setup_server();
  21538. start_server();
  21539. }
  21540. void TearDown() override {
  21541. stop_server_.store(true);
  21542. event_cv_.notify_all();
  21543. server_->stop();
  21544. if (server_thread_.joinable()) { server_thread_.join(); }
  21545. }
  21546. void setup_server() {
  21547. // Simple SSE endpoint
  21548. server_->Get("/events", [this](const Request &req, Response &res) {
  21549. auto last_id = req.get_header_value("Last-Event-ID");
  21550. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  21551. res.set_chunked_content_provider(
  21552. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  21553. std::unique_lock<std::mutex> lock(event_mutex_);
  21554. if (event_cv_.wait_for(
  21555. lock, std::chrono::milliseconds(200), [this] {
  21556. return !events_.empty() || stop_server_.load();
  21557. })) {
  21558. if (stop_server_.load()) { return false; }
  21559. if (!events_.empty()) {
  21560. std::string event = events_.front();
  21561. events_.erase(events_.begin());
  21562. sink.write(event.data(), event.size());
  21563. return true;
  21564. }
  21565. }
  21566. return !stop_server_.load();
  21567. });
  21568. });
  21569. // Endpoint that returns error
  21570. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  21571. res.status = 500;
  21572. res.set_content("Internal Server Error", "text/plain");
  21573. });
  21574. // Endpoint for custom event types
  21575. server_->Get("/custom-events", [](const Request &, Response &res) {
  21576. res.set_chunked_content_provider(
  21577. "text/event-stream", [](size_t offset, DataSink &sink) {
  21578. if (offset == 0) {
  21579. std::string event = "event: update\ndata: updated\n\n"
  21580. "event: delete\ndata: deleted\n\n";
  21581. sink.write(event.data(), event.size());
  21582. }
  21583. return false; // End stream after sending
  21584. });
  21585. });
  21586. }
  21587. void start_server() {
  21588. port_ = server_->bind_to_any_port(HOST);
  21589. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  21590. // Wait for server to start
  21591. while (!server_->is_running()) {
  21592. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21593. }
  21594. }
  21595. int get_port() const { return port_; }
  21596. void send_event(const std::string &event) {
  21597. std::lock_guard<std::mutex> lock(event_mutex_);
  21598. events_.push_back(event);
  21599. event_cv_.notify_all();
  21600. }
  21601. std::unique_ptr<Server> server_;
  21602. std::thread server_thread_;
  21603. std::mutex event_mutex_;
  21604. std::condition_variable event_cv_;
  21605. std::vector<std::string> events_;
  21606. std::atomic<bool> stop_server_{false};
  21607. std::string last_received_event_id_;
  21608. int port_ = 0;
  21609. };
  21610. //==============================================================================
  21611. // SSE Parsing Tests
  21612. //==============================================================================
  21613. class SSEParsingTest : public SSEIntegrationTest {
  21614. protected:
  21615. // Feeds a raw event stream to SSEClient and returns the dispatched messages.
  21616. // A trailing sentinel event tells when the whole stream has been parsed.
  21617. std::vector<sse::SSEMessage> parse(const std::string &stream) {
  21618. auto body = stream + "event: end\ndata: end\n\n";
  21619. server_->Get("/parse", [body](const Request &, Response &res) {
  21620. res.set_content(body, "text/event-stream");
  21621. });
  21622. return collect("/parse");
  21623. }
  21624. // Runs SSEClient against path until an "end" event arrives and returns the
  21625. // messages dispatched before it
  21626. std::vector<sse::SSEMessage> collect(const std::string &path) {
  21627. Client client(HOST, get_port());
  21628. sse::SSEClient sse(client, path);
  21629. std::mutex mutex;
  21630. std::condition_variable cv;
  21631. std::vector<sse::SSEMessage> messages;
  21632. auto done = false;
  21633. sse.on_message([&](const sse::SSEMessage &msg) {
  21634. std::lock_guard<std::mutex> lock(mutex);
  21635. // Ignore a replay from a reconnect that races with stop()
  21636. if (!done) { messages.push_back(msg); }
  21637. });
  21638. sse.on_event("end", [&](const sse::SSEMessage &) {
  21639. std::lock_guard<std::mutex> lock(mutex);
  21640. done = true;
  21641. cv.notify_all();
  21642. });
  21643. sse.set_reconnect_interval(100);
  21644. sse.start_async();
  21645. {
  21646. std::unique_lock<std::mutex> lock(mutex);
  21647. cv.wait_for(lock, std::chrono::seconds(5), [&] { return done; });
  21648. }
  21649. sse.stop();
  21650. EXPECT_TRUE(done);
  21651. return messages;
  21652. }
  21653. };
  21654. TEST_F(SSEParsingTest, SingleLineData) {
  21655. auto msgs = parse("data: hello\n\n");
  21656. ASSERT_EQ(msgs.size(), 1u);
  21657. EXPECT_EQ(msgs[0].data, "hello");
  21658. EXPECT_EQ(msgs[0].event, "message");
  21659. }
  21660. TEST_F(SSEParsingTest, MultiLineData) {
  21661. auto msgs = parse("data: line1\ndata: line2\ndata: line3\n\n");
  21662. ASSERT_EQ(msgs.size(), 1u);
  21663. EXPECT_EQ(msgs[0].data, "line1\nline2\nline3");
  21664. }
  21665. TEST_F(SSEParsingTest, CustomEventType) {
  21666. auto msgs = parse("event: update\ndata: payload\n\n");
  21667. ASSERT_EQ(msgs.size(), 1u);
  21668. EXPECT_EQ(msgs[0].event, "update");
  21669. EXPECT_EQ(msgs[0].data, "payload");
  21670. }
  21671. TEST_F(SSEParsingTest, EventIdHandling) {
  21672. auto msgs = parse("id: 12345\ndata: test\n\n");
  21673. ASSERT_EQ(msgs.size(), 1u);
  21674. EXPECT_EQ(msgs[0].id, "12345");
  21675. }
  21676. TEST_F(SSEParsingTest, EmptyEventId) {
  21677. auto msgs = parse("id:\ndata: test\n\n");
  21678. ASSERT_EQ(msgs.size(), 1u);
  21679. EXPECT_EQ(msgs[0].id, "");
  21680. }
  21681. TEST_F(SSEParsingTest, CommentsIgnored) {
  21682. auto msgs = parse(": this is a comment\ndata: hello\n\n");
  21683. ASSERT_EQ(msgs.size(), 1u);
  21684. EXPECT_EQ(msgs[0].data, "hello");
  21685. EXPECT_EQ(msgs[0].event, "message");
  21686. }
  21687. TEST_F(SSEParsingTest, ColonInValue) {
  21688. auto msgs = parse("data: hello:world:test\n\n");
  21689. ASSERT_EQ(msgs.size(), 1u);
  21690. EXPECT_EQ(msgs[0].data, "hello:world:test");
  21691. }
  21692. TEST_F(SSEParsingTest, FieldNameOnly) {
  21693. // A line without a colon is a field name with an empty value
  21694. auto msgs = parse("data\n\n");
  21695. ASSERT_EQ(msgs.size(), 1u);
  21696. EXPECT_EQ(msgs[0].data, "");
  21697. }
  21698. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  21699. auto msgs = parse("event: update\r\ndata: hello\r\n\r\n");
  21700. ASSERT_EQ(msgs.size(), 1u);
  21701. EXPECT_EQ(msgs[0].event, "update");
  21702. EXPECT_EQ(msgs[0].data, "hello");
  21703. }
  21704. TEST_F(SSEParsingTest, FieldNameOnlyWithCarriageReturn) {
  21705. auto msgs = parse("data\r\n\r\n");
  21706. ASSERT_EQ(msgs.size(), 1u);
  21707. EXPECT_EQ(msgs[0].data, "");
  21708. }
  21709. TEST_F(SSEParsingTest, CarriageReturnLineEnding) {
  21710. auto msgs = parse("event: update\rdata: hello\r\r");
  21711. ASSERT_EQ(msgs.size(), 1u);
  21712. EXPECT_EQ(msgs[0].event, "update");
  21713. EXPECT_EQ(msgs[0].data, "hello");
  21714. }
  21715. TEST_F(SSEParsingTest, LineEndingSplitAcrossChunks) {
  21716. // Chunk boundaries fall inside every \r\n and right before the first one
  21717. std::vector<std::string> chunks = {"event: update", "\r", "\ndata: hello\r",
  21718. "\n\r", "\nevent: end\ndata: end\n\n"};
  21719. server_->Get("/split", [chunks](const Request &, Response &res) {
  21720. auto i = std::make_shared<size_t>(0);
  21721. res.set_chunked_content_provider(
  21722. "text/event-stream", [chunks, i](size_t /*offset*/, DataSink &sink) {
  21723. if (*i == chunks.size()) {
  21724. sink.done();
  21725. } else {
  21726. sink.write(chunks[*i].data(), chunks[*i].size());
  21727. (*i)++;
  21728. }
  21729. return true;
  21730. });
  21731. });
  21732. auto msgs = collect("/split");
  21733. ASSERT_EQ(msgs.size(), 1u);
  21734. EXPECT_EQ(msgs[0].event, "update");
  21735. EXPECT_EQ(msgs[0].data, "hello");
  21736. }
  21737. TEST_F(SSEParsingTest, LeadingByteOrderMarkIgnored) {
  21738. // Only a BOM at the start of the stream is ignored
  21739. auto msgs = parse("\xEF\xBB\xBF"
  21740. "data: first\n\n"
  21741. "\xEF\xBB\xBF"
  21742. "data: second\n\n");
  21743. ASSERT_EQ(msgs.size(), 1u);
  21744. EXPECT_EQ(msgs[0].data, "first");
  21745. }
  21746. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  21747. auto msgs = parse("unknown: value\ndata: hello\n\n");
  21748. ASSERT_EQ(msgs.size(), 1u);
  21749. EXPECT_EQ(msgs[0].data, "hello");
  21750. EXPECT_EQ(msgs[0].event, "message");
  21751. }
  21752. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  21753. auto msgs = parse("data: hello\n\ndata:hello\n\n");
  21754. ASSERT_EQ(msgs.size(), 2u);
  21755. EXPECT_EQ(msgs[0].data, "hello");
  21756. EXPECT_EQ(msgs[1].data, "hello");
  21757. }
  21758. TEST_F(SSEParsingTest, EventWithoutDataResetsEventType) {
  21759. // An event without data is not dispatched, and its type must not leak
  21760. // into the next event
  21761. auto msgs = parse("event: update\n\ndata: hello\n\n");
  21762. ASSERT_EQ(msgs.size(), 1u);
  21763. EXPECT_EQ(msgs[0].event, "message");
  21764. EXPECT_EQ(msgs[0].data, "hello");
  21765. }
  21766. TEST_F(SSEParsingTest, EmptyEventTypeIsMessage) {
  21767. // Also when the empty field replaces an earlier type
  21768. auto msgs = parse("event:\ndata: a\n\nevent: update\nevent:\ndata: b\n\n");
  21769. ASSERT_EQ(msgs.size(), 2u);
  21770. EXPECT_EQ(msgs[0].event, "message");
  21771. EXPECT_EQ(msgs[1].event, "message");
  21772. }
  21773. TEST_F(SSEParsingTest, EventWithoutDataUpdatesLastEventId) {
  21774. // The first connection sends only an id; the second echoes back the
  21775. // Last-Event-ID it was reconnected with
  21776. std::atomic<int> connection_count{0};
  21777. server_->Get("/id-only", [&](const Request &req, Response &res) {
  21778. if (connection_count++ == 0) {
  21779. res.set_content("id: 42\n\n", "text/event-stream");
  21780. } else {
  21781. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21782. "\n\nevent: end\ndata: end\n\n",
  21783. "text/event-stream");
  21784. }
  21785. });
  21786. auto msgs = collect("/id-only");
  21787. ASSERT_EQ(msgs.size(), 1u);
  21788. EXPECT_EQ(msgs[0].data, "42");
  21789. }
  21790. TEST_F(SSEParsingTest, EmptyEventIdClearsLastEventId) {
  21791. // The first connection sets an id and then clears it with an empty one; the
  21792. // second reports whether it was reconnected with a Last-Event-ID
  21793. std::atomic<int> connection_count{0};
  21794. server_->Get("/id-clear", [&](const Request &req, Response &res) {
  21795. if (connection_count++ == 0) {
  21796. res.set_content("id: 1\ndata: first\n\nid:\ndata: second\n\n",
  21797. "text/event-stream");
  21798. } else {
  21799. res.set_content(
  21800. std::string("data: ") +
  21801. (req.has_header("Last-Event-ID") ? "sent" : "not sent") +
  21802. "\n\nevent: end\ndata: end\n\n",
  21803. "text/event-stream");
  21804. }
  21805. });
  21806. auto msgs = collect("/id-clear");
  21807. ASSERT_EQ(msgs.size(), 3u);
  21808. EXPECT_EQ(msgs[0].id, "1");
  21809. EXPECT_EQ(msgs[1].id, "");
  21810. EXPECT_EQ(msgs[2].data, "not sent");
  21811. }
  21812. TEST_F(SSEParsingTest, UnsendableEventIdKeepsLastEventId) {
  21813. // The first connection sets an id and then sends ids that cannot be carried
  21814. // in a header; the second echoes back the Last-Event-ID it was reconnected
  21815. // with
  21816. std::atomic<int> connection_count{0};
  21817. server_->Get("/id-unsendable", [&](const Request &req, Response &res) {
  21818. if (connection_count++ == 0) {
  21819. res.set_content(std::string("id: 42\n\nid: a") + '\0' +
  21820. "b\n\nid: \x01\n\nid: 7\n\nid: 7 \n\n",
  21821. "text/event-stream");
  21822. } else {
  21823. res.set_content("data: " + req.get_header_value("Last-Event-ID") +
  21824. "\n\nevent: end\ndata: end\n\n",
  21825. "text/event-stream");
  21826. }
  21827. });
  21828. auto msgs = collect("/id-unsendable");
  21829. ASSERT_EQ(msgs.size(), 1u);
  21830. EXPECT_EQ(msgs[0].data, "42");
  21831. }
  21832. TEST_F(SSEParsingTest, CompleteEventParsing) {
  21833. auto msgs = parse("event: notification\nid: evt-42\n"
  21834. "data: {\"type\":\"alert\"}\nretry: 1000\n\n");
  21835. ASSERT_EQ(msgs.size(), 1u);
  21836. EXPECT_EQ(msgs[0].event, "notification");
  21837. EXPECT_EQ(msgs[0].id, "evt-42");
  21838. EXPECT_EQ(msgs[0].data, "{\"type\":\"alert\"}");
  21839. }
  21840. TEST(SSEMessageTest, Clear) {
  21841. sse::SSEMessage msg;
  21842. msg.event = "custom";
  21843. msg.data = "some data";
  21844. msg.id = "123";
  21845. msg.clear();
  21846. EXPECT_EQ(msg.event, "message");
  21847. EXPECT_EQ(msg.data, "");
  21848. EXPECT_EQ(msg.id, "");
  21849. }
  21850. //==============================================================================
  21851. // SSE Integration Tests
  21852. //==============================================================================
  21853. // Test: Successful connection and on_open callback
  21854. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  21855. // Add a simple endpoint that sends one event and closes
  21856. server_->Get("/simple-event", [](const Request &, Response &res) {
  21857. res.set_chunked_content_provider(
  21858. "text/event-stream", [](size_t offset, DataSink &sink) {
  21859. if (offset == 0) {
  21860. std::string event = "data: hello\n\n";
  21861. sink.write(event.data(), event.size());
  21862. }
  21863. return false; // Close stream after sending
  21864. });
  21865. });
  21866. Client client("localhost", get_port());
  21867. sse::SSEClient sse(client, "/simple-event");
  21868. std::atomic<bool> open_called{false};
  21869. std::atomic<bool> message_received{false};
  21870. sse.on_open([&open_called]() { open_called.store(true); });
  21871. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  21872. if (msg.data == "hello") { message_received.store(true); }
  21873. });
  21874. sse.set_reconnect_interval(100);
  21875. sse.set_max_reconnect_attempts(1);
  21876. // Start async
  21877. sse.start_async();
  21878. // Wait for message to be processed
  21879. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21880. sse.stop();
  21881. EXPECT_TRUE(open_called.load());
  21882. EXPECT_TRUE(message_received.load());
  21883. }
  21884. TEST_F(SSEIntegrationTest, TooLongEventEndsTheConnection) {
  21885. // A data line that never ends.
  21886. server_->Get("/endless-line", [](const Request &, Response &res) {
  21887. res.set_chunked_content_provider(
  21888. "text/event-stream", [](size_t offset, DataSink &sink) {
  21889. if (offset == 0) { sink.write("data: ", 6); }
  21890. std::string chunk(64 * 1024, 'A');
  21891. return sink.write(chunk.data(), chunk.size());
  21892. });
  21893. });
  21894. Client client("localhost", get_port());
  21895. sse::SSEClient sse(client, "/endless-line");
  21896. std::atomic<bool> too_long{false};
  21897. sse.on_error([&](Error err) {
  21898. if (err == Error::ExceedMaxPayloadSize) { too_long = true; }
  21899. });
  21900. sse.set_max_reconnect_attempts(1);
  21901. sse.start_async();
  21902. for (int i = 0; i < 500 && !too_long; i++) {
  21903. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21904. }
  21905. sse.stop();
  21906. EXPECT_TRUE(too_long);
  21907. }
  21908. TEST_F(SSEIntegrationTest, PayloadLimitDoesNotEndTheStream) {
  21909. // Far more in all than the client's payload limit below.
  21910. server_->Get("/many-events", [](const Request &, Response &res) {
  21911. res.set_chunked_content_provider(
  21912. "text/event-stream", [](size_t offset, DataSink &sink) {
  21913. if (offset == 0) {
  21914. std::string events;
  21915. for (int i = 0; i < 1000; i++) {
  21916. events += "data: message\n\n";
  21917. }
  21918. sink.write(events.data(), events.size());
  21919. }
  21920. return false;
  21921. });
  21922. });
  21923. Client client("localhost", get_port());
  21924. client.set_payload_max_length(1024);
  21925. sse::SSEClient sse(client, "/many-events");
  21926. std::atomic<int> messages{0};
  21927. std::atomic<bool> too_large{false};
  21928. sse.on_message([&](const sse::SSEMessage &) { messages++; });
  21929. sse.on_error([&](Error err) {
  21930. if (err == Error::ExceedMaxPayloadSize) { too_large = true; }
  21931. });
  21932. sse.set_max_reconnect_attempts(1);
  21933. sse.start_async();
  21934. for (int i = 0; i < 500 && messages < 1000; i++) {
  21935. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  21936. }
  21937. sse.stop();
  21938. EXPECT_GE(messages.load(), 1000);
  21939. EXPECT_FALSE(too_large);
  21940. }
  21941. // Test: on_message callback
  21942. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  21943. // Endpoint that sends multiple events then closes
  21944. server_->Get("/multi-event", [](const Request &, Response &res) {
  21945. res.set_chunked_content_provider(
  21946. "text/event-stream", [](size_t offset, DataSink &sink) {
  21947. if (offset == 0) {
  21948. std::string events = "data: message1\n\ndata: message2\n\n";
  21949. sink.write(events.data(), events.size());
  21950. }
  21951. return false;
  21952. });
  21953. });
  21954. Client client("localhost", get_port());
  21955. sse::SSEClient sse(client, "/multi-event");
  21956. std::vector<std::string> received_messages;
  21957. std::mutex messages_mutex;
  21958. sse.on_message([&](const sse::SSEMessage &msg) {
  21959. std::lock_guard<std::mutex> lock(messages_mutex);
  21960. received_messages.push_back(msg.data);
  21961. });
  21962. sse.set_reconnect_interval(100);
  21963. sse.set_max_reconnect_attempts(1);
  21964. sse.start_async();
  21965. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  21966. sse.stop();
  21967. std::lock_guard<std::mutex> lock(messages_mutex);
  21968. EXPECT_GE(received_messages.size(), 2u);
  21969. if (received_messages.size() >= 2) {
  21970. EXPECT_EQ(received_messages[0], "message1");
  21971. EXPECT_EQ(received_messages[1], "message2");
  21972. }
  21973. }
  21974. // Test: on_event for specific types
  21975. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  21976. Client client("localhost", get_port());
  21977. sse::SSEClient sse(client, "/custom-events");
  21978. std::atomic<bool> update_received{false};
  21979. std::atomic<bool> delete_received{false};
  21980. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  21981. if (msg.data == "updated") { update_received.store(true); }
  21982. });
  21983. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  21984. if (msg.data == "deleted") { delete_received.store(true); }
  21985. });
  21986. sse.set_max_reconnect_attempts(1);
  21987. sse.start_async();
  21988. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  21989. sse.stop();
  21990. EXPECT_TRUE(update_received.load());
  21991. EXPECT_TRUE(delete_received.load());
  21992. }
  21993. // Test: on_error callback on connection failure
  21994. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  21995. // Connect to a non-existent port
  21996. Client client("localhost", 59999);
  21997. sse::SSEClient sse(client, "/events");
  21998. std::atomic<bool> error_called{false};
  21999. Error received_error = Error::Success;
  22000. sse.on_error([&](Error err) {
  22001. error_called.store(true);
  22002. received_error = err;
  22003. });
  22004. sse.set_reconnect_interval(50);
  22005. sse.set_max_reconnect_attempts(1);
  22006. sse.start_async();
  22007. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22008. sse.stop();
  22009. EXPECT_TRUE(error_called.load());
  22010. EXPECT_NE(received_error, Error::Success);
  22011. }
  22012. // Test: Last-Event-ID header sent on reconnect
  22013. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  22014. // Endpoint that sends event with ID
  22015. server_->Get("/event-with-id", [](const Request &, Response &res) {
  22016. res.set_chunked_content_provider(
  22017. "text/event-stream", [](size_t offset, DataSink &sink) {
  22018. if (offset == 0) {
  22019. std::string event = "id: evt-123\ndata: test\n\n";
  22020. sink.write(event.data(), event.size());
  22021. }
  22022. return false;
  22023. });
  22024. });
  22025. Client client("localhost", get_port());
  22026. sse::SSEClient sse(client, "/event-with-id");
  22027. std::atomic<bool> id_received{false};
  22028. sse.on_message([&](const sse::SSEMessage &msg) {
  22029. if (!msg.id.empty()) { id_received.store(true); }
  22030. });
  22031. sse.set_reconnect_interval(100);
  22032. sse.set_max_reconnect_attempts(1);
  22033. sse.start_async();
  22034. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22035. sse.stop();
  22036. EXPECT_TRUE(id_received.load());
  22037. EXPECT_EQ(sse.last_event_id(), "evt-123");
  22038. }
  22039. // Test: Manual stop
  22040. TEST_F(SSEIntegrationTest, ManualStop) {
  22041. // Endpoint that sends one event and stays open briefly. The server outlives
  22042. // this test body, so the provider uses the fixture's flag, not a local.
  22043. server_->Get("/stay-open", [this](const Request &, Response &res) {
  22044. res.set_chunked_content_provider(
  22045. "text/event-stream", [this](size_t offset, DataSink &sink) {
  22046. if (offset == 0) {
  22047. std::string event = "data: connected\n\n";
  22048. sink.write(event.data(), event.size());
  22049. }
  22050. for (int i = 0; i < 10 && !stop_server_.load(); ++i) {
  22051. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22052. }
  22053. return false;
  22054. });
  22055. });
  22056. Client client("localhost", get_port());
  22057. sse::SSEClient sse(client, "/stay-open");
  22058. std::atomic<bool> connected{false};
  22059. sse.on_open([&connected]() { connected.store(true); });
  22060. sse.set_reconnect_interval(100);
  22061. sse.set_max_reconnect_attempts(1);
  22062. sse.start_async();
  22063. // Wait for connection to establish
  22064. for (int i = 0; i < 20 && !connected.load(); ++i) {
  22065. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  22066. }
  22067. EXPECT_TRUE(connected.load());
  22068. EXPECT_TRUE(sse.is_connected());
  22069. // Signal handler to stop
  22070. stop_server_.store(true);
  22071. // Stop SSE client
  22072. sse.stop();
  22073. EXPECT_FALSE(sse.is_connected());
  22074. }
  22075. // Sends one event, then nothing until stop is set
  22076. static Server::Handler idle_event_stream(std::atomic<bool> &stop) {
  22077. return [&stop](const Request &, Response &res) {
  22078. res.set_chunked_content_provider(
  22079. "text/event-stream", [&stop](size_t offset, DataSink &sink) {
  22080. if (offset == 0) {
  22081. std::string event = "data: hello\n\n";
  22082. sink.write(event.data(), event.size());
  22083. }
  22084. while (!stop.load()) {
  22085. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22086. }
  22087. return false;
  22088. });
  22089. };
  22090. }
  22091. // Both stop() and the destructor end a read blocked on /idle-stream promptly
  22092. static void check_stop_interrupts_blocked_read(Client &client) {
  22093. client.set_read_timeout(30, 0);
  22094. for (auto by_destructor : {false, true}) {
  22095. std::atomic<bool> received{false};
  22096. std::chrono::steady_clock::time_point start;
  22097. {
  22098. sse::SSEClient sse(client, "/idle-stream");
  22099. sse.on_message([&](const sse::SSEMessage &) { received.store(true); });
  22100. sse.start_async();
  22101. for (int i = 0; i < 500 && !received.load(); ++i) {
  22102. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22103. }
  22104. ASSERT_TRUE(received.load());
  22105. // Let the client block in the next read
  22106. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  22107. start = std::chrono::steady_clock::now();
  22108. if (!by_destructor) { sse.stop(); }
  22109. }
  22110. EXPECT_LT(std::chrono::steady_clock::now() - start,
  22111. std::chrono::seconds(2));
  22112. }
  22113. }
  22114. TEST_F(SSEIntegrationTest, StopInterruptsBlockedRead) {
  22115. server_->Get("/idle-stream", idle_event_stream(stop_server_));
  22116. Client client("localhost", get_port());
  22117. check_stop_interrupts_blocked_read(client);
  22118. }
  22119. #ifdef CPPHTTPLIB_SSL_ENABLED
  22120. TEST(SSEClientSSLTest, StopInterruptsBlockedRead) {
  22121. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22122. std::atomic<bool> done{false};
  22123. svr.Get("/idle-stream", idle_event_stream(done));
  22124. auto port = svr.bind_to_any_port(HOST);
  22125. std::thread t([&] { svr.listen_after_bind(); });
  22126. auto se = detail::scope_exit([&] {
  22127. done.store(true);
  22128. svr.stop();
  22129. t.join();
  22130. });
  22131. svr.wait_until_ready();
  22132. Client client("https://localhost:" + std::to_string(port));
  22133. client.enable_server_certificate_verification(false);
  22134. check_stop_interrupts_blocked_read(client);
  22135. }
  22136. #endif
  22137. // Test: SSEClient with custom headers
  22138. TEST_F(SSEIntegrationTest, CustomHeaders) {
  22139. // Setup a server endpoint that checks for custom header
  22140. std::atomic<bool> header_received{false};
  22141. server_->Get("/header-check", [&](const Request &req, Response &res) {
  22142. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  22143. header_received.store(true);
  22144. }
  22145. res.set_chunked_content_provider("text/event-stream",
  22146. [](size_t, DataSink &) { return false; });
  22147. });
  22148. Client client("localhost", get_port());
  22149. Headers headers = {{"X-Custom-Header", "custom-value"}};
  22150. sse::SSEClient sse(client, "/header-check", headers);
  22151. sse.set_max_reconnect_attempts(1);
  22152. sse.start_async();
  22153. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  22154. sse.stop();
  22155. EXPECT_TRUE(header_received.load());
  22156. }
  22157. // Test: Reconnect interval configuration
  22158. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  22159. Client client("localhost", get_port());
  22160. sse::SSEClient sse(client, "/events");
  22161. auto &result = sse.set_reconnect_interval(500);
  22162. // Builder pattern should return reference to self
  22163. EXPECT_EQ(&result, &sse);
  22164. }
  22165. // Test: Max reconnect attempts
  22166. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  22167. // Connect to non-existent port to force reconnects
  22168. Client client("localhost", 59998);
  22169. sse::SSEClient sse(client, "/events");
  22170. std::atomic<int> error_count{0};
  22171. sse.on_error([&](Error) { error_count.fetch_add(1); });
  22172. sse.set_reconnect_interval(50);
  22173. sse.set_max_reconnect_attempts(2);
  22174. auto start = std::chrono::steady_clock::now();
  22175. sse.start(); // Blocking call
  22176. auto end = std::chrono::steady_clock::now();
  22177. // Should have stopped after 2 failed attempts
  22178. EXPECT_GE(error_count.load(), 2);
  22179. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  22180. auto duration =
  22181. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  22182. #ifdef _WIN32
  22183. // Windows is much slower for socket connection failures
  22184. EXPECT_LT(duration.count(), 7000);
  22185. #else
  22186. EXPECT_LT(duration.count(), 1000);
  22187. #endif
  22188. }
  22189. // Test: Multi-line data in integration
  22190. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  22191. // Endpoint with multi-line data
  22192. server_->Get("/multiline-data", [](const Request &, Response &res) {
  22193. res.set_chunked_content_provider(
  22194. "text/event-stream", [](size_t offset, DataSink &sink) {
  22195. if (offset == 0) {
  22196. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  22197. sink.write(event.data(), event.size());
  22198. }
  22199. return false;
  22200. });
  22201. });
  22202. Client client("localhost", get_port());
  22203. sse::SSEClient sse(client, "/multiline-data");
  22204. std::string received_data;
  22205. std::mutex data_mutex;
  22206. sse.on_message([&](const sse::SSEMessage &msg) {
  22207. std::lock_guard<std::mutex> lock(data_mutex);
  22208. received_data = msg.data;
  22209. });
  22210. sse.set_reconnect_interval(100);
  22211. sse.set_max_reconnect_attempts(1);
  22212. sse.start_async();
  22213. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22214. sse.stop();
  22215. std::lock_guard<std::mutex> lock(data_mutex);
  22216. EXPECT_EQ(received_data, "line1\nline2\nline3");
  22217. }
  22218. TEST_F(SSEIntegrationTest, EmptyDataLines) {
  22219. server_->Get("/empty-data-lines", [](const Request &, Response &res) {
  22220. res.set_chunked_content_provider("text/event-stream", [](size_t offset,
  22221. DataSink &sink) {
  22222. if (offset == 0) {
  22223. const std::string events = "data:\n\ndata:\ndata: hello\n\ndata\n\n";
  22224. sink.write(events.data(), events.size());
  22225. }
  22226. return false;
  22227. });
  22228. });
  22229. Client client("localhost", get_port());
  22230. sse::SSEClient sse(client, "/empty-data-lines");
  22231. std::mutex mutex;
  22232. std::condition_variable cv;
  22233. std::vector<std::string> received;
  22234. sse.on_message([&](const sse::SSEMessage &msg) {
  22235. std::lock_guard<std::mutex> lock(mutex);
  22236. received.push_back(msg.data);
  22237. cv.notify_all();
  22238. });
  22239. sse.set_max_reconnect_attempts(1);
  22240. sse.start_async();
  22241. {
  22242. std::unique_lock<std::mutex> lock(mutex);
  22243. cv.wait_for(lock, std::chrono::seconds(2),
  22244. [&] { return received.size() >= 3; });
  22245. }
  22246. sse.stop();
  22247. ASSERT_GE(received.size(), 3u);
  22248. EXPECT_EQ(received[0], "");
  22249. EXPECT_EQ(received[1], "\nhello");
  22250. EXPECT_EQ(received[2], "");
  22251. }
  22252. // Test: Auto-reconnect after server disconnection
  22253. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  22254. std::atomic<int> connection_count{0};
  22255. std::atomic<int> message_count{0};
  22256. // Endpoint that sends one event and closes, forcing reconnect
  22257. server_->Get("/reconnect-test",
  22258. [&connection_count](const Request &, Response &res) {
  22259. connection_count.fetch_add(1);
  22260. res.set_chunked_content_provider(
  22261. "text/event-stream", [](size_t offset, DataSink &sink) {
  22262. if (offset == 0) {
  22263. std::string event = "data: hello\n\n";
  22264. sink.write(event.data(), event.size());
  22265. }
  22266. return false; // Close connection after sending
  22267. });
  22268. });
  22269. Client client("localhost", get_port());
  22270. sse::SSEClient sse(client, "/reconnect-test");
  22271. sse.on_message([&message_count](const sse::SSEMessage &) {
  22272. message_count.fetch_add(1);
  22273. });
  22274. sse.set_reconnect_interval(100);
  22275. sse.set_max_reconnect_attempts(3);
  22276. sse.start_async();
  22277. // Wait long enough for multiple reconnects
  22278. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22279. sse.stop();
  22280. // Should have connected multiple times (initial + reconnects)
  22281. EXPECT_GE(connection_count.load(), 2);
  22282. // Should have received messages from multiple connections
  22283. EXPECT_GE(message_count.load(), 2);
  22284. }
  22285. TEST_F(SSEIntegrationTest, StreamEndingAtConnectionCloseIsNotAnError) {
  22286. std::atomic<int> connection_count{0};
  22287. // Neither Content-Length nor chunked: the close ends the stream
  22288. server_->Get("/close-delimited",
  22289. [&connection_count](const Request &, Response &res) {
  22290. connection_count.fetch_add(1);
  22291. res.set_content_provider(
  22292. "text/event-stream", [](size_t offset, DataSink &sink) {
  22293. if (offset == 0) {
  22294. std::string event = "data: hello\n\n";
  22295. sink.write(event.data(), event.size());
  22296. } else {
  22297. sink.done();
  22298. }
  22299. return true;
  22300. });
  22301. });
  22302. Client client("localhost", get_port());
  22303. sse::SSEClient sse(client, "/close-delimited");
  22304. std::atomic<int> error_count{0};
  22305. sse.on_error([&error_count](Error) { error_count.fetch_add(1); });
  22306. sse.set_reconnect_interval(100);
  22307. sse.start_async();
  22308. for (int i = 0; i < 500 && connection_count.load() < 2; ++i) {
  22309. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  22310. }
  22311. sse.stop();
  22312. // Reconnects as after any end of the stream, but reports no error
  22313. EXPECT_GE(connection_count.load(), 2);
  22314. EXPECT_EQ(0, error_count.load());
  22315. }
  22316. // Test: A retry field that is not all ASCII digits is ignored
  22317. TEST_F(SSEIntegrationTest, NonDigitRetryFieldIgnored) {
  22318. std::atomic<int> connection_count{0};
  22319. server_->Get("/bad-retry",
  22320. [&connection_count](const Request &, Response &res) {
  22321. connection_count.fetch_add(1);
  22322. res.set_chunked_content_provider(
  22323. "text/event-stream", [](size_t offset, DataSink &sink) {
  22324. if (offset == 0) {
  22325. std::string event = "retry: -1\ndata: hello\n\n";
  22326. sink.write(event.data(), event.size());
  22327. }
  22328. return false;
  22329. });
  22330. });
  22331. Client client("localhost", get_port());
  22332. sse::SSEClient sse(client, "/bad-retry");
  22333. sse.set_reconnect_interval(10000);
  22334. sse.start_async();
  22335. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22336. sse.stop();
  22337. EXPECT_EQ(connection_count.load(), 1);
  22338. }
  22339. // Test: A retry field of all ASCII digits sets the reconnection time
  22340. TEST_F(SSEIntegrationTest, DigitRetryFieldApplied) {
  22341. std::mutex mutex;
  22342. std::condition_variable cv;
  22343. std::vector<std::chrono::steady_clock::time_point> connected_at;
  22344. server_->Get("/zero-retry", [&](const Request &, Response &res) {
  22345. {
  22346. std::lock_guard<std::mutex> lock(mutex);
  22347. connected_at.push_back(std::chrono::steady_clock::now());
  22348. cv.notify_all();
  22349. }
  22350. res.set_chunked_content_provider(
  22351. "text/event-stream", [](size_t offset, DataSink &sink) {
  22352. if (offset == 0) {
  22353. std::string event = "retry: 0\ndata: hello\n\n";
  22354. sink.write(event.data(), event.size());
  22355. }
  22356. return false;
  22357. });
  22358. });
  22359. Client client("localhost", get_port());
  22360. sse::SSEClient sse(client, "/zero-retry");
  22361. sse.set_reconnect_interval(10000);
  22362. sse.start_async();
  22363. {
  22364. std::unique_lock<std::mutex> lock(mutex);
  22365. cv.wait_for(lock, std::chrono::seconds(5),
  22366. [&] { return connected_at.size() >= 2; });
  22367. }
  22368. sse.stop();
  22369. // The server-supplied interval is applied, but never below 100ms, so
  22370. // "retry: 0" does not cause a busy reconnect loop
  22371. std::lock_guard<std::mutex> lock(mutex);
  22372. ASSERT_GE(connected_at.size(), 2u);
  22373. auto interval_ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  22374. connected_at[1] - connected_at[0])
  22375. .count();
  22376. EXPECT_GE(interval_ms, 100);
  22377. }
  22378. // Test: Last-Event-ID sent on reconnect
  22379. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  22380. std::atomic<int> connection_count{0};
  22381. std::vector<std::string> received_last_event_ids;
  22382. std::mutex id_mutex;
  22383. // Endpoint that checks Last-Event-ID header and sends event with ID
  22384. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  22385. int conn = connection_count.fetch_add(1);
  22386. // Capture the Last-Event-ID header from each connection
  22387. {
  22388. std::lock_guard<std::mutex> lock(id_mutex);
  22389. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  22390. }
  22391. res.set_chunked_content_provider(
  22392. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  22393. if (offset == 0) {
  22394. std::string event =
  22395. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  22396. sink.write(event.data(), event.size());
  22397. }
  22398. return false;
  22399. });
  22400. });
  22401. Client client("localhost", get_port());
  22402. sse::SSEClient sse(client, "/reconnect-with-id");
  22403. sse.set_reconnect_interval(100);
  22404. sse.set_max_reconnect_attempts(3);
  22405. sse.start_async();
  22406. // Wait for at least 2 connections
  22407. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  22408. sse.stop();
  22409. // Verify behavior
  22410. std::lock_guard<std::mutex> lock(id_mutex);
  22411. EXPECT_GE(received_last_event_ids.size(), 2u);
  22412. // First connection should have no Last-Event-ID
  22413. if (!received_last_event_ids.empty()) {
  22414. EXPECT_EQ(received_last_event_ids[0], "");
  22415. }
  22416. // Second connection should have Last-Event-ID from first connection
  22417. if (received_last_event_ids.size() >= 2) {
  22418. EXPECT_EQ(received_last_event_ids[1], "event-0");
  22419. }
  22420. }
  22421. // Test: set_headers updates headers used on reconnect
  22422. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  22423. std::vector<std::string> received_tokens;
  22424. std::mutex token_mutex;
  22425. // Endpoint that captures Authorization header
  22426. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  22427. {
  22428. std::lock_guard<std::mutex> lock(token_mutex);
  22429. received_tokens.push_back(req.get_header_value("Authorization"));
  22430. }
  22431. res.set_chunked_content_provider(
  22432. "text/event-stream", [](size_t offset, DataSink &sink) {
  22433. if (offset == 0) {
  22434. std::string event = "data: hello\n\n";
  22435. sink.write(event.data(), event.size());
  22436. }
  22437. return false; // Close connection to trigger reconnect
  22438. });
  22439. });
  22440. Client client("localhost", get_port());
  22441. Headers headers = {{"Authorization", "Bearer old-token"}};
  22442. sse::SSEClient sse(client, "/auth-check", headers);
  22443. // Update headers on each successful connection
  22444. sse.on_open(
  22445. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  22446. sse.set_reconnect_interval(100);
  22447. sse.set_max_reconnect_attempts(3);
  22448. sse.start_async();
  22449. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22450. sse.stop();
  22451. std::lock_guard<std::mutex> lock(token_mutex);
  22452. ASSERT_GE(received_tokens.size(), 2u);
  22453. // First connection uses original header
  22454. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  22455. // Second connection uses updated header from set_headers
  22456. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  22457. }
  22458. // Test: 401 allows reconnection (so on_error can refresh headers)
  22459. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  22460. std::atomic<int> connection_count{0};
  22461. // Endpoint: returns 401 on first attempt, 200 on second
  22462. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  22463. int conn = connection_count.fetch_add(1);
  22464. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  22465. res.status = StatusCode::Unauthorized_401;
  22466. res.set_content("Unauthorized", "text/plain");
  22467. return;
  22468. }
  22469. res.set_chunked_content_provider(
  22470. "text/event-stream", [](size_t offset, DataSink &sink) {
  22471. if (offset == 0) {
  22472. std::string event = "data: authenticated\n\n";
  22473. sink.write(event.data(), event.size());
  22474. }
  22475. return false;
  22476. });
  22477. });
  22478. Client client("localhost", get_port());
  22479. Headers headers = {{"Authorization", "Bearer expired"}};
  22480. sse::SSEClient sse(client, "/auth-retry", headers);
  22481. std::atomic<bool> message_received{false};
  22482. // Refresh token on error
  22483. sse.on_error(
  22484. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  22485. sse.on_message([&](const sse::SSEMessage &msg) {
  22486. if (msg.data == "authenticated") { message_received.store(true); }
  22487. });
  22488. sse.set_reconnect_interval(100);
  22489. sse.set_max_reconnect_attempts(3);
  22490. sse.start_async();
  22491. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  22492. sse.stop();
  22493. // Should have reconnected after 401 and succeeded with new token
  22494. EXPECT_GE(connection_count.load(), 2);
  22495. EXPECT_TRUE(message_received.load());
  22496. }
  22497. TEST(Issue2318Test, EmptyHostString) {
  22498. {
  22499. httplib::Client cli_empty("", PORT);
  22500. auto res = cli_empty.Get("/");
  22501. ASSERT_FALSE(res);
  22502. EXPECT_EQ(httplib::Error::Connection, res.error());
  22503. }
  22504. {
  22505. httplib::Client cli(" ", PORT);
  22506. auto res = cli.Get("/");
  22507. ASSERT_FALSE(res);
  22508. EXPECT_EQ(httplib::Error::Connection, res.error());
  22509. }
  22510. }
  22511. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  22512. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  22513. Server svr;
  22514. // Set a small payload limit (1KB)
  22515. svr.set_payload_max_length(1024);
  22516. svr.Post("/test", [&](const Request &req, Response &res) {
  22517. res.set_content("Body size: " + std::to_string(req.body.size()),
  22518. "text/plain");
  22519. });
  22520. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  22521. auto se = detail::scope_exit([&] {
  22522. svr.stop();
  22523. listen_thread.join();
  22524. });
  22525. svr.wait_until_ready();
  22526. // Create data that compresses well but exceeds limit when decompressed
  22527. // 8KB of repeated null bytes compresses to a very small size
  22528. std::string original_data(8 * 1024, '\0');
  22529. // Compress the data using gzip
  22530. std::string compressed_data;
  22531. detail::gzip_compressor compressor;
  22532. compressor.compress(original_data.data(), original_data.size(), true,
  22533. [&](const char *data, size_t size) {
  22534. compressed_data.append(data, size);
  22535. return true;
  22536. });
  22537. // Verify compression worked (compressed should be much smaller)
  22538. ASSERT_LT(compressed_data.size(), original_data.size());
  22539. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  22540. // Send compressed data with Content-Encoding: gzip
  22541. Client cli(HOST, PORT);
  22542. Headers headers = {{"Content-Encoding", "gzip"}};
  22543. auto res =
  22544. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  22545. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  22546. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22547. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  22548. }
  22549. #endif
  22550. // ============================================================================
  22551. // OpenSSL-Specific Tests
  22552. // ============================================================================
  22553. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  22554. X509 *readCertificate(const std::string &strFileName) {
  22555. std::ifstream inStream(strFileName);
  22556. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  22557. std::istreambuf_iterator<char>());
  22558. if (strCertPEM.empty()) return (nullptr);
  22559. BIO *pbCert = BIO_new(BIO_s_mem());
  22560. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  22561. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  22562. BIO_free(pbCert);
  22563. return (pCert);
  22564. }
  22565. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  22566. std::ifstream inStream(strFileName);
  22567. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  22568. std::istreambuf_iterator<char>());
  22569. if (strPrivateKeyPEM.empty()) return (nullptr);
  22570. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  22571. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  22572. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  22573. BIO_free(pbPrivKey);
  22574. return (pPrivateKey);
  22575. }
  22576. TEST(BindServerTest, UpdateCerts) {
  22577. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22578. int port = svr.bind_to_any_port("0.0.0.0");
  22579. ASSERT_TRUE(svr.is_valid());
  22580. ASSERT_TRUE(port > 0);
  22581. X509 *cert = readCertificate(SERVER_CERT_FILE);
  22582. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  22583. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  22584. ASSERT_TRUE(cert != nullptr);
  22585. ASSERT_TRUE(ca_cert != nullptr);
  22586. ASSERT_TRUE(key != nullptr);
  22587. X509_STORE *cert_store = X509_STORE_new();
  22588. X509_STORE_add_cert(cert_store, ca_cert);
  22589. // svr.update_certs(cert, key, cert_store); // deprecated
  22590. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  22591. CLIENT_CA_CERT_FILE);
  22592. ASSERT_TRUE(svr.is_valid());
  22593. svr.stop();
  22594. X509_STORE_free(cert_store);
  22595. X509_free(cert);
  22596. X509_free(ca_cert);
  22597. EVP_PKEY_free(key);
  22598. }
  22599. // Test that update_certs() updates client CA list correctly
  22600. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  22601. // Start with file-based constructor
  22602. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22603. ASSERT_TRUE(svr.is_valid());
  22604. // Initially no client CA list should be set
  22605. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22606. ASSERT_TRUE(ssl_ctx != nullptr);
  22607. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  22608. EXPECT_TRUE(!ca_list_before || sk_X509_NAME_num(ca_list_before) == 0);
  22609. // Now update with client CA (PEM string)
  22610. std::string cert_pem, key_pem, ca_pem;
  22611. read_file(SERVER_CERT_FILE, cert_pem);
  22612. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  22613. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  22614. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  22615. ASSERT_TRUE(svr.is_valid());
  22616. // Now client CA list should be set
  22617. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  22618. ASSERT_TRUE(ca_list_after != nullptr);
  22619. EXPECT_TRUE(sk_X509_NAME_num(ca_list_after) > 0);
  22620. }
  22621. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  22622. // Test that the file-path SSLServer constructor properly sets the client CA
  22623. // list that is sent to clients during the TLS handshake (CertificateRequest)
  22624. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  22625. ASSERT_TRUE(svr.is_valid());
  22626. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  22627. ASSERT_TRUE(ssl_ctx != nullptr);
  22628. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  22629. ASSERT_TRUE(ca_list != nullptr);
  22630. EXPECT_TRUE(sk_X509_NAME_num(ca_list) > 0);
  22631. }
  22632. #endif
  22633. // ============================================================================
  22634. // MbedTLS-Specific Tests
  22635. // ============================================================================
  22636. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  22637. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  22638. using namespace httplib::tls;
  22639. // Track if callback was invoked
  22640. bool callback_invoked = false;
  22641. // The callback receives void* ctx which is actually MbedTlsContext*
  22642. // We can access the mbedtls_ssl_config via the context
  22643. auto setup_callback = [&callback_invoked](void *ctx) {
  22644. callback_invoked = true;
  22645. // Cast to MbedTlsContext* to access the ssl config
  22646. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  22647. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  22648. // Use static variables to hold certificate data (simplified for test)
  22649. static mbedtls_x509_crt own_cert;
  22650. static mbedtls_pk_context own_key;
  22651. static mbedtls_x509_crt ca_chain;
  22652. static bool initialized = false;
  22653. if (!initialized) {
  22654. mbedtls_x509_crt_init(&own_cert);
  22655. mbedtls_pk_init(&own_key);
  22656. mbedtls_x509_crt_init(&ca_chain);
  22657. // Load server certificate
  22658. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  22659. return false;
  22660. }
  22661. // Load server private key.
  22662. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  22663. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  22664. #if MBEDTLS_VERSION_MAJOR == 3
  22665. ,
  22666. mbedtls_ctr_drbg_random, nullptr
  22667. #endif
  22668. ) != 0) {
  22669. return false;
  22670. }
  22671. // Load CA chain for client verification
  22672. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  22673. return false;
  22674. }
  22675. initialized = true;
  22676. }
  22677. // Configure the SSL config
  22678. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  22679. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  22680. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  22681. // Set minimum TLS version using mbedTLS native API
  22682. #if MBEDTLS_VERSION_MAJOR >= 3
  22683. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  22684. #else
  22685. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  22686. MBEDTLS_SSL_MINOR_VERSION_3);
  22687. #endif
  22688. return true;
  22689. };
  22690. SSLServer svr(setup_callback);
  22691. ASSERT_TRUE(svr.is_valid());
  22692. ASSERT_TRUE(callback_invoked);
  22693. svr.Get("/test", [&](const Request &req, Response &res) {
  22694. res.set_content("test", "text/plain");
  22695. auto cert = req.peer_cert();
  22696. ASSERT_TRUE(static_cast<bool>(cert));
  22697. auto common_name = cert.subject_cn();
  22698. EXPECT_EQ("Common Name", common_name);
  22699. });
  22700. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22701. auto se = detail::scope_exit([&] {
  22702. svr.stop();
  22703. t.join();
  22704. ASSERT_FALSE(svr.is_running());
  22705. });
  22706. svr.wait_until_ready();
  22707. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  22708. cli.enable_server_certificate_verification(false);
  22709. cli.set_connection_timeout(30);
  22710. auto res = cli.Get("/test");
  22711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22712. ASSERT_EQ(StatusCode::OK_200, res->status);
  22713. }
  22714. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  22715. // context (owning mbedtls_ssl_config) before shutting down a still-open
  22716. // keep-alive SSL session, which reads through that config in
  22717. // mbedtls_ssl_close_notify.
  22718. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  22719. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  22720. ASSERT_TRUE(svr.is_valid());
  22721. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  22722. res.set_content("test", "text/plain");
  22723. });
  22724. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  22725. auto se = detail::scope_exit([&] {
  22726. svr.stop();
  22727. t.join();
  22728. ASSERT_FALSE(svr.is_running());
  22729. });
  22730. svr.wait_until_ready();
  22731. {
  22732. SSLClient cli(HOST, PORT);
  22733. cli.enable_server_certificate_verification(false);
  22734. cli.set_keep_alive(true);
  22735. auto res = cli.Get("/test");
  22736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22737. ASSERT_EQ(StatusCode::OK_200, res->status);
  22738. // cli is destructed here with the keep-alive SSL session still open.
  22739. }
  22740. }
  22741. #endif
  22742. // WebSocket Tests
  22743. TEST(WebSocketTest, RSVBitsMustBeZero) {
  22744. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  22745. // defining the meaning of these bits has been negotiated.
  22746. auto make_frame = [](uint8_t first_byte) {
  22747. std::string frame;
  22748. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  22749. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  22750. frame += "Hello";
  22751. return frame;
  22752. };
  22753. // RSV1 set (0x40)
  22754. {
  22755. detail::BufferStream strm;
  22756. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  22757. ws::Opcode opcode;
  22758. std::string payload;
  22759. bool fin;
  22760. EXPECT_EQ(
  22761. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22762. ws::impl::FrameRead::Fail);
  22763. }
  22764. // RSV2 set (0x20)
  22765. {
  22766. detail::BufferStream strm;
  22767. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  22768. ws::Opcode opcode;
  22769. std::string payload;
  22770. bool fin;
  22771. EXPECT_EQ(
  22772. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22773. ws::impl::FrameRead::Fail);
  22774. }
  22775. // RSV3 set (0x10)
  22776. {
  22777. detail::BufferStream strm;
  22778. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  22779. ws::Opcode opcode;
  22780. std::string payload;
  22781. bool fin;
  22782. EXPECT_EQ(
  22783. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22784. ws::impl::FrameRead::Fail);
  22785. }
  22786. // No RSV bits set - should succeed
  22787. {
  22788. detail::BufferStream strm;
  22789. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  22790. ws::Opcode opcode;
  22791. std::string payload;
  22792. bool fin;
  22793. EXPECT_EQ(
  22794. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22795. ws::impl::FrameRead::Ok);
  22796. EXPECT_EQ(ws::Opcode::Text, opcode);
  22797. EXPECT_EQ("Hello", payload);
  22798. EXPECT_TRUE(fin);
  22799. }
  22800. }
  22801. TEST(WebSocketTest, ControlFrameValidation) {
  22802. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  22803. // payload length <= 125.
  22804. // Ping with FIN=0 - must be rejected
  22805. {
  22806. detail::BufferStream strm;
  22807. std::string frame;
  22808. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  22809. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22810. strm.write(frame.data(), frame.size());
  22811. ws::Opcode opcode;
  22812. std::string payload;
  22813. bool fin;
  22814. EXPECT_EQ(
  22815. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22816. ws::impl::FrameRead::Fail);
  22817. }
  22818. // Close with FIN=0 - must be rejected
  22819. {
  22820. detail::BufferStream strm;
  22821. std::string frame;
  22822. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  22823. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  22824. strm.write(frame.data(), frame.size());
  22825. ws::Opcode opcode;
  22826. std::string payload;
  22827. bool fin;
  22828. EXPECT_EQ(
  22829. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22830. ws::impl::FrameRead::Fail);
  22831. }
  22832. // Ping with payload_len=126 (extended length) - must be rejected
  22833. {
  22834. detail::BufferStream strm;
  22835. std::string frame;
  22836. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22837. frame += static_cast<char>(126); // payload_len=126 (>125)
  22838. frame += static_cast<char>(0x00); // extended length high byte
  22839. frame += static_cast<char>(126); // extended length low byte
  22840. frame += std::string(126, 'x');
  22841. strm.write(frame.data(), frame.size());
  22842. ws::Opcode opcode;
  22843. std::string payload;
  22844. bool fin;
  22845. EXPECT_EQ(
  22846. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22847. ws::impl::FrameRead::Fail);
  22848. }
  22849. // Ping with FIN=1 and payload_len=125 - should succeed
  22850. {
  22851. detail::BufferStream strm;
  22852. std::string frame;
  22853. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  22854. frame += static_cast<char>(125); // payload_len=125
  22855. frame += std::string(125, 'x');
  22856. strm.write(frame.data(), frame.size());
  22857. ws::Opcode opcode;
  22858. std::string payload;
  22859. bool fin;
  22860. EXPECT_EQ(
  22861. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22862. ws::impl::FrameRead::Ok);
  22863. EXPECT_EQ(ws::Opcode::Ping, opcode);
  22864. EXPECT_EQ(125u, payload.size());
  22865. EXPECT_TRUE(fin);
  22866. }
  22867. }
  22868. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  22869. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  22870. // length MUST be 0.
  22871. // MSB set - must be rejected
  22872. {
  22873. detail::BufferStream strm;
  22874. std::string frame;
  22875. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22876. frame += static_cast<char>(127); // 64-bit extended length
  22877. frame += static_cast<char>(0x80); // MSB set (invalid)
  22878. frame += std::string(7, '\0'); // remaining 7 bytes of length
  22879. strm.write(frame.data(), frame.size());
  22880. ws::Opcode opcode;
  22881. std::string payload;
  22882. bool fin;
  22883. EXPECT_EQ(
  22884. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22885. ws::impl::FrameRead::Fail);
  22886. }
  22887. // MSB clear - should pass length parsing (will be rejected by max_len,
  22888. // but that's a different check; use a small length to verify)
  22889. {
  22890. detail::BufferStream strm;
  22891. std::string frame;
  22892. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  22893. frame += static_cast<char>(127); // 64-bit extended length
  22894. frame += std::string(7, '\0'); // high bytes = 0
  22895. frame += static_cast<char>(0x03); // length = 3
  22896. frame += "abc";
  22897. strm.write(frame.data(), frame.size());
  22898. ws::Opcode opcode;
  22899. std::string payload;
  22900. bool fin;
  22901. EXPECT_EQ(
  22902. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  22903. ws::impl::FrameRead::Ok);
  22904. EXPECT_EQ(ws::Opcode::Text, opcode);
  22905. EXPECT_EQ("abc", payload);
  22906. }
  22907. }
  22908. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  22909. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  22910. // Valid UTF-8
  22911. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  22912. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  22913. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  22914. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  22915. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  22916. // Invalid UTF-8
  22917. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  22918. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  22919. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  22920. EXPECT_FALSE(
  22921. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  22922. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  22923. }
  22924. TEST(WebSocketTest, ConnectAndDisconnect) {
  22925. Server svr;
  22926. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  22927. std::string msg;
  22928. while (ws.read(msg)) {}
  22929. });
  22930. auto port = svr.bind_to_any_port(HOST);
  22931. std::thread t([&]() { svr.listen_after_bind(); });
  22932. svr.wait_until_ready();
  22933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  22934. auto res = client.connect();
  22935. ASSERT_TRUE(res);
  22936. EXPECT_EQ(Error::Success, res.error());
  22937. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  22938. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  22939. EXPECT_TRUE(client.is_open());
  22940. client.close();
  22941. EXPECT_FALSE(client.is_open());
  22942. svr.stop();
  22943. t.join();
  22944. }
  22945. TEST(WebSocketTest, ValidURL) {
  22946. ws::WebSocketClient ws1("ws://localhost:8080/path");
  22947. EXPECT_TRUE(ws1.is_valid());
  22948. ws::WebSocketClient ws2("ws://example.com/path");
  22949. EXPECT_TRUE(ws2.is_valid());
  22950. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  22951. EXPECT_TRUE(ws3.is_valid());
  22952. #ifdef CPPHTTPLIB_SSL_ENABLED
  22953. ws::WebSocketClient wss1("wss://example.com/path");
  22954. EXPECT_TRUE(wss1.is_valid());
  22955. ws::WebSocketClient wss2("wss://example.com:443/path");
  22956. EXPECT_TRUE(wss2.is_valid());
  22957. #endif
  22958. }
  22959. TEST(WebSocketTest, InvalidURL) {
  22960. // No scheme
  22961. ws::WebSocketClient ws1("localhost:8080/path");
  22962. EXPECT_FALSE(ws1.is_valid());
  22963. // No path
  22964. ws::WebSocketClient ws2("ws://localhost:8080");
  22965. EXPECT_FALSE(ws2.is_valid());
  22966. // Empty string
  22967. ws::WebSocketClient ws3("");
  22968. EXPECT_FALSE(ws3.is_valid());
  22969. // Missing host
  22970. ws::WebSocketClient ws4("ws://:8080/path");
  22971. EXPECT_FALSE(ws4.is_valid());
  22972. // Port number overflow — should not crash
  22973. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  22974. EXPECT_FALSE(ws5.is_valid());
  22975. // Port out of range
  22976. ws::WebSocketClient ws6("ws://localhost:99999/path");
  22977. EXPECT_FALSE(ws6.is_valid());
  22978. }
  22979. TEST(WebSocketTest, UnsupportedScheme) {
  22980. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  22981. ws::WebSocketClient ws1("http://localhost:8080/path");
  22982. EXPECT_FALSE(ws1.is_valid());
  22983. ws::WebSocketClient ws2("https://localhost:8080/path");
  22984. EXPECT_FALSE(ws2.is_valid());
  22985. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  22986. EXPECT_FALSE(ws3.is_valid());
  22987. #else
  22988. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  22989. std::invalid_argument);
  22990. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  22991. std::invalid_argument);
  22992. #endif
  22993. }
  22994. TEST(WebSocketTest, ConnectWhenInvalid) {
  22995. ws::WebSocketClient ws("not a valid url");
  22996. EXPECT_FALSE(ws.is_valid());
  22997. auto res = ws.connect();
  22998. EXPECT_FALSE(res);
  22999. EXPECT_EQ(Error::Connection, res.error());
  23000. EXPECT_EQ(-1, res.status());
  23001. }
  23002. TEST(WebSocketTest, ConnectRefusedReportsError) {
  23003. // Grab a port that is free, then close it again so nothing listens there
  23004. Server svr;
  23005. auto port = svr.bind_to_any_port(HOST);
  23006. svr.stop();
  23007. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23008. auto res = client.connect();
  23009. ASSERT_FALSE(res);
  23010. EXPECT_EQ(Error::Connection, res.error());
  23011. EXPECT_EQ(-1, res.status());
  23012. }
  23013. TEST(WebSocketTest, DefaultPort) {
  23014. ws::WebSocketClient ws1("ws://example.com/path");
  23015. EXPECT_TRUE(ws1.is_valid());
  23016. // ws:// defaults to port 80 (verified by successful parse)
  23017. #ifdef CPPHTTPLIB_SSL_ENABLED
  23018. ws::WebSocketClient ws2("wss://example.com/path");
  23019. EXPECT_TRUE(ws2.is_valid());
  23020. // wss:// defaults to port 443 (verified by successful parse)
  23021. #endif
  23022. }
  23023. TEST(WebSocketTest, IPv6LiteralAddress) {
  23024. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  23025. EXPECT_TRUE(ws1.is_valid());
  23026. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  23027. EXPECT_TRUE(ws2.is_valid());
  23028. }
  23029. TEST(WebSocketTest, ComplexPath) {
  23030. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  23031. EXPECT_TRUE(ws1.is_valid());
  23032. ws::WebSocketClient ws2("ws://localhost:8080/");
  23033. EXPECT_TRUE(ws2.is_valid());
  23034. }
  23035. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  23036. Server svr;
  23037. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23038. std::string msg;
  23039. while (ws.read(msg)) {}
  23040. });
  23041. auto port = svr.bind_to_any_port(HOST);
  23042. std::thread t([&]() { svr.listen_after_bind(); });
  23043. svr.wait_until_ready();
  23044. auto another_host = "example.com";
  23045. auto wrong_ip = "192.0.2.1";
  23046. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23047. client.set_hostname_addr_map({{another_host, wrong_ip}});
  23048. ASSERT_TRUE(client.connect());
  23049. EXPECT_TRUE(client.is_open());
  23050. client.close();
  23051. svr.stop();
  23052. t.join();
  23053. }
  23054. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  23055. Server svr;
  23056. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23057. std::string msg;
  23058. while (ws.read(msg)) {}
  23059. });
  23060. auto port = svr.bind_to_any_port(HOST);
  23061. std::thread t([&]() { svr.listen_after_bind(); });
  23062. svr.wait_until_ready();
  23063. auto wrong_ip = "192.0.2.1";
  23064. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23065. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  23066. client.set_connection_timeout(1);
  23067. client.set_read_timeout(1);
  23068. client.set_write_timeout(1);
  23069. EXPECT_FALSE(client.connect());
  23070. EXPECT_FALSE(client.is_open());
  23071. svr.stop();
  23072. t.join();
  23073. }
  23074. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  23075. // A mapped value that is not an IP literal must be resolved. HOST resolves
  23076. // from the hosts file, so this test needs no external DNS. "target.invalid"
  23077. // (RFC 6761) is only a map key and the Host header value.
  23078. auto host = "target.invalid";
  23079. Server svr;
  23080. std::string received_host;
  23081. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23082. received_host = req.get_header_value("Host");
  23083. std::string msg;
  23084. while (ws.read(msg)) {}
  23085. });
  23086. auto port = svr.bind_to_any_port(HOST);
  23087. std::thread t([&]() { svr.listen_after_bind(); });
  23088. // ASSERT_* below returns from the test body, which would leave t joinable
  23089. // and make ~thread call std::terminate.
  23090. auto se = detail::scope_exit([&] {
  23091. svr.stop();
  23092. if (t.joinable()) { t.join(); }
  23093. });
  23094. svr.wait_until_ready();
  23095. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  23096. std::to_string(port) + "/ws");
  23097. client.set_hostname_addr_map({{host, HOST}});
  23098. ASSERT_TRUE(client.connect());
  23099. EXPECT_TRUE(client.is_open());
  23100. client.close();
  23101. svr.stop();
  23102. t.join();
  23103. // The mapping only redirects the connection; the identity stays host_.
  23104. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  23105. }
  23106. class WebSocketIntegrationTest : public ::testing::Test {
  23107. protected:
  23108. void SetUp() override {
  23109. server_ = httplib::detail::make_unique<Server>();
  23110. setup_server();
  23111. start_server();
  23112. }
  23113. void TearDown() override {
  23114. server_->stop();
  23115. if (server_thread_.joinable()) { server_thread_.join(); }
  23116. }
  23117. void setup_server() {
  23118. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  23119. std::string msg;
  23120. ws::ReadResult ret;
  23121. while ((ret = ws.read(msg))) {
  23122. if (ret == ws::Binary) {
  23123. ws.send(msg.data(), msg.size());
  23124. } else {
  23125. ws.send(msg);
  23126. }
  23127. }
  23128. });
  23129. server_->WebSocket("/ws-echo-string",
  23130. [](const Request &, ws::WebSocket &ws) {
  23131. std::string msg;
  23132. while (ws.read(msg)) {
  23133. ws.send("echo: " + msg);
  23134. }
  23135. });
  23136. server_->WebSocket(
  23137. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  23138. // Echo back request metadata
  23139. ws.send("path:" + req.path);
  23140. ws.send("header:" + req.get_header_value("X-Test-Header"));
  23141. std::string msg;
  23142. while (ws.read(msg)) {}
  23143. });
  23144. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  23145. std::string msg;
  23146. ws.read(msg); // wait for a message
  23147. ws.close();
  23148. });
  23149. server_->WebSocket("/ws-close-status",
  23150. [](const Request &, ws::WebSocket &ws) {
  23151. std::string msg;
  23152. ws.read(msg); // wait for a message
  23153. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  23154. });
  23155. server_->WebSocket(
  23156. "/ws-subprotocol",
  23157. [](const Request &, ws::WebSocket &ws) {
  23158. std::string msg;
  23159. while (ws.read(msg)) {
  23160. ws.send(msg);
  23161. }
  23162. },
  23163. [](const std::vector<std::string> &protocols) -> std::string {
  23164. for (const auto &p : protocols) {
  23165. if (p == "graphql-ws") { return p; }
  23166. }
  23167. return "";
  23168. });
  23169. server_->WebSocket(
  23170. "/ws-subprotocol-unoffered",
  23171. [](const Request &, ws::WebSocket &ws) {
  23172. std::string msg;
  23173. while (ws.read(msg)) {
  23174. ws.send(msg);
  23175. }
  23176. },
  23177. [](const std::vector<std::string> &) -> std::string {
  23178. return "admin";
  23179. });
  23180. }
  23181. void start_server() {
  23182. port_ = server_->bind_to_any_port(HOST);
  23183. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  23184. server_->wait_until_ready();
  23185. }
  23186. std::unique_ptr<Server> server_;
  23187. std::thread server_thread_;
  23188. int port_ = 0;
  23189. };
  23190. TEST_F(WebSocketIntegrationTest, TextEcho) {
  23191. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23192. "/ws-echo");
  23193. ASSERT_TRUE(client.connect());
  23194. ASSERT_TRUE(client.is_open());
  23195. ASSERT_TRUE(client.send("Hello WebSocket"));
  23196. std::string msg;
  23197. EXPECT_EQ(ws::Text, client.read(msg));
  23198. EXPECT_EQ("Hello WebSocket", msg);
  23199. client.close();
  23200. }
  23201. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  23202. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23203. "/ws-echo");
  23204. ASSERT_TRUE(client.connect());
  23205. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  23206. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  23207. std::string msg;
  23208. EXPECT_EQ(ws::Binary, client.read(msg));
  23209. EXPECT_EQ(binary_data, msg);
  23210. client.close();
  23211. }
  23212. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  23213. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23214. "/ws-echo");
  23215. ASSERT_TRUE(client.connect());
  23216. for (int i = 0; i < 10; i++) {
  23217. auto text = "message " + std::to_string(i);
  23218. ASSERT_TRUE(client.send(text));
  23219. std::string msg;
  23220. ASSERT_TRUE(client.read(msg));
  23221. EXPECT_EQ(text, msg);
  23222. }
  23223. client.close();
  23224. }
  23225. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  23226. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23227. "/ws-close");
  23228. ASSERT_TRUE(client.connect());
  23229. // Send a message to trigger the server to close
  23230. ASSERT_TRUE(client.send("trigger close"));
  23231. // The server will close, so read should return false
  23232. std::string msg;
  23233. EXPECT_FALSE(client.read(msg));
  23234. EXPECT_FALSE(client.is_open());
  23235. }
  23236. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  23237. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23238. "/ws-echo");
  23239. ASSERT_TRUE(client.connect());
  23240. // 128KB message
  23241. std::string large_data(128 * 1024, 'X');
  23242. ASSERT_TRUE(client.send(large_data));
  23243. std::string msg;
  23244. ASSERT_TRUE(client.read(msg));
  23245. EXPECT_EQ(large_data, msg);
  23246. client.close();
  23247. }
  23248. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  23249. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23250. "/ws-echo");
  23251. ASSERT_TRUE(client.connect());
  23252. const int num_threads = 4;
  23253. std::vector<std::thread> threads;
  23254. std::atomic<int> send_count{0};
  23255. for (int t = 0; t < num_threads; t++) {
  23256. threads.emplace_back([&client, &send_count, t]() {
  23257. for (int i = 0; i < 5; i++) {
  23258. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  23259. if (client.send(text)) { send_count++; }
  23260. }
  23261. });
  23262. }
  23263. for (auto &th : threads) {
  23264. th.join();
  23265. }
  23266. int received = 0;
  23267. std::string msg;
  23268. while (received < send_count.load()) {
  23269. if (!client.read(msg)) { break; }
  23270. received++;
  23271. }
  23272. EXPECT_EQ(send_count.load(), received);
  23273. client.close();
  23274. }
  23275. TEST_F(WebSocketIntegrationTest, ReadString) {
  23276. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23277. "/ws-echo-string");
  23278. ASSERT_TRUE(client.connect());
  23279. ASSERT_TRUE(client.send("hello"));
  23280. std::string msg;
  23281. ASSERT_TRUE(client.read(msg));
  23282. EXPECT_EQ("echo: hello", msg);
  23283. ASSERT_TRUE(client.send("world"));
  23284. ASSERT_TRUE(client.read(msg));
  23285. EXPECT_EQ("echo: world", msg);
  23286. client.close();
  23287. }
  23288. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  23289. Headers headers = {{"X-Test-Header", "test-value"}};
  23290. ws::WebSocketClient client(
  23291. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  23292. ASSERT_TRUE(client.connect());
  23293. std::string msg;
  23294. ASSERT_TRUE(client.read(msg));
  23295. EXPECT_EQ("path:/ws-request-info", msg);
  23296. ASSERT_TRUE(client.read(msg));
  23297. EXPECT_EQ("header:test-value", msg);
  23298. client.close();
  23299. }
  23300. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  23301. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23302. "/ws-echo");
  23303. client.set_read_timeout(1, 0); // 1 second
  23304. ASSERT_TRUE(client.connect());
  23305. // Don't send anything — server echo handler waits for a message, so read()
  23306. // should time out. The connection survives it: nothing was consumed.
  23307. std::string msg;
  23308. EXPECT_EQ(client.read(msg), ws::Timeout);
  23309. EXPECT_TRUE(client.is_open());
  23310. // And it is still usable afterwards.
  23311. EXPECT_TRUE(client.send("after timeout"));
  23312. EXPECT_EQ(client.read(msg), ws::Text);
  23313. EXPECT_EQ(msg, "after timeout");
  23314. }
  23315. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  23316. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23317. "/ws-echo");
  23318. client.set_read_timeout(1, 0);
  23319. ASSERT_TRUE(client.connect());
  23320. ASSERT_TRUE(client.send("first"));
  23321. std::string msg;
  23322. ASSERT_EQ(client.read(msg), ws::Text);
  23323. ASSERT_EQ(msg, "first");
  23324. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  23325. // not be used with a read timeout: it would reprocess the previous message.
  23326. EXPECT_EQ(client.read(msg), ws::Timeout);
  23327. EXPECT_EQ(msg, "first");
  23328. }
  23329. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  23330. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23331. "/ws-echo");
  23332. ASSERT_TRUE(client.connect());
  23333. // Setting it once the connection is open reaches the live stream, not just
  23334. // the seed for the next connect().
  23335. client.set_read_timeout(1, 0);
  23336. std::string msg;
  23337. EXPECT_EQ(client.read(msg), ws::Timeout);
  23338. EXPECT_TRUE(client.is_open());
  23339. }
  23340. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  23341. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23342. "/ws-echo");
  23343. client.set_read_timeout(5, 0);
  23344. ASSERT_TRUE(client.connect());
  23345. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23346. // The server should reject it and close the connection.
  23347. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  23348. client.send(oversized);
  23349. // The server's read() should have failed due to payload limit,
  23350. // so our read() should return false (connection closed).
  23351. std::string msg;
  23352. EXPECT_FALSE(client.read(msg));
  23353. }
  23354. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  23355. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23356. "/ws-echo");
  23357. client.set_read_timeout(10, 0);
  23358. ASSERT_TRUE(client.connect());
  23359. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  23360. // This should succeed.
  23361. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  23362. ASSERT_TRUE(client.send(at_limit));
  23363. std::string msg;
  23364. ASSERT_TRUE(client.read(msg));
  23365. EXPECT_EQ(at_limit.size(), msg.size());
  23366. client.close();
  23367. }
  23368. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  23369. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23370. "/nonexistent");
  23371. auto res = client.connect();
  23372. EXPECT_FALSE(res);
  23373. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  23374. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  23375. EXPECT_FALSE(client.is_open());
  23376. }
  23377. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  23378. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23379. "/ws-echo");
  23380. ASSERT_TRUE(client.connect());
  23381. ASSERT_TRUE(client.send(""));
  23382. std::string msg;
  23383. EXPECT_EQ(ws::Text, client.read(msg));
  23384. EXPECT_EQ("", msg);
  23385. client.close();
  23386. }
  23387. TEST_F(WebSocketIntegrationTest, Reconnect) {
  23388. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23389. "/ws-echo");
  23390. // First connection
  23391. ASSERT_TRUE(client.connect());
  23392. ASSERT_TRUE(client.send("first"));
  23393. std::string msg;
  23394. ASSERT_TRUE(client.read(msg));
  23395. EXPECT_EQ("first", msg);
  23396. client.close();
  23397. EXPECT_FALSE(client.is_open());
  23398. // Reconnect using the same client object
  23399. ASSERT_TRUE(client.connect());
  23400. ASSERT_TRUE(client.is_open());
  23401. ASSERT_TRUE(client.send("second"));
  23402. ASSERT_TRUE(client.read(msg));
  23403. EXPECT_EQ("second", msg);
  23404. client.close();
  23405. }
  23406. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  23407. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23408. "/ws-close-status");
  23409. ASSERT_TRUE(client.connect());
  23410. // Trigger the server to close with GoingAway status
  23411. ASSERT_TRUE(client.send("trigger"));
  23412. // read() should return false after receiving the close frame
  23413. std::string msg;
  23414. EXPECT_FALSE(client.read(msg));
  23415. EXPECT_FALSE(client.is_open());
  23416. }
  23417. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  23418. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23419. "/ws-echo");
  23420. ASSERT_TRUE(client.connect());
  23421. client.close(ws::CloseStatus::GoingAway, "client leaving");
  23422. EXPECT_FALSE(client.is_open());
  23423. }
  23424. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  23425. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  23426. ws::WebSocketClient client(
  23427. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23428. ASSERT_TRUE(client.connect());
  23429. // Server should have selected graphql-ws
  23430. EXPECT_EQ("graphql-ws", client.subprotocol());
  23431. client.close();
  23432. }
  23433. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  23434. Headers headers;
  23435. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  23436. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  23437. ws::WebSocketClient client(
  23438. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23439. ASSERT_TRUE(client.connect());
  23440. // The offer on the second field line counts too, so graphql-ws is selected
  23441. EXPECT_EQ("graphql-ws", client.subprotocol());
  23442. client.close();
  23443. }
  23444. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  23445. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  23446. ws::WebSocketClient client(
  23447. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  23448. ASSERT_TRUE(client.connect());
  23449. // Server should not have selected any subprotocol
  23450. EXPECT_TRUE(client.subprotocol().empty());
  23451. client.close();
  23452. }
  23453. TEST_F(WebSocketIntegrationTest, SubProtocolSelectorReturnsUnoffered) {
  23454. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  23455. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23456. "/ws-subprotocol-unoffered",
  23457. headers);
  23458. ASSERT_TRUE(client.connect());
  23459. EXPECT_TRUE(client.subprotocol().empty());
  23460. client.close();
  23461. }
  23462. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  23463. // Connect without requesting any subprotocol
  23464. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23465. "/ws-subprotocol");
  23466. ASSERT_TRUE(client.connect());
  23467. EXPECT_TRUE(client.subprotocol().empty());
  23468. client.close();
  23469. }
  23470. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  23471. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23472. "/ws-echo");
  23473. client.set_tcp_nodelay(true);
  23474. client.set_connection_timeout(3, 0);
  23475. bool socket_options_called = false;
  23476. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  23477. ASSERT_TRUE(client.connect());
  23478. ASSERT_TRUE(client.is_open());
  23479. EXPECT_TRUE(socket_options_called);
  23480. ASSERT_TRUE(client.send("hello"));
  23481. std::string msg;
  23482. auto result = client.read(msg);
  23483. EXPECT_EQ(result, ws::ReadResult::Text);
  23484. EXPECT_EQ(msg, "hello");
  23485. client.close();
  23486. }
  23487. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  23488. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  23489. "/ws-echo");
  23490. client.set_connection_timeout(std::chrono::seconds(3));
  23491. client.set_write_timeout(std::chrono::seconds(3));
  23492. // A sub-second remainder exercises the seconds/microseconds split.
  23493. client.set_read_timeout(std::chrono::milliseconds(1500));
  23494. ASSERT_TRUE(client.connect());
  23495. auto start = std::chrono::steady_clock::now();
  23496. std::string msg;
  23497. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  23498. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  23499. std::chrono::steady_clock::now() - start)
  23500. .count();
  23501. // Above 1s so that dropping the microseconds half of the split fails here.
  23502. // Ignoring the setter altogether would not reach this line at all: a client
  23503. // waits forever by default.
  23504. EXPECT_GE(elapsed, 1400);
  23505. EXPECT_LT(elapsed, 30000);
  23506. }
  23507. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  23508. Server svr;
  23509. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23510. if (!req.has_header("Authorization")) {
  23511. res.status = StatusCode::Unauthorized_401;
  23512. res.set_content("Unauthorized", "text/plain");
  23513. return Server::HandlerResponse::Handled;
  23514. }
  23515. return Server::HandlerResponse::Unhandled;
  23516. });
  23517. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23518. std::string msg;
  23519. while (ws.read(msg)) {
  23520. ws.send(msg);
  23521. }
  23522. });
  23523. auto port = svr.bind_to_any_port("localhost");
  23524. std::thread t([&]() { svr.listen_after_bind(); });
  23525. svr.wait_until_ready();
  23526. // Without Authorization header - should be rejected before upgrade
  23527. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  23528. EXPECT_FALSE(client1.connect());
  23529. // The rejection is framed like any other HTTP response
  23530. {
  23531. Client cli("localhost", port);
  23532. Headers headers = {{"Upgrade", "websocket"},
  23533. {"Connection", "Upgrade"},
  23534. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23535. {"Sec-WebSocket-Version", "13"}};
  23536. auto res = cli.Get("/ws", headers);
  23537. ASSERT_TRUE(res);
  23538. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23539. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23540. EXPECT_EQ("Unauthorized", res->body);
  23541. }
  23542. // With Authorization header - should succeed
  23543. Headers headers = {{"Authorization", "Bearer token123"}};
  23544. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  23545. headers);
  23546. ASSERT_TRUE(client2.connect());
  23547. ASSERT_TRUE(client2.send("hello"));
  23548. std::string msg;
  23549. ASSERT_TRUE(client2.read(msg));
  23550. EXPECT_EQ("hello", msg);
  23551. client2.close();
  23552. svr.stop();
  23553. t.join();
  23554. }
  23555. TEST(WebSocketPreRoutingTest, RunsOnceForUnmatchedUpgrade) {
  23556. Server svr;
  23557. std::atomic<int> pre_routing_calls{0};
  23558. std::atomic<int> pre_request_calls{0};
  23559. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  23560. pre_routing_calls++;
  23561. if (req.path == "/handled") {
  23562. res.set_content("handled", "text/plain");
  23563. return Server::HandlerResponse::Handled;
  23564. }
  23565. return Server::HandlerResponse::Unhandled;
  23566. });
  23567. svr.set_pre_request_handler([&](const Request &, Response &) {
  23568. pre_request_calls++;
  23569. return Server::HandlerResponse::Unhandled;
  23570. });
  23571. svr.Get("/http", [](const Request &, Response &res) {
  23572. res.set_content("http", "text/plain");
  23573. });
  23574. svr.WebSocket("/ws",
  23575. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23576. auto port = svr.bind_to_any_port("localhost");
  23577. std::thread t([&]() { svr.listen_after_bind(); });
  23578. auto se = detail::scope_exit([&] {
  23579. svr.stop();
  23580. t.join();
  23581. });
  23582. svr.wait_until_ready();
  23583. Headers upgrade = {{"Upgrade", "websocket"},
  23584. {"Connection", "Upgrade"},
  23585. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23586. {"Sec-WebSocket-Version", "13"}};
  23587. auto get = [&](const char *path) {
  23588. pre_routing_calls = 0;
  23589. return Client("localhost", port).Get(path, upgrade);
  23590. };
  23591. // No WebSocket route, but an HTTP one
  23592. auto res = get("/http");
  23593. ASSERT_TRUE(res);
  23594. EXPECT_EQ(StatusCode::OK_200, res->status);
  23595. EXPECT_EQ("http", res->body);
  23596. EXPECT_EQ(1, pre_routing_calls);
  23597. EXPECT_EQ(1, pre_request_calls);
  23598. // No route at all
  23599. res = get("/none");
  23600. ASSERT_TRUE(res);
  23601. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  23602. EXPECT_EQ(1, pre_routing_calls);
  23603. // Answered by the pre-routing handler
  23604. res = get("/handled");
  23605. ASSERT_TRUE(res);
  23606. EXPECT_EQ(StatusCode::OK_200, res->status);
  23607. EXPECT_EQ("handled", res->body);
  23608. EXPECT_EQ(1, pre_routing_calls);
  23609. // A WebSocket route
  23610. pre_routing_calls = 0;
  23611. pre_request_calls = 0;
  23612. {
  23613. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23614. "/ws");
  23615. ASSERT_TRUE(client.connect());
  23616. std::string msg;
  23617. ASSERT_TRUE(client.read(msg));
  23618. EXPECT_EQ("ws", msg);
  23619. client.close();
  23620. }
  23621. EXPECT_EQ(1, pre_routing_calls);
  23622. EXPECT_EQ(1, pre_request_calls);
  23623. }
  23624. // An upgrade request answered by a hook leaves its body unread, so that body
  23625. // must not be served as the next request on the connection.
  23626. TEST(WebSocketPreRoutingTest, AnsweredUpgradeBodyIsNotNextRequest) {
  23627. Server svr;
  23628. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  23629. if (req.path == "/pre-routing") {
  23630. res.set_content("pre-routing", "text/plain");
  23631. return Server::HandlerResponse::Handled;
  23632. }
  23633. return Server::HandlerResponse::Unhandled;
  23634. });
  23635. svr.set_pre_request_handler([](const Request &req, Response &res) {
  23636. if (req.matched_route == "/pre-request") {
  23637. res.set_content("pre-request", "text/plain");
  23638. return Server::HandlerResponse::Handled;
  23639. }
  23640. return Server::HandlerResponse::Unhandled;
  23641. });
  23642. svr.Get("/smuggled", [](const Request &, Response &res) {
  23643. res.set_content("smuggled", "text/plain");
  23644. });
  23645. svr.WebSocket("/pre-request",
  23646. [](const Request &, ws::WebSocket &ws) { ws.send("ws"); });
  23647. auto port = svr.bind_to_any_port(HOST);
  23648. std::thread t([&]() { svr.listen_after_bind(); });
  23649. auto se = detail::scope_exit([&] {
  23650. svr.stop();
  23651. t.join();
  23652. });
  23653. svr.wait_until_ready();
  23654. const std::string body = "GET /smuggled HTTP/1.1\r\nHost: localhost\r\n\r\n";
  23655. for (auto path : {"/pre-routing", "/pre-request"}) {
  23656. std::string req = std::string("GET ") + path +
  23657. " HTTP/1.1\r\n"
  23658. "Host: localhost\r\n"
  23659. "Upgrade: websocket\r\n"
  23660. "Connection: Upgrade\r\n"
  23661. "Sec-WebSocket-Key: dGhlIHNhbXBsZSBub25jZQ==\r\n"
  23662. "Sec-WebSocket-Version: 13\r\n"
  23663. "Content-Length: " +
  23664. std::to_string(body.size()) + "\r\n\r\n" + body;
  23665. std::string res;
  23666. ASSERT_TRUE(send_request(5, req, &res, port));
  23667. EXPECT_EQ(0u, res.find("HTTP/1.1 200 OK\r\n")) << path;
  23668. EXPECT_NE(std::string::npos, res.find("Connection: close\r\n")) << path;
  23669. // Only one response, and the body was not served as a request
  23670. EXPECT_EQ(std::string::npos, res.find("HTTP/1.1", 1)) << path;
  23671. }
  23672. }
  23673. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  23674. Server svr;
  23675. std::atomic<int> pre_request_calls{0};
  23676. std::atomic<bool> route_matched{false};
  23677. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  23678. pre_request_calls++;
  23679. if (req.matched_route == "/ws/:id") { route_matched = true; }
  23680. if (req.get_header_value("Authorization") != "Bearer token123") {
  23681. res.status = StatusCode::Unauthorized_401;
  23682. res.set_content("Unauthorized", "text/plain");
  23683. return Server::HandlerResponse::Handled;
  23684. }
  23685. return Server::HandlerResponse::Unhandled;
  23686. });
  23687. std::atomic<bool> handler_called{false};
  23688. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  23689. handler_called = true;
  23690. ws.send(req.matched_route + " " + req.path_params.at("id"));
  23691. });
  23692. auto port = svr.bind_to_any_port("localhost");
  23693. std::thread t([&]() { svr.listen_after_bind(); });
  23694. svr.wait_until_ready();
  23695. // Without Authorization header - should be rejected before upgrade
  23696. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  23697. "/ws/1");
  23698. EXPECT_FALSE(client1.connect());
  23699. EXPECT_FALSE(handler_called);
  23700. EXPECT_EQ(1, pre_request_calls);
  23701. EXPECT_TRUE(route_matched);
  23702. // The rejection is an ordinary HTTP response, not a protocol switch
  23703. {
  23704. Client cli("localhost", port);
  23705. Headers headers = {{"Upgrade", "websocket"},
  23706. {"Connection", "Upgrade"},
  23707. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23708. {"Sec-WebSocket-Version", "13"}};
  23709. auto res = cli.Get("/ws/1", headers);
  23710. ASSERT_TRUE(res);
  23711. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  23712. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  23713. EXPECT_EQ("Unauthorized", res->body);
  23714. }
  23715. EXPECT_FALSE(handler_called);
  23716. // With Authorization header - should succeed
  23717. Headers headers = {{"Authorization", "Bearer token123"}};
  23718. ws::WebSocketClient client2(
  23719. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  23720. ASSERT_TRUE(client2.connect());
  23721. std::string msg;
  23722. ASSERT_TRUE(client2.read(msg));
  23723. EXPECT_EQ("/ws/:id 2", msg);
  23724. EXPECT_TRUE(handler_called);
  23725. client2.close();
  23726. svr.stop();
  23727. t.join();
  23728. }
  23729. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  23730. static Headers websocket_upgrade_headers() {
  23731. return {{"Upgrade", "websocket"},
  23732. {"Connection", "Upgrade"},
  23733. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  23734. {"Sec-WebSocket-Version", "13"},
  23735. {"Sec-WebSocket-Protocol", "chat"}};
  23736. }
  23737. TEST(WebSocketExceptionTest, HooksBeforeUpgradeReachExceptionHandler) {
  23738. Server svr;
  23739. svr.set_pre_routing_handler([](const Request &req, Response &) {
  23740. if (req.path == "/pre-routing") { throw std::runtime_error(req.path); }
  23741. return Server::HandlerResponse::Unhandled;
  23742. });
  23743. svr.set_pre_request_handler([](const Request &req, Response &) {
  23744. if (req.path == "/pre-request") { throw std::runtime_error(req.path); }
  23745. return Server::HandlerResponse::Unhandled;
  23746. });
  23747. svr.set_exception_handler(
  23748. [](const Request &, Response &res, std::exception_ptr ep) {
  23749. try {
  23750. std::rethrow_exception(ep);
  23751. } catch (std::exception &e) { res.set_content(e.what(), "text/plain"); }
  23752. });
  23753. auto handler = [](const Request &, ws::WebSocket &) {};
  23754. svr.WebSocket("/pre-routing", handler);
  23755. svr.WebSocket("/pre-request", handler);
  23756. svr.WebSocket("/sub-protocol", handler,
  23757. [](const std::vector<std::string> &) -> std::string {
  23758. throw std::runtime_error("/sub-protocol");
  23759. });
  23760. auto port = svr.bind_to_any_port(HOST);
  23761. ASSERT_GT(port, 0);
  23762. thread t = thread([&] { svr.listen_after_bind(); });
  23763. auto se = detail::scope_exit([&] {
  23764. svr.stop();
  23765. t.join();
  23766. ASSERT_FALSE(svr.is_running());
  23767. });
  23768. svr.wait_until_ready();
  23769. Client cli(HOST, port);
  23770. for (auto path : {"/pre-routing", "/pre-request", "/sub-protocol"}) {
  23771. auto res = cli.Get(path, websocket_upgrade_headers());
  23772. if (!res) {
  23773. ADD_FAILURE() << path << ": " << to_string(res.error());
  23774. continue;
  23775. }
  23776. EXPECT_EQ(StatusCode::InternalServerError_500, res->status) << path;
  23777. EXPECT_EQ(path, res->body);
  23778. }
  23779. }
  23780. TEST(WebSocketExceptionTest, HookBeforeUpgradeWithoutExceptionHandler) {
  23781. Server svr;
  23782. svr.set_pre_routing_handler(
  23783. [](const Request &, Response &) -> Server::HandlerResponse {
  23784. throw std::runtime_error("pre-routing");
  23785. });
  23786. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  23787. auto port = svr.bind_to_any_port(HOST);
  23788. ASSERT_GT(port, 0);
  23789. thread t = thread([&] { svr.listen_after_bind(); });
  23790. auto se = detail::scope_exit([&] {
  23791. svr.stop();
  23792. t.join();
  23793. ASSERT_FALSE(svr.is_running());
  23794. });
  23795. svr.wait_until_ready();
  23796. Client cli(HOST, port);
  23797. auto res = cli.Get("/ws", websocket_upgrade_headers());
  23798. ASSERT_TRUE(res) << to_string(res.error());
  23799. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  23800. }
  23801. #endif
  23802. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  23803. Server svr;
  23804. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  23805. // A read timeout is how a handler gets control back. Without it, a handler
  23806. // parked in read() can never write on the connection it is reading.
  23807. ws.set_read_timeout(std::chrono::milliseconds(100));
  23808. std::string msg;
  23809. while (ws.is_open()) {
  23810. auto r = ws.read(msg);
  23811. if (r == httplib::ws::Timeout) {
  23812. ws.send("tick");
  23813. continue;
  23814. }
  23815. if (r == httplib::ws::Fail) { break; }
  23816. ws.send(msg);
  23817. }
  23818. });
  23819. auto port = svr.bind_to_any_port("localhost");
  23820. std::thread t([&]() { svr.listen_after_bind(); });
  23821. svr.wait_until_ready();
  23822. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  23823. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  23824. ASSERT_TRUE(client.connect());
  23825. // The client sends nothing, so anything it receives came out of the
  23826. // handler's timeout path.
  23827. std::string msg;
  23828. ASSERT_EQ(client.read(msg), ws::Text);
  23829. EXPECT_EQ("tick", msg);
  23830. client.close();
  23831. svr.stop();
  23832. t.join();
  23833. }
  23834. // Stream::read may return fewer bytes than asked for. This is that contract at
  23835. // its worst -- one byte per call -- which is what a frame header straddling a
  23836. // read buffer's boundary looks like to the frame parser.
  23837. class WsByteAtATimeStream : public Stream {
  23838. public:
  23839. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  23840. bool is_readable() const override { return true; }
  23841. bool wait_readable() const override { return true; }
  23842. bool wait_writable() const override { return true; }
  23843. ssize_t read(char *ptr, size_t size) override {
  23844. if (size == 0 || pos_ >= data_.size()) { return 0; }
  23845. *ptr = data_[pos_++];
  23846. return 1;
  23847. }
  23848. ssize_t write(const char *, size_t size) override {
  23849. return static_cast<ssize_t>(size);
  23850. }
  23851. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  23852. ip = "127.0.0.1";
  23853. port = 0;
  23854. }
  23855. void get_local_ip_and_port(std::string &ip, int &port) const override {
  23856. ip = "127.0.0.1";
  23857. port = 0;
  23858. }
  23859. socket_t socket() const override { return INVALID_SOCKET; }
  23860. time_t duration() const override { return 0; }
  23861. private:
  23862. std::string data_;
  23863. size_t pos_ = 0;
  23864. };
  23865. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  23866. // The payload uses the 16-bit extended length, so the header, the length
  23867. // and the mask key are all multi-byte fields here. Each used to be read
  23868. // with a single read() call, which fails as soon as one is split. The
  23869. // payload is also a little over one read chunk, so it is read in two.
  23870. std::string body;
  23871. for (size_t i = 0; i < CPPHTTPLIB_RECV_BUFSIZ + 3; i++) {
  23872. body += static_cast<char>(i % 251);
  23873. }
  23874. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  23875. std::string frame;
  23876. frame += static_cast<char>(0x81); // FIN + Text
  23877. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  23878. frame += static_cast<char>(body.size() >> 8);
  23879. frame += static_cast<char>(body.size() & 0xff);
  23880. for (size_t i = 0; i < 4; i++) {
  23881. frame += static_cast<char>(mask[i]);
  23882. }
  23883. for (size_t i = 0; i < body.size(); i++) {
  23884. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  23885. }
  23886. WsByteAtATimeStream strm(frame);
  23887. ws::Opcode opcode;
  23888. std::string payload;
  23889. bool fin = false;
  23890. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  23891. /*expect_masked=*/true, body.size()),
  23892. ws::impl::FrameRead::Ok);
  23893. EXPECT_TRUE(fin);
  23894. EXPECT_EQ(opcode, ws::Opcode::Text);
  23895. EXPECT_EQ(payload, body);
  23896. }
  23897. TEST(WebSocketFrameTest, ZeroMaxLenMeansNoLimit) {
  23898. std::string body(2000, 'x');
  23899. std::string frame;
  23900. frame += static_cast<char>(0x82); // FIN + Binary
  23901. frame += static_cast<char>(126); // 16-bit length follows
  23902. frame += static_cast<char>(body.size() >> 8);
  23903. frame += static_cast<char>(body.size() & 0xff);
  23904. frame += body;
  23905. detail::BufferStream strm;
  23906. strm.write(frame.data(), frame.size());
  23907. ws::Opcode opcode;
  23908. std::string payload;
  23909. bool fin;
  23910. EXPECT_EQ(
  23911. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 0),
  23912. ws::impl::FrameRead::Ok);
  23913. EXPECT_EQ(body, payload);
  23914. }
  23915. TEST(WebSocketFrameTest, PayloadGrowsOnlyAsItArrives) {
  23916. // The header announces the largest payload allowed, and only 3 bytes of it
  23917. // ever arrive.
  23918. uint64_t len = CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH;
  23919. std::string frame;
  23920. frame += static_cast<char>(0x82); // FIN + Binary
  23921. frame += static_cast<char>(127); // 64-bit length follows
  23922. for (int shift = 56; shift >= 0; shift -= 8) {
  23923. frame += static_cast<char>((len >> shift) & 0xff);
  23924. }
  23925. frame += "abc";
  23926. detail::BufferStream strm;
  23927. strm.write(frame.data(), frame.size());
  23928. ws::Opcode opcode;
  23929. std::string payload;
  23930. bool fin;
  23931. EXPECT_EQ(
  23932. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false,
  23933. CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH),
  23934. ws::impl::FrameRead::Fail);
  23935. EXPECT_LT(payload.capacity(), 2 * CPPHTTPLIB_RECV_BUFSIZ);
  23936. }
  23937. TEST(WebSocketTest, QueryStringInHandshake) {
  23938. Server svr;
  23939. std::mutex mtx;
  23940. std::string received_target;
  23941. std::string received_token;
  23942. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23943. {
  23944. std::lock_guard<std::mutex> lock(mtx);
  23945. received_target = req.target;
  23946. if (req.has_param("token")) {
  23947. received_token = req.get_param_value("token");
  23948. }
  23949. }
  23950. std::string msg;
  23951. while (ws.read(msg)) {
  23952. ws.send(msg);
  23953. }
  23954. });
  23955. auto port = svr.bind_to_any_port("localhost");
  23956. std::thread t([&]() { svr.listen_after_bind(); });
  23957. svr.wait_until_ready();
  23958. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  23959. "/ws?token=ABC&session=123");
  23960. ASSERT_TRUE(client.connect());
  23961. // Round-trip ensures the handler has run and captured the request.
  23962. ASSERT_TRUE(client.send("hello"));
  23963. std::string msg;
  23964. ASSERT_TRUE(client.read(msg));
  23965. EXPECT_EQ("hello", msg);
  23966. client.close();
  23967. {
  23968. std::lock_guard<std::mutex> lock(mtx);
  23969. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  23970. EXPECT_EQ("ABC", received_token);
  23971. }
  23972. svr.stop();
  23973. t.join();
  23974. }
  23975. // Run a handshake against a throwaway server and hand the request the server
  23976. // received back to the caller, so tests can assert on the headers the client
  23977. // actually put on the wire.
  23978. static void capture_websocket_handshake_request(
  23979. const Headers &client_headers,
  23980. std::function<void(const Request &, int port)> verify) {
  23981. Server svr;
  23982. std::mutex mtx;
  23983. Request received;
  23984. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  23985. {
  23986. std::lock_guard<std::mutex> lock(mtx);
  23987. received = req;
  23988. }
  23989. std::string msg;
  23990. while (ws.read(msg)) {
  23991. ws.send(msg);
  23992. }
  23993. });
  23994. auto port = svr.bind_to_any_port("localhost");
  23995. std::thread t([&]() { svr.listen_after_bind(); });
  23996. auto se = detail::scope_exit([&] {
  23997. svr.stop();
  23998. t.join();
  23999. });
  24000. svr.wait_until_ready();
  24001. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  24002. client_headers);
  24003. ASSERT_TRUE(client.connect());
  24004. ASSERT_TRUE(client.send("hello"));
  24005. std::string msg;
  24006. ASSERT_TRUE(client.read(msg));
  24007. client.close();
  24008. {
  24009. std::lock_guard<std::mutex> lock(mtx);
  24010. verify(received, port);
  24011. }
  24012. }
  24013. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  24014. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  24015. // Non-default port must be present in the Host header. Default ports
  24016. // (80/443) are omitted; that logic is covered by
  24017. // MakeHostAndPortStringTest.
  24018. EXPECT_EQ("localhost:" + std::to_string(port),
  24019. req.get_header_value("Host"));
  24020. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  24021. req.get_header_value("User-Agent"));
  24022. EXPECT_FALSE(req.has_header("Accept"));
  24023. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  24024. EXPECT_FALSE(req.has_header("Content-Length"));
  24025. });
  24026. }
  24027. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  24028. capture_websocket_handshake_request(
  24029. {{"Host", "example.com"},
  24030. {"User-Agent", "custom-agent"},
  24031. {"X-Custom", "value"}},
  24032. [](const Request &req, int) {
  24033. EXPECT_EQ("example.com", req.get_header_value("Host"));
  24034. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  24035. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  24036. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  24037. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  24038. });
  24039. }
  24040. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  24041. capture_websocket_handshake_request(
  24042. {{"Upgrade", "bogus"},
  24043. {"Connection", "close"},
  24044. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  24045. {"Sec-WebSocket-Version", "8"}},
  24046. [](const Request &req, int) {
  24047. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  24048. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  24049. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  24050. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  24051. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  24052. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  24053. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  24054. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  24055. req.get_header_value("Sec-WebSocket-Key"));
  24056. });
  24057. }
  24058. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  24059. // A header the client refuses to send must abort the handshake before any
  24060. // part of it reaches the wire; a lone request line would otherwise sit in
  24061. // the peer's buffer as a truncated request.
  24062. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  24063. ASSERT_NE(INVALID_SOCKET, srv);
  24064. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  24065. sockaddr_in addr{};
  24066. addr.sin_family = AF_INET;
  24067. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  24068. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24069. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  24070. ASSERT_EQ(0, ::listen(srv, 1));
  24071. sockaddr_in bound{};
  24072. socklen_t bound_len = sizeof(bound);
  24073. ASSERT_EQ(
  24074. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  24075. auto port = ntohs(bound.sin_port);
  24076. ssize_t received = -1;
  24077. std::thread t([&] {
  24078. // Bound every blocking call so a regression fails the test with a bad
  24079. // value instead of hanging the suite.
  24080. fd_set rfds;
  24081. FD_ZERO(&rfds);
  24082. FD_SET(srv, &rfds);
  24083. timeval tv{5, 0};
  24084. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  24085. 0) {
  24086. return;
  24087. }
  24088. sockaddr_in cli_addr{};
  24089. socklen_t cli_len = sizeof(cli_addr);
  24090. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  24091. if (cli == INVALID_SOCKET) { return; }
  24092. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  24093. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24094. char buf[4096];
  24095. received = ::recv(cli, buf, sizeof(buf), 0);
  24096. });
  24097. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  24098. // connect() has already shut the socket down by the time it returns false,
  24099. // so the peer sees EOF without waiting for the client to be destroyed.
  24100. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  24101. {{"X-Bad", "a\r\nInjected: 1"}});
  24102. EXPECT_FALSE(client.connect());
  24103. t.join();
  24104. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  24105. EXPECT_EQ(0, received);
  24106. }
  24107. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  24108. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  24109. // contains "upgrade" as a substring is a different token and must not
  24110. // start a WebSocket handshake.
  24111. auto make_request = [](const std::vector<std::string> &connection_values) {
  24112. Request req;
  24113. req.method = "GET";
  24114. req.headers.emplace("Upgrade", "websocket");
  24115. for (const auto &value : connection_values) {
  24116. req.headers.emplace("Connection", value);
  24117. }
  24118. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24119. req.headers.emplace("Sec-WebSocket-Version", "13");
  24120. return req;
  24121. };
  24122. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  24123. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  24124. EXPECT_TRUE(
  24125. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  24126. EXPECT_TRUE(
  24127. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  24128. EXPECT_TRUE(
  24129. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  24130. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  24131. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  24132. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  24133. EXPECT_FALSE(
  24134. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  24135. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  24136. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24137. }
  24138. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  24139. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  24140. // asks recipients to match each protocol-name case-insensitively, and RFC
  24141. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  24142. // client naming websocket alongside another protocol, or on a second field
  24143. // line, is offering websocket; a value that merely contains "websocket" as a
  24144. // substring is a different protocol name and is not.
  24145. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  24146. Request req;
  24147. req.method = "GET";
  24148. for (const auto &value : upgrade_values) {
  24149. req.headers.emplace("Upgrade", value);
  24150. }
  24151. req.headers.emplace("Connection", "Upgrade");
  24152. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  24153. req.headers.emplace("Sec-WebSocket-Version", "13");
  24154. return req;
  24155. };
  24156. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  24157. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  24158. EXPECT_TRUE(
  24159. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  24160. EXPECT_TRUE(
  24161. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  24162. EXPECT_TRUE(
  24163. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  24164. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  24165. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  24166. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  24167. EXPECT_FALSE(
  24168. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  24169. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  24170. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  24171. }
  24172. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  24173. Server svr;
  24174. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  24175. auto port = svr.bind_to_any_port("localhost");
  24176. std::thread t([&]() { svr.listen_after_bind(); });
  24177. auto se = detail::scope_exit([&] {
  24178. svr.stop();
  24179. t.join();
  24180. });
  24181. svr.wait_until_ready();
  24182. Headers headers = {{"Upgrade", "websocket"},
  24183. {"Connection", "notupgrade"},
  24184. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  24185. {"Sec-WebSocket-Version", "13"}};
  24186. Client cli("localhost", port);
  24187. auto res = cli.Get("/ws", headers);
  24188. // The route exists only as a WebSocket route, so a request that fails the
  24189. // handshake check falls through to ordinary routing.
  24190. ASSERT_TRUE(res);
  24191. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  24192. }
  24193. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  24194. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  24195. // Connection value is the only thing left for the client to reject.
  24196. Server svr;
  24197. svr.Get("/ws", [](const Request &req, Response &res) {
  24198. res.status = StatusCode::SwitchingProtocol_101;
  24199. res.set_header("Upgrade", "websocket");
  24200. res.set_header("Connection", "notupgrade");
  24201. res.set_header("Sec-WebSocket-Accept",
  24202. detail::websocket_accept_key(
  24203. req.get_header_value("Sec-WebSocket-Key")));
  24204. });
  24205. auto port = svr.bind_to_any_port("localhost");
  24206. std::thread t([&]() { svr.listen_after_bind(); });
  24207. auto se = detail::scope_exit([&] {
  24208. svr.stop();
  24209. t.join();
  24210. });
  24211. svr.wait_until_ready();
  24212. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  24213. auto res = client.connect();
  24214. EXPECT_FALSE(res);
  24215. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24216. EXPECT_FALSE(client.is_open());
  24217. }
  24218. TEST(WebSocketTest, ClientRejectsUnofferedSubprotocol) {
  24219. Server svr;
  24220. svr.Get("/ws", [](const Request &req, Response &res) {
  24221. res.status = StatusCode::SwitchingProtocol_101;
  24222. res.set_header("Upgrade", "websocket");
  24223. res.set_header("Connection", "Upgrade");
  24224. res.set_header("Sec-WebSocket-Accept",
  24225. detail::websocket_accept_key(
  24226. req.get_header_value("Sec-WebSocket-Key")));
  24227. res.set_header("Sec-WebSocket-Protocol", "admin");
  24228. });
  24229. auto port = svr.bind_to_any_port("localhost");
  24230. std::thread t([&]() { svr.listen_after_bind(); });
  24231. auto se = detail::scope_exit([&] {
  24232. svr.stop();
  24233. t.join();
  24234. });
  24235. svr.wait_until_ready();
  24236. const auto url = "ws://localhost:" + std::to_string(port) + "/ws";
  24237. // Server selects a subprotocol the client never offered
  24238. {
  24239. Headers headers = {{"Sec-WebSocket-Protocol", "chat"}};
  24240. ws::WebSocketClient client(url, headers);
  24241. auto res = client.connect();
  24242. EXPECT_FALSE(res);
  24243. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24244. EXPECT_FALSE(client.is_open());
  24245. EXPECT_TRUE(client.subprotocol().empty());
  24246. }
  24247. // Client offered none but the server named one anyway
  24248. {
  24249. ws::WebSocketClient client(url);
  24250. auto res = client.connect();
  24251. EXPECT_FALSE(res);
  24252. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  24253. EXPECT_FALSE(client.is_open());
  24254. EXPECT_TRUE(client.subprotocol().empty());
  24255. }
  24256. }
  24257. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  24258. // The socket path doubles as the URL host, so it must not contain '/'.
  24259. const char *shard = getenv("GTEST_SHARD_INDEX");
  24260. const std::string sock_path =
  24261. shard ? std::string("httplib-ws-") + shard + ".sock"
  24262. : std::string("httplib-ws.sock");
  24263. std::remove(sock_path.c_str());
  24264. Server svr;
  24265. std::mutex mtx;
  24266. std::string received_host;
  24267. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  24268. {
  24269. std::lock_guard<std::mutex> lock(mtx);
  24270. received_host = req.get_header_value("Host");
  24271. }
  24272. std::string msg;
  24273. while (ws.read(msg)) {
  24274. ws.send(msg);
  24275. }
  24276. });
  24277. svr.set_address_family(AF_UNIX);
  24278. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  24279. auto se = detail::scope_exit([&] {
  24280. svr.stop();
  24281. t.join();
  24282. std::remove(sock_path.c_str());
  24283. });
  24284. svr.wait_until_ready();
  24285. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  24286. client.set_address_family(AF_UNIX);
  24287. ASSERT_TRUE(client.connect());
  24288. ASSERT_TRUE(client.send("hello"));
  24289. std::string msg;
  24290. ASSERT_TRUE(client.read(msg));
  24291. client.close();
  24292. {
  24293. std::lock_guard<std::mutex> lock(mtx);
  24294. // There is no host:port for a Unix socket, so the same "localhost"
  24295. // placeholder the HTTP client uses is expected.
  24296. EXPECT_EQ("localhost", received_host);
  24297. }
  24298. }
  24299. // Two threads must never parse WebSocket frames from the same stream.
  24300. // close() used to read the peer's Close reply with its own frame read, so it
  24301. // raced a reader thread that was in the middle of a payload: the payload loop
  24302. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  24303. // so bytes taken by close() were replaced with bytes from further along the
  24304. // stream. The message kept its length and silently changed content.
  24305. //
  24306. // The raw peer below sends a frame header plus part of the payload, waits for
  24307. // the handler to call close(), and only then sends the rest. Whichever thread
  24308. // would win the race for those bytes, the message must arrive intact, because
  24309. // close() must not touch the stream while read() owns it.
  24310. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  24311. #ifndef _WIN32
  24312. signal(SIGPIPE, SIG_IGN);
  24313. #endif
  24314. const size_t payload_len = 120; // fits the 7-bit length field
  24315. const size_t prefix_len = 8;
  24316. const int attempts = 8;
  24317. std::string expected(payload_len, '\0');
  24318. for (size_t i = 0; i < payload_len; i++) {
  24319. expected[i] = static_cast<char>('a' + i % 26);
  24320. }
  24321. std::atomic<bool> peer_stalled{false};
  24322. std::atomic<bool> handler_done{false};
  24323. std::mutex received_mutex;
  24324. std::vector<std::string> received;
  24325. // Bound every wait, so a regression fails the test instead of hanging the
  24326. // suite.
  24327. auto wait_for = [](const std::atomic<bool> &flag) {
  24328. for (int i = 0; i < 500 && !flag; i++) {
  24329. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24330. }
  24331. };
  24332. Server svr;
  24333. svr.set_websocket_ping_interval(0);
  24334. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24335. std::thread reader([&]() {
  24336. std::string msg;
  24337. while (ws.read(msg)) {
  24338. std::lock_guard<std::mutex> guard(received_mutex);
  24339. received.push_back(msg);
  24340. }
  24341. });
  24342. // Wait until the peer stalls mid-payload, so the reader thread is parked
  24343. // inside read_websocket_frame() when close() runs.
  24344. wait_for(peer_stalled);
  24345. ws.close();
  24346. reader.join();
  24347. handler_done = true;
  24348. });
  24349. auto port = svr.bind_to_any_port("127.0.0.1");
  24350. std::thread t([&]() { svr.listen_after_bind(); });
  24351. auto se = detail::scope_exit([&] {
  24352. svr.stop();
  24353. t.join();
  24354. });
  24355. svr.wait_until_ready();
  24356. auto send_bytes = [](socket_t s, const std::string &data) {
  24357. #ifdef _WIN32
  24358. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  24359. #else
  24360. auto n = ::send(s, data.data(), data.size(), 0);
  24361. #endif
  24362. return n == static_cast<decltype(n)>(data.size());
  24363. };
  24364. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  24365. // Every length used here fits the 7-bit length field.
  24366. auto masked_header = [](uint8_t first_byte, size_t len) {
  24367. std::string h;
  24368. h += static_cast<char>(first_byte);
  24369. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  24370. h.append(4, '\0'); // mask key
  24371. return h;
  24372. };
  24373. for (int attempt = 0; attempt < attempts; attempt++) {
  24374. peer_stalled = false;
  24375. handler_done = false;
  24376. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24377. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  24378. auto se_sock = detail::scope_exit([&] {
  24379. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  24380. });
  24381. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24382. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  24383. sockaddr_in addr{};
  24384. addr.sin_family = AF_INET;
  24385. addr.sin_port = htons(static_cast<uint16_t>(port));
  24386. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24387. ASSERT_EQ(
  24388. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  24389. << "attempt " << attempt;
  24390. ASSERT_TRUE(send_bytes(sock,
  24391. "GET /ws HTTP/1.1\r\n"
  24392. "Host: 127.0.0.1\r\n"
  24393. "Upgrade: websocket\r\n"
  24394. "Connection: Upgrade\r\n"
  24395. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24396. "Sec-WebSocket-Version: 13\r\n"
  24397. "\r\n"))
  24398. << "attempt " << attempt;
  24399. std::string response;
  24400. while (response.find("\r\n\r\n") == std::string::npos) {
  24401. char buf[512];
  24402. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  24403. if (n <= 0) { break; }
  24404. response.append(buf, static_cast<size_t>(n));
  24405. }
  24406. ASSERT_NE(std::string::npos, response.find(" 101 "))
  24407. << "attempt " << attempt;
  24408. // Send the header of a Binary message but only the first prefix_len bytes
  24409. // of its payload, leaving the reader thread stalled inside the payload.
  24410. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  24411. expected.substr(0, prefix_len)))
  24412. << "attempt " << attempt;
  24413. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24414. peer_stalled = true;
  24415. // Let close() send its Close frame and park in its own read before the
  24416. // rest of the payload arrives, so both threads are waiting for it.
  24417. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24418. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  24419. close_frame += static_cast<char>(0x03); // status 1000
  24420. close_frame += static_cast<char>(0xE8);
  24421. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  24422. << "attempt " << attempt;
  24423. // Closing the peer releases the reader thread even on the buggy path,
  24424. // where it waits for bytes another thread already consumed.
  24425. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  24426. detail::close_socket(sock);
  24427. sock = INVALID_SOCKET;
  24428. wait_for(handler_done);
  24429. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  24430. }
  24431. std::lock_guard<std::mutex> guard(received_mutex);
  24432. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  24433. << "a message in flight when close() ran was dropped";
  24434. for (size_t i = 0; i < received.size(); i++) {
  24435. EXPECT_EQ(expected, received[i]) << "message " << i;
  24436. }
  24437. }
  24438. // Connects to 127.0.0.1:port and completes a WebSocket handshake for path,
  24439. // returning the socket, or INVALID_SOCKET.
  24440. static socket_t connect_raw_websocket(int port, const std::string &path) {
  24441. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  24442. if (sock == INVALID_SOCKET) { return sock; }
  24443. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  24444. sockaddr_in addr{};
  24445. addr.sin_family = AF_INET;
  24446. addr.sin_port = htons(static_cast<uint16_t>(port));
  24447. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  24448. std::string req = "GET " + path +
  24449. " HTTP/1.1\r\n"
  24450. "Host: 127.0.0.1\r\n"
  24451. "Upgrade: websocket\r\n"
  24452. "Connection: Upgrade\r\n"
  24453. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  24454. "Sec-WebSocket-Version: 13\r\n"
  24455. "\r\n";
  24456. std::string res;
  24457. if (::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) == 0 &&
  24458. detail::send_socket(sock, req.data(), req.size(), 0) ==
  24459. static_cast<ssize_t>(req.size())) {
  24460. char c;
  24461. while (res.find("\r\n\r\n") == std::string::npos &&
  24462. ::recv(sock, &c, 1, 0) == 1) {
  24463. res += c;
  24464. }
  24465. }
  24466. if (res.find(" 101 ") == std::string::npos) {
  24467. detail::close_socket(sock);
  24468. return INVALID_SOCKET;
  24469. }
  24470. return sock;
  24471. }
  24472. // A client frame with an all-zero mask key, so the payload goes out verbatim.
  24473. // The payload must fit the 7-bit length field.
  24474. static std::string masked_frame(uint8_t first_byte,
  24475. const std::string &payload) {
  24476. std::string f;
  24477. f += static_cast<char>(first_byte);
  24478. f += static_cast<char>(0x80 | payload.size());
  24479. f.append(4, '\0');
  24480. return f + payload;
  24481. }
  24482. TEST(WebSocketTest, AssemblesFragmentsAroundAPing) {
  24483. std::atomic<bool> done{false};
  24484. std::string received;
  24485. Server svr;
  24486. svr.set_websocket_ping_interval(0);
  24487. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24488. std::string msg;
  24489. if (ws.read(msg) == ws::Binary) { received = msg; }
  24490. done = true;
  24491. });
  24492. auto port = svr.bind_to_any_port("127.0.0.1");
  24493. std::thread t([&]() { svr.listen_after_bind(); });
  24494. auto se = detail::scope_exit([&] {
  24495. svr.stop();
  24496. t.join();
  24497. });
  24498. svr.wait_until_ready();
  24499. auto sock = connect_raw_websocket(port, "/ws");
  24500. ASSERT_NE(INVALID_SOCKET, sock);
  24501. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24502. auto frames = masked_frame(0x02, "Hel") + // Binary, more to come
  24503. masked_frame(0x89, "p") + // FIN + Ping
  24504. masked_frame(0x80, "lo"); // FIN + Continuation
  24505. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24506. for (int i = 0; i < 500 && !done; i++) {
  24507. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  24508. }
  24509. ASSERT_TRUE(done);
  24510. EXPECT_EQ("Hello", received);
  24511. // The Ping between the fragments is answered with a Pong.
  24512. char pong[3];
  24513. ASSERT_EQ(3, ::recv(sock, pong, sizeof(pong), MSG_WAITALL));
  24514. EXPECT_EQ(std::string("\x8a\x01p", 3), std::string(pong, 3));
  24515. }
  24516. TEST(WebSocketTest, NegativePingIntervalSendsNoPings) {
  24517. Server svr;
  24518. svr.set_websocket_ping_interval(-1);
  24519. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24520. std::string msg;
  24521. while (ws.read(msg)) {}
  24522. });
  24523. auto port = svr.bind_to_any_port("127.0.0.1");
  24524. std::thread t([&]() { svr.listen_after_bind(); });
  24525. auto se = detail::scope_exit([&] {
  24526. svr.stop();
  24527. t.join();
  24528. });
  24529. svr.wait_until_ready();
  24530. auto sock = connect_raw_websocket(port, "/ws");
  24531. ASSERT_NE(INVALID_SOCKET, sock);
  24532. auto se_sock = detail::scope_exit([&] { detail::close_socket(sock); });
  24533. // Nothing comes while the client stays quiet.
  24534. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 0, 300000);
  24535. char c;
  24536. EXPECT_EQ(-1, ::recv(sock, &c, 1, 0));
  24537. }
  24538. // The client's heartbeat gives up on a peer that leaves its pings unanswered,
  24539. // and that has to end a read() already waiting on the peer, on every platform.
  24540. static void check_pong_timeout_ends_read(Server &svr, const char *scheme) {
  24541. // The peer sends no pings, and its handler never calls read(), which is
  24542. // where pongs are written.
  24543. std::mutex mutex;
  24544. std::condition_variable cv;
  24545. auto release = false;
  24546. svr.set_websocket_ping_interval(0);
  24547. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &) {
  24548. std::unique_lock<std::mutex> lock(mutex);
  24549. cv.wait(lock, [&] { return release; });
  24550. });
  24551. auto port = svr.bind_to_any_port(HOST);
  24552. std::thread t([&]() { svr.listen_after_bind(); });
  24553. auto se = detail::scope_exit([&] {
  24554. {
  24555. std::lock_guard<std::mutex> lock(mutex);
  24556. release = true;
  24557. }
  24558. cv.notify_all();
  24559. svr.stop();
  24560. t.join();
  24561. });
  24562. svr.wait_until_ready();
  24563. ws::WebSocketClient client(std::string(scheme) +
  24564. "://localhost:" + std::to_string(port) + "/ws");
  24565. #ifdef CPPHTTPLIB_SSL_ENABLED
  24566. client.enable_server_certificate_verification(false);
  24567. #endif
  24568. // A ping a second, given up on after two go unanswered: about 3s
  24569. client.set_websocket_ping_interval(1);
  24570. client.set_websocket_max_missed_pongs(2);
  24571. // Well past that, so that a read the timeout ends instead stands out
  24572. client.set_read_timeout(10);
  24573. ASSERT_TRUE(client.connect());
  24574. auto start = std::chrono::steady_clock::now();
  24575. std::string msg;
  24576. EXPECT_EQ(ws::Fail, client.read(msg));
  24577. EXPECT_LT(std::chrono::duration_cast<std::chrono::milliseconds>(
  24578. std::chrono::steady_clock::now() - start)
  24579. .count(),
  24580. 6000);
  24581. EXPECT_FALSE(client.is_open());
  24582. }
  24583. TEST(WebSocketTest, PongTimeoutEndsABlockedRead) {
  24584. Server svr;
  24585. check_pong_timeout_ends_read(svr, "ws");
  24586. }
  24587. #ifdef CPPHTTPLIB_SSL_ENABLED
  24588. TEST(WebSocketTest, PongTimeoutEndsABlockedReadOverTLS) {
  24589. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24590. ASSERT_TRUE(svr.is_valid());
  24591. check_pong_timeout_ends_read(svr, "wss");
  24592. }
  24593. #endif
  24594. TEST(WebSocketTest, AnswersAMalformedCloseWithProtocolError) {
  24595. Server svr;
  24596. svr.set_websocket_ping_interval(0);
  24597. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  24598. std::string msg;
  24599. while (ws.read(msg)) {}
  24600. });
  24601. auto port = svr.bind_to_any_port("127.0.0.1");
  24602. std::thread t([&]() { svr.listen_after_bind(); });
  24603. auto se = detail::scope_exit([&] {
  24604. svr.stop();
  24605. t.join();
  24606. });
  24607. svr.wait_until_ready();
  24608. // Each Close payload and the reply it should get: an echo when valid, 1002
  24609. // otherwise.
  24610. std::vector<std::pair<std::string, std::string>> cases = {
  24611. {std::string("\x03\xe8") + "bye", std::string("\x03\xe8") + "bye"},
  24612. {std::string("\x03"), std::string("\x03\xea")}, // 1 byte
  24613. {std::string("\x03\xed"), std::string("\x03\xea")}, // 1005
  24614. {std::string("\x03\xe8\xff"), std::string("\x03\xea")}, // bad UTF-8
  24615. };
  24616. // Also between the fragments of a message.
  24617. for (const auto &prefix : {std::string(), masked_frame(0x02, "a")}) {
  24618. for (const auto &c : cases) {
  24619. auto sock = connect_raw_websocket(port, "/ws");
  24620. ASSERT_NE(INVALID_SOCKET, sock);
  24621. auto frames = prefix + masked_frame(0x88, c.first);
  24622. detail::send_socket(sock, frames.data(), frames.size(), 0);
  24623. std::string reply;
  24624. char buf[256];
  24625. while (reply.size() < 2 + c.second.size()) {
  24626. auto n = ::recv(sock, buf, sizeof(buf), 0);
  24627. if (n <= 0) { break; }
  24628. reply.append(buf, static_cast<size_t>(n));
  24629. }
  24630. detail::close_socket(sock);
  24631. EXPECT_EQ(std::string("\x88") + static_cast<char>(c.second.size()) +
  24632. c.second,
  24633. reply);
  24634. }
  24635. }
  24636. }
  24637. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  24638. class WebSocketSSLIntegrationTest : public ::testing::Test {
  24639. protected:
  24640. void SetUp() override {
  24641. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  24642. SERVER_PRIVATE_KEY_FILE);
  24643. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24644. std::string msg;
  24645. ws::ReadResult ret;
  24646. while ((ret = ws.read(msg))) {
  24647. if (ret == ws::Binary) {
  24648. ws.send(msg.data(), msg.size());
  24649. } else {
  24650. ws.send(msg);
  24651. }
  24652. }
  24653. });
  24654. port_ = server_->bind_to_any_port(HOST);
  24655. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24656. server_->wait_until_ready();
  24657. }
  24658. void TearDown() override {
  24659. server_->stop();
  24660. if (server_thread_.joinable()) { server_thread_.join(); }
  24661. }
  24662. std::unique_ptr<SSLServer> server_;
  24663. std::thread server_thread_;
  24664. int port_ = 0;
  24665. };
  24666. TEST_F(WebSocketSSLIntegrationTest, VerifiersDecide) {
  24667. auto url = "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24668. {
  24669. ws::WebSocketClient client(url);
  24670. client.enable_server_certificate_verification(false);
  24671. auto calls = 0;
  24672. client.set_server_certificate_verifier([&](const tls::VerifyContext &) {
  24673. calls++;
  24674. return false;
  24675. });
  24676. EXPECT_FALSE(client.connect());
  24677. EXPECT_GT(calls, 0);
  24678. }
  24679. {
  24680. ws::WebSocketClient client(url);
  24681. client.enable_server_certificate_verification(false);
  24682. client.set_session_verifier([](tls::session_t) {
  24683. return SSLVerifierResponse::CertificateRejected;
  24684. });
  24685. EXPECT_FALSE(client.connect());
  24686. }
  24687. {
  24688. ws::WebSocketClient client(url);
  24689. client.enable_server_certificate_verification(false);
  24690. client.set_session_verifier([](tls::session_t) {
  24691. return SSLVerifierResponse::CertificateAccepted;
  24692. });
  24693. EXPECT_TRUE(client.connect());
  24694. }
  24695. }
  24696. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  24697. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24698. "/ws-echo");
  24699. client.enable_server_certificate_verification(false);
  24700. ASSERT_TRUE(client.connect());
  24701. ASSERT_TRUE(client.is_open());
  24702. ASSERT_TRUE(client.send("Hello WSS"));
  24703. std::string msg;
  24704. EXPECT_EQ(ws::Text, client.read(msg));
  24705. EXPECT_EQ("Hello WSS", msg);
  24706. client.close();
  24707. }
  24708. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  24709. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  24710. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  24711. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  24712. // client (without calling close() first) is the only path that runs
  24713. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  24714. // bug exactly.
  24715. //
  24716. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  24717. // when linked against an instrumented libssl; run under Valgrind to catch it
  24718. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  24719. // suite (the freed session otherwise stalls on the close handshake) — this test
  24720. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  24721. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  24722. {
  24723. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24724. "/ws-echo");
  24725. client.enable_server_certificate_verification(false);
  24726. client.set_read_timeout(2, 0);
  24727. client.set_write_timeout(2, 0);
  24728. ASSERT_TRUE(client.connect());
  24729. ASSERT_TRUE(client.is_open());
  24730. ASSERT_TRUE(client.send("still open"));
  24731. // Intentionally do NOT call client.close(): leaving scope runs
  24732. // shutdown_and_close() with the WebSocket still open, which must send the
  24733. // close frame while the TLS session is still alive.
  24734. }
  24735. }
  24736. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  24737. // shutdown_and_close() at the start of connect(), reproducing the same
  24738. // use-after-free within the test body rather than at scope exit. The second
  24739. // connect must succeed and echo, proving the close handshake ran over a live
  24740. // session. See the note above about memory-tool requirements.
  24741. TEST_F(WebSocketSSLIntegrationTest,
  24742. ReconnectWhileOpenSendsCloseOverLiveSession) {
  24743. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  24744. "/ws-echo");
  24745. client.enable_server_certificate_verification(false);
  24746. client.set_read_timeout(2, 0);
  24747. client.set_write_timeout(2, 0);
  24748. ASSERT_TRUE(client.connect());
  24749. ASSERT_TRUE(client.is_open());
  24750. ASSERT_TRUE(client.send("still open"));
  24751. // Reconnect without closing first: connect() calls shutdown_and_close() on
  24752. // the still-open connection, which must not touch a freed TLS session.
  24753. ASSERT_TRUE(client.connect());
  24754. ASSERT_TRUE(client.is_open());
  24755. ASSERT_TRUE(client.send("after reconnect"));
  24756. std::string msg;
  24757. EXPECT_EQ(ws::Text, client.read(msg));
  24758. EXPECT_EQ("after reconnect", msg);
  24759. client.close();
  24760. }
  24761. #endif
  24762. #ifdef CPPHTTPLIB_SSL_ENABLED
  24763. class WebSocketSSLCATest : public ::testing::Test {
  24764. protected:
  24765. void SetUp() override {
  24766. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  24767. SERVER_PRIVATE_KEY_FILE);
  24768. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24769. std::string msg;
  24770. while (ws.read(msg)) {
  24771. ws.send(msg);
  24772. }
  24773. });
  24774. port_ = server_->bind_to_any_port("127.0.0.1");
  24775. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24776. server_->wait_until_ready();
  24777. }
  24778. void TearDown() override {
  24779. server_->stop();
  24780. if (server_thread_.joinable()) { server_thread_.join(); }
  24781. }
  24782. std::string url() const {
  24783. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  24784. }
  24785. std::unique_ptr<SSLServer> server_;
  24786. std::thread server_thread_;
  24787. int port_ = 0;
  24788. };
  24789. // A custom CA loaded as PEM verifies the server with full certificate
  24790. // verification enabled
  24791. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  24792. ws::WebSocketClient client(url());
  24793. std::string cert;
  24794. read_file(SERVER_CERT2_FILE, cert);
  24795. client.load_ca_cert_store(cert.c_str(), cert.size());
  24796. ASSERT_TRUE(client.connect());
  24797. ASSERT_TRUE(client.send("hello"));
  24798. std::string msg;
  24799. EXPECT_EQ(ws::Text, client.read(msg));
  24800. EXPECT_EQ("hello", msg);
  24801. client.close();
  24802. }
  24803. // A custom CA that does not cover the server must fail verification (the
  24804. // custom CA is exclusive; system certs are not loaded alongside it)
  24805. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  24806. ws::WebSocketClient client(url());
  24807. std::string cert;
  24808. read_file(CLIENT_CA_CERT_FILE, cert);
  24809. client.load_ca_cert_store(cert.c_str(), cert.size());
  24810. auto res = client.connect();
  24811. ASSERT_FALSE(res);
  24812. EXPECT_EQ(Error::SSLServerVerification, res.error());
  24813. EXPECT_EQ(-1, res.status());
  24814. EXPECT_NE(0u, res.ssl_backend_error());
  24815. }
  24816. // The same CA as a file path rather than PEM in memory
  24817. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  24818. ws::WebSocketClient client(url());
  24819. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24820. ASSERT_TRUE(client.connect());
  24821. ASSERT_TRUE(client.send("hello"));
  24822. std::string msg;
  24823. EXPECT_EQ(ws::Text, client.read(msg));
  24824. EXPECT_EQ("hello", msg);
  24825. client.close();
  24826. }
  24827. // ...and a CA file that does not cover the server still fails, so it is the
  24828. // path above that decides the outcome
  24829. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  24830. ws::WebSocketClient client(url());
  24831. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24832. ASSERT_FALSE(client.connect());
  24833. }
  24834. // Regression test: reconnecting with a native custom CA store used to reuse
  24835. // a store handle the previous TLS context had already freed (use-after-free
  24836. // under the OpenSSL backend). The context now lives as long as the client.
  24837. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  24838. ws::WebSocketClient client(url());
  24839. std::string cert;
  24840. read_file(SERVER_CERT2_FILE, cert);
  24841. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  24842. ASSERT_TRUE(client.connect());
  24843. client.close();
  24844. ASSERT_TRUE(client.connect());
  24845. ASSERT_TRUE(client.send("again"));
  24846. std::string msg;
  24847. EXPECT_EQ(ws::Text, client.read(msg));
  24848. EXPECT_EQ("again", msg);
  24849. client.close();
  24850. }
  24851. // Regression test: a certificate with a trusted chain but no identity match
  24852. // for the server IP must be rejected. The Mbed TLS backend used to skip
  24853. // verification entirely for IP hosts, so this connection succeeded there.
  24854. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  24855. // chain verification while the identity check must still fail.
  24856. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  24857. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  24858. ASSERT_TRUE(svr.is_valid());
  24859. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24860. std::string msg;
  24861. while (ws.read(msg)) {
  24862. ws.send(msg);
  24863. }
  24864. });
  24865. auto port = svr.bind_to_any_port("127.0.0.1");
  24866. auto t = std::thread([&]() { svr.listen_after_bind(); });
  24867. auto se = detail::scope_exit([&] {
  24868. svr.stop();
  24869. t.join();
  24870. });
  24871. svr.wait_until_ready();
  24872. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  24873. "/echo");
  24874. std::string cert;
  24875. read_file(SERVER_CERT_FILE, cert);
  24876. client.load_ca_cert_store(cert.c_str(), cert.size());
  24877. ASSERT_FALSE(client.connect());
  24878. }
  24879. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  24880. // SNI, so nothing binds the host name to the TLS session. These bind the
  24881. // server to "localhost" instead, the only shape that exercises the SNI and
  24882. // hostname-verification path with certificate verification left enabled.
  24883. class WebSocketSSLDnsHostTest : public ::testing::Test {
  24884. protected:
  24885. void Start(const char *cert_file) {
  24886. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  24887. SERVER_PRIVATE_KEY_FILE);
  24888. ASSERT_TRUE(server_->is_valid());
  24889. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  24890. std::string msg;
  24891. while (ws.read(msg)) {
  24892. ws.send(msg);
  24893. }
  24894. });
  24895. port_ = server_->bind_to_any_port("localhost");
  24896. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24897. server_->wait_until_ready();
  24898. }
  24899. void TearDown() override {
  24900. if (server_) { server_->stop(); }
  24901. if (server_thread_.joinable()) { server_thread_.join(); }
  24902. }
  24903. std::string url() const {
  24904. return "wss://localhost:" + std::to_string(port_) + "/echo";
  24905. }
  24906. std::unique_ptr<SSLServer> server_;
  24907. std::thread server_thread_;
  24908. int port_ = 0;
  24909. };
  24910. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  24911. // out and the connection is usable
  24912. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  24913. Start(SERVER_CERT2_FILE);
  24914. ws::WebSocketClient client(url());
  24915. client.set_ca_cert_path(SERVER_CERT2_FILE);
  24916. ASSERT_TRUE(client.connect());
  24917. ASSERT_TRUE(client.send("hello"));
  24918. std::string msg;
  24919. EXPECT_EQ(ws::Text, client.read(msg));
  24920. EXPECT_EQ("hello", msg);
  24921. client.close();
  24922. }
  24923. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  24924. // while the identity check must still reject "localhost"
  24925. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  24926. Start(SERVER_CERT_FILE);
  24927. ws::WebSocketClient client(url());
  24928. client.set_ca_cert_path(SERVER_CERT_FILE);
  24929. auto res = client.connect();
  24930. ASSERT_FALSE(res);
  24931. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  24932. EXPECT_EQ(-1, res.status());
  24933. }
  24934. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  24935. // disabled: the chain is still checked, only the identity check is skipped
  24936. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  24937. Start(SERVER_CERT_FILE);
  24938. ws::WebSocketClient client(url());
  24939. client.set_ca_cert_path(SERVER_CERT_FILE);
  24940. client.enable_server_hostname_verification(false);
  24941. ASSERT_TRUE(client.connect());
  24942. ASSERT_TRUE(client.send("hello"));
  24943. std::string msg;
  24944. EXPECT_EQ(ws::Text, client.read(msg));
  24945. EXPECT_EQ("hello", msg);
  24946. client.close();
  24947. }
  24948. // A CA that did not sign the server certificate fails the chain, even though
  24949. // the name would match
  24950. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  24951. Start(SERVER_CERT2_FILE);
  24952. ws::WebSocketClient client(url());
  24953. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  24954. ASSERT_FALSE(client.connect());
  24955. }
  24956. // With verification disabled, neither the chain nor the name is checked
  24957. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  24958. Start(SERVER_CERT_FILE);
  24959. ws::WebSocketClient client(url());
  24960. client.enable_server_certificate_verification(false);
  24961. ASSERT_TRUE(client.connect());
  24962. ASSERT_TRUE(client.send("hello"));
  24963. std::string msg;
  24964. EXPECT_EQ(ws::Text, client.read(msg));
  24965. EXPECT_EQ("hello", msg);
  24966. client.close();
  24967. }
  24968. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  24969. protected:
  24970. void SetUp() override {
  24971. server_ = httplib::detail::make_unique<SSLServer>(
  24972. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  24973. ASSERT_TRUE(server_->is_valid());
  24974. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  24975. std::string msg;
  24976. while (ws.read(msg)) {
  24977. ws.send(msg);
  24978. }
  24979. });
  24980. port_ = server_->bind_to_any_port("localhost");
  24981. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  24982. server_->wait_until_ready();
  24983. }
  24984. void TearDown() override {
  24985. server_->stop();
  24986. if (server_thread_.joinable()) { server_thread_.join(); }
  24987. }
  24988. std::string url() const {
  24989. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  24990. }
  24991. void ConnectWithClientCert(const std::string &client_cert_file,
  24992. const std::string &client_private_key_file,
  24993. const char *private_key_password) {
  24994. std::string cert_pem, key_pem;
  24995. read_file(client_cert_file, cert_pem);
  24996. read_file(client_private_key_file, key_pem);
  24997. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  24998. key_pem.c_str(), key_pem.size(),
  24999. private_key_password};
  25000. ConnectWithPem(pem);
  25001. }
  25002. void ConnectWithPem(const ws::WebSocketClient::PemMemory &pem) {
  25003. ws::WebSocketClient client(url(), pem);
  25004. ASSERT_TRUE(client.is_valid());
  25005. client.enable_server_certificate_verification(false);
  25006. ASSERT_TRUE(client.connect());
  25007. ASSERT_TRUE(client.send("hello"));
  25008. std::string msg;
  25009. EXPECT_EQ(ws::Text, client.read(msg));
  25010. EXPECT_EQ("hello", msg);
  25011. client.close();
  25012. }
  25013. std::unique_ptr<SSLServer> server_;
  25014. std::thread server_thread_;
  25015. int port_ = 0;
  25016. };
  25017. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  25018. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  25019. }
  25020. // Control for the tests above: the fixture's server really does require a
  25021. // client certificate, so it is the PEM the constructor installed that decides
  25022. // the outcome.
  25023. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  25024. ws::WebSocketClient client(url());
  25025. ASSERT_TRUE(client.is_valid());
  25026. client.enable_server_certificate_verification(false);
  25027. EXPECT_FALSE(client.connect());
  25028. }
  25029. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  25030. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  25031. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  25032. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  25033. }
  25034. // The PemMemory lengths are honoured, so the PEM needs no NUL terminator
  25035. TEST_F(WebSocketSSLPemMemoryTest, ExactSizeBuffersAccepted) {
  25036. std::string cert_pem, key_pem;
  25037. read_file(CLIENT_CERT_FILE, cert_pem);
  25038. read_file(CLIENT_PRIVATE_KEY_FILE, key_pem);
  25039. std::vector<char> cert(cert_pem.begin(), cert_pem.end());
  25040. std::vector<char> key(key_pem.begin(), key_pem.end());
  25041. ws::WebSocketClient::PemMemory pem = {cert.data(), cert.size(), key.data(),
  25042. key.size(), nullptr};
  25043. ConnectWithPem(pem);
  25044. }
  25045. #endif
  25046. #if !defined(_WIN32)
  25047. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  25048. auto secret_dir = std::string("./symlink_test_secret");
  25049. auto served_dir = std::string("./symlink_test_served");
  25050. auto secret_file = secret_dir + "/secret.txt";
  25051. auto symlink_path = served_dir + "/escape";
  25052. // Setup: create directories and files
  25053. mkdir(secret_dir.c_str(), 0755);
  25054. mkdir(served_dir.c_str(), 0755);
  25055. {
  25056. std::ofstream ofs(secret_file);
  25057. ofs << "SECRET_DATA";
  25058. }
  25059. // Create symlink using absolute path so it resolves correctly
  25060. #ifdef PATH_MAX
  25061. char abs_secret[PATH_MAX];
  25062. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  25063. #else
  25064. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  25065. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  25066. ASSERT_NE(nullptr, abs_secret);
  25067. #endif
  25068. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  25069. auto se = detail::scope_exit([&] {
  25070. unlink(symlink_path.c_str());
  25071. unlink(secret_file.c_str());
  25072. rmdir(served_dir.c_str());
  25073. rmdir(secret_dir.c_str());
  25074. });
  25075. Server svr;
  25076. svr.set_mount_point("/", served_dir);
  25077. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  25078. auto se2 = detail::scope_exit([&] {
  25079. svr.stop();
  25080. listen_thread.join();
  25081. });
  25082. svr.wait_until_ready();
  25083. Client cli("localhost", PORT);
  25084. // Symlink pointing outside base dir should be blocked
  25085. auto res = cli.Get("/escape/secret.txt");
  25086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25087. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  25088. }
  25089. #endif
  25090. // Sends `outer_head` (with every "{len}" replaced by the length of an embedded
  25091. // "GET /smuggled" request), reads the first response, and only then sends the
  25092. // embedded request as the body. Returns how many times /smuggled ran.
  25093. //
  25094. // The body is sent AFTER receiving the first response (as in the original
  25095. // PoC) so that the stream_line_reader cannot buffer it together with the
  25096. // headers of the first request.
  25097. static int count_smuggled_requests(const std::string &outer_head,
  25098. std::string &first_response) {
  25099. Server svr;
  25100. svr.set_mount_point("/", "./www");
  25101. std::atomic<int> smuggled_count(0);
  25102. svr.Get("/smuggled", [&](const Request &, Response &res) {
  25103. smuggled_count++;
  25104. res.set_content("oops", "text/plain");
  25105. });
  25106. svr.Post("/post", [&](const Request &req, Response &res) {
  25107. res.set_content(req.body, "text/plain");
  25108. });
  25109. auto port = svr.bind_to_any_port("localhost");
  25110. thread t = thread([&] { svr.listen_after_bind(); });
  25111. auto se = detail::scope_exit([&] {
  25112. svr.stop();
  25113. t.join();
  25114. });
  25115. svr.wait_until_ready();
  25116. auto error = Error::Success;
  25117. auto sock = detail::create_client_socket(
  25118. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  25119. /*connection_timeout_sec=*/2, 0,
  25120. /*read_timeout_sec=*/2, 0,
  25121. /*write_timeout_sec=*/2, 0, std::string(), error);
  25122. EXPECT_NE(INVALID_SOCKET, sock);
  25123. if (sock == INVALID_SOCKET) { return -1; }
  25124. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25125. // The "smuggled" request will be sent as the body of the outer request
  25126. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  25127. "Host: localhost\r\n"
  25128. "Connection: close\r\n"
  25129. "\r\n";
  25130. auto head = outer_head;
  25131. auto len = std::to_string(smuggled.size());
  25132. for (auto pos = head.find("{len}"); pos != std::string::npos;
  25133. pos = head.find("{len}", pos + len.size())) {
  25134. head.replace(pos, 5, len);
  25135. }
  25136. // Step 1: Send only the outer request headers (no body yet)
  25137. auto sent = detail::send_socket(sock, head.data(), head.size(), 0);
  25138. EXPECT_EQ(static_cast<ssize_t>(head.size()), sent);
  25139. // Step 2: Read the first response
  25140. char buf[4096];
  25141. for (;;) {
  25142. auto n = recv(sock, buf, sizeof(buf), 0);
  25143. if (n <= 0) break;
  25144. first_response.append(buf, static_cast<size_t>(n));
  25145. // Stop once we have a complete response (headers + body)
  25146. auto hdr_end = first_response.find("\r\n\r\n");
  25147. if (hdr_end != std::string::npos) {
  25148. // Check for Content-Length to know when the body is complete
  25149. auto cl_pos = first_response.find("Content-Length:");
  25150. if (cl_pos != std::string::npos) {
  25151. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  25152. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  25153. auto cl = std::stoul(
  25154. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  25155. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  25156. } else {
  25157. break; // No Content-Length, assume headers-only response
  25158. }
  25159. }
  25160. }
  25161. // Step 3: Now send the body, which looks like a new HTTP request. On a
  25162. // vulnerable server the keep-alive loop reads this as a second request. The
  25163. // server may already have closed the connection, so the result is ignored.
  25164. detail::send_socket(sock, smuggled.data(), smuggled.size(), 0);
  25165. // Half-close so that a server which drained the body sees EOF and closes,
  25166. // instead of the read below waiting for the read timeout.
  25167. #ifdef _WIN32
  25168. ::shutdown(sock, SD_SEND);
  25169. #else
  25170. ::shutdown(sock, SHUT_WR);
  25171. #endif
  25172. // Step 4: Read until the server closes the connection
  25173. for (;;) {
  25174. auto n = recv(sock, buf, sizeof(buf), 0);
  25175. if (n <= 0) break;
  25176. }
  25177. return smuggled_count.load();
  25178. }
  25179. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  25180. // A GET request with Content-Length to a static file handler must have its
  25181. // body drained before the keep-alive connection is reused. Otherwise the
  25182. // unread body bytes are interpreted as the next HTTP request.
  25183. std::string first_response;
  25184. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25185. "Host: localhost\r\n"
  25186. "Content-Length: {len}\r\n"
  25187. "\r\n",
  25188. first_response));
  25189. EXPECT_EQ(0u, first_response.find("HTTP/1.1 200"));
  25190. }
  25191. TEST(RequestSmugglingTest, InvalidContentLengthRejected) {
  25192. // RFC 9112 §6.3: a Content-Length that is not a valid decimal length must
  25193. // be answered with 400 and the connection closed. Treating it as "no body"
  25194. // leaves the body to be parsed as the next request.
  25195. const char *values[] = {"{len}, {len}", "+{len}", "0x2e", "", " {len}x"};
  25196. const char *targets[] = {
  25197. "GET /file", // handler that never reads the body
  25198. "GET /not-found", // no handler matches (404)
  25199. "POST /post", // handler that reads the body
  25200. };
  25201. for (auto target : targets) {
  25202. for (auto value : values) {
  25203. std::string first_response;
  25204. EXPECT_EQ(0, count_smuggled_requests(std::string(target) +
  25205. " HTTP/1.1\r\n"
  25206. "Host: localhost\r\n"
  25207. "Content-Length: " +
  25208. value + "\r\n\r\n",
  25209. first_response))
  25210. << target << " with Content-Length: " << value;
  25211. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"))
  25212. << target << " with Content-Length: " << value;
  25213. }
  25214. }
  25215. }
  25216. TEST(RequestSmugglingTest, RejectedRequestLineClosesConnection) {
  25217. // A 400 for an unparseable request line leaves the rest of the message
  25218. // unread, so the connection must be closed rather than reused.
  25219. std::string first_response;
  25220. EXPECT_EQ(0, count_smuggled_requests("FOO /file HTTP/1.1\r\n"
  25221. "Host: localhost\r\n"
  25222. "Content-Length: {len}\r\n"
  25223. "\r\n",
  25224. first_response));
  25225. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25226. }
  25227. TEST(RequestSmugglingTest, RejectedHeadersCloseConnection) {
  25228. // Same as above for a header block that fails to parse.
  25229. std::string first_response;
  25230. EXPECT_EQ(0, count_smuggled_requests("GET /file HTTP/1.1\r\n"
  25231. "Host: localhost\r\n"
  25232. "Bad Header\r\n"
  25233. "Content-Length: {len}\r\n"
  25234. "\r\n",
  25235. first_response));
  25236. EXPECT_EQ(0u, first_response.find("HTTP/1.1 400"));
  25237. }
  25238. TEST(RequestSmugglingTest, ErrorResponseClosesConnection) {
  25239. // RFC 9112 §9.6: an error response carries "Connection: close", so the
  25240. // server must not read another request on that connection, even when the
  25241. // request had no body to drain.
  25242. std::string first_response;
  25243. EXPECT_EQ(0, count_smuggled_requests("GET /not-found HTTP/1.1\r\n"
  25244. "Host: localhost\r\n"
  25245. "\r\n",
  25246. first_response));
  25247. EXPECT_EQ(0u, first_response.find("HTTP/1.1 404"));
  25248. EXPECT_NE(std::string::npos, first_response.find("Connection: close"));
  25249. }
  25250. TEST(RequestSmugglingTest, AbortedContentReaderClosesConnection) {
  25251. // A content reader that stops early leaves the stream inside the body.
  25252. // Draining the whole Content-Length from there, or reading the body again,
  25253. // reads into the next request, and whatever follows is parsed as a request
  25254. // of its own.
  25255. Server svr;
  25256. std::atomic<int> smuggled_count(0);
  25257. svr.Get("/smuggled", [&](const Request &, Response &) { smuggled_count++; });
  25258. svr.Post("/upload", [](const Request &req, Response &res,
  25259. const ContentReader &content_reader) {
  25260. // Stop at the last chunk, so the whole body has been read however it
  25261. // arrives.
  25262. auto length = req.get_header_value_u64("Content-Length");
  25263. size_t total = 0;
  25264. auto consumed = content_reader([&](const char *, size_t n) {
  25265. total += n;
  25266. return total < length;
  25267. });
  25268. EXPECT_FALSE(consumed);
  25269. if (req.has_param("retry")) {
  25270. EXPECT_FALSE(content_reader([](const char *, size_t) { return true; }));
  25271. }
  25272. // Replace the 400 the aborted read set, which would close the connection.
  25273. res.set_redirect("/done");
  25274. });
  25275. auto port = svr.bind_to_any_port(HOST);
  25276. thread t = thread([&] { svr.listen_after_bind(); });
  25277. auto se = detail::scope_exit([&] {
  25278. svr.stop();
  25279. t.join();
  25280. });
  25281. svr.wait_until_ready();
  25282. // A front end sees the second request as a POST whose body is the GET. The
  25283. // first body is as long as the POST's headers, so draining it again reads
  25284. // exactly those and leaves the GET to be parsed next.
  25285. std::string inner = "GET /smuggled HTTP/1.1\r\n"
  25286. "Host: localhost\r\n"
  25287. "\r\n";
  25288. std::string second_head = "POST /post HTTP/1.1\r\n"
  25289. "Host: localhost\r\n"
  25290. "Content-Length: " +
  25291. std::to_string(inner.size()) +
  25292. "\r\n"
  25293. "\r\n";
  25294. for (auto target : {"/upload", "/upload?retry"}) {
  25295. smuggled_count = 0;
  25296. std::string request = "POST " + std::string(target) +
  25297. " HTTP/1.1\r\n"
  25298. "Host: localhost\r\n"
  25299. "Content-Length: " +
  25300. std::to_string(second_head.size()) +
  25301. "\r\n"
  25302. "\r\n" +
  25303. std::string(second_head.size(), 'A') + second_head +
  25304. inner;
  25305. std::string response;
  25306. ASSERT_TRUE(send_request(2, request, &response, port)) << target;
  25307. EXPECT_EQ(0u, response.find("HTTP/1.1 302")) << target;
  25308. EXPECT_NE(std::string::npos, response.find("Connection: close")) << target;
  25309. EXPECT_EQ(std::string::npos, response.find("HTTP/1.1", 1)) << target;
  25310. EXPECT_EQ(0, smuggled_count.load()) << target;
  25311. }
  25312. }
  25313. // An error response closes the connection anyway, so the body is left unread
  25314. // with a redirect, such as one to a login page.
  25315. static void serve_redirects(Server &svr,
  25316. const std::function<void(int)> &client) {
  25317. svr.set_pre_routing_handler([](const Request &, Response &res) {
  25318. res.set_redirect("/login");
  25319. return Server::HandlerResponse::Handled;
  25320. });
  25321. auto port = svr.bind_to_any_port(HOST);
  25322. ASSERT_GT(port, 0);
  25323. thread t = thread([&] { svr.listen_after_bind(); });
  25324. auto se = detail::scope_exit([&] {
  25325. svr.stop();
  25326. t.join();
  25327. ASSERT_FALSE(svr.is_running());
  25328. });
  25329. svr.wait_until_ready();
  25330. client(port);
  25331. }
  25332. TEST(UnreadBodyDrainTest, LongerThanTheLimitClosesTheConnection) {
  25333. Server svr;
  25334. serve_redirects(svr, [](int port) {
  25335. auto body = std::string(CPPHTTPLIB_UNREAD_PAYLOAD_MAX_LENGTH + 1, 'x');
  25336. auto req = "POST / HTTP/1.1\r\nHost: localhost\r\nContent-Length: " +
  25337. std::to_string(body.size()) + "\r\n\r\n" + body +
  25338. "GET / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  25339. std::string resp;
  25340. ASSERT_TRUE(send_request(1, req, &resp, port));
  25341. ASSERT_EQ(0u, resp.find("HTTP/1.1 302"));
  25342. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  25343. });
  25344. }
  25345. TEST(UnreadBodyDrainTest, SlowerThanTheReadTimeoutClosesTheConnection) {
  25346. Server svr;
  25347. svr.set_read_timeout(0, 200000);
  25348. serve_redirects(svr, [](int port) {
  25349. // A byte every 100 ms keeps each read within the read timeout, but not the
  25350. // body as a whole, so the server closes and the bytes sent after that fail.
  25351. std::vector<std::string> parts{"POST / HTTP/1.1\r\nHost: localhost\r\n"
  25352. "Content-Length: 10\r\n\r\n"};
  25353. parts.resize(11, "x");
  25354. EXPECT_FALSE(send_request_in_parts(1, parts, nullptr, port));
  25355. });
  25356. }
  25357. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  25358. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  25359. // must be rejected with 400 Bad Request.
  25360. Server svr;
  25361. svr.Post("/test", [&](const Request &, Response &res) {
  25362. res.set_content("ok", "text/plain");
  25363. });
  25364. thread t = thread([&] { svr.listen(HOST, PORT); });
  25365. auto se = detail::scope_exit([&] {
  25366. svr.stop();
  25367. t.join();
  25368. ASSERT_FALSE(svr.is_running());
  25369. });
  25370. svr.wait_until_ready();
  25371. // Exact "chunked"
  25372. {
  25373. auto req = "POST /test HTTP/1.1\r\n"
  25374. "Host: localhost\r\n"
  25375. "Content-Length: 5\r\n"
  25376. "Transfer-Encoding: chunked\r\n"
  25377. "Connection: close\r\n"
  25378. "\r\n"
  25379. "hello";
  25380. std::string response;
  25381. ASSERT_TRUE(send_request(1, req, &response));
  25382. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25383. response.substr(0, response.find("\r\n")));
  25384. }
  25385. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  25386. {
  25387. auto req = "POST /test HTTP/1.1\r\n"
  25388. "Host: localhost\r\n"
  25389. "Content-Length: 5\r\n"
  25390. "Transfer-Encoding: gzip, chunked\r\n"
  25391. "Connection: close\r\n"
  25392. "\r\n"
  25393. "hello";
  25394. std::string response;
  25395. ASSERT_TRUE(send_request(1, req, &response));
  25396. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25397. response.substr(0, response.find("\r\n")));
  25398. }
  25399. }
  25400. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  25401. Server svr;
  25402. svr.Post("/test", [&](const Request &, Response &res) {
  25403. res.set_content("ok", "text/plain");
  25404. });
  25405. thread t = thread([&] { svr.listen(HOST, PORT); });
  25406. auto se = detail::scope_exit([&] {
  25407. svr.stop();
  25408. t.join();
  25409. ASSERT_FALSE(svr.is_running());
  25410. });
  25411. svr.wait_until_ready();
  25412. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  25413. // length cannot be determined, so the server must answer 400 and close
  25414. // rather than treat the request as bodyless and leave the body in the
  25415. // socket for the next request to pick up.
  25416. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  25417. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  25418. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  25419. std::string response;
  25420. ASSERT_TRUE(send_request(1, req, &response));
  25421. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25422. response.substr(0, response.find("\r\n")))
  25423. << transfer_encoding;
  25424. }
  25425. // RFC 9110 5.3: the codings may also be split across several
  25426. // Transfer-Encoding lines, which combine in the order they were received.
  25427. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  25428. // just like the single-line "chunked, gzip" above.
  25429. {
  25430. auto req = "POST /test HTTP/1.1\r\n"
  25431. "Host: localhost\r\n"
  25432. "Transfer-Encoding: chunked\r\n"
  25433. "Transfer-Encoding: gzip\r\n"
  25434. "\r\n"
  25435. "0\r\n\r\n";
  25436. std::string response;
  25437. ASSERT_TRUE(send_request(1, req, &response));
  25438. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  25439. response.substr(0, response.find("\r\n")));
  25440. }
  25441. }
  25442. TEST(RequestSmugglingTest, TransferEncodingOtherThanChunkedNotImplemented) {
  25443. Server svr;
  25444. svr.Post("/test", [&](const Request &, Response &res) {
  25445. res.set_content("ok", "text/plain");
  25446. });
  25447. auto port = svr.bind_to_any_port(HOST);
  25448. ASSERT_GT(port, 0);
  25449. thread t = thread([&] { svr.listen_after_bind(); });
  25450. auto se = detail::scope_exit([&] {
  25451. svr.stop();
  25452. t.join();
  25453. ASSERT_FALSE(svr.is_running());
  25454. });
  25455. svr.wait_until_ready();
  25456. for (auto transfer_encoding :
  25457. {"Transfer-Encoding: gzip, chunked\r\n",
  25458. "Transfer-Encoding: gzip\r\nTransfer-Encoding: chunked\r\n",
  25459. "Transfer-Encoding: chunked\r\nTransfer-Encoding: chunked\r\n"}) {
  25460. auto req = std::string("POST /test HTTP/1.1\r\nHost: localhost\r\n") +
  25461. transfer_encoding + "\r\n0\r\n\r\n";
  25462. std::string response;
  25463. ASSERT_TRUE(send_request(1, req, &response, port)) << transfer_encoding;
  25464. EXPECT_EQ("HTTP/1.1 501 Not Implemented",
  25465. response.substr(0, response.find("\r\n")))
  25466. << transfer_encoding;
  25467. EXPECT_NE(std::string::npos, response.find("Connection: close"))
  25468. << transfer_encoding;
  25469. }
  25470. }
  25471. // Regression for issue #2450: a DELETE without Content-Length on a
  25472. // keep-alive connection must not let the post-response drain consume the
  25473. // next request's bytes.
  25474. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  25475. Server svr;
  25476. std::atomic<int> delete_count(0);
  25477. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  25478. delete_count++;
  25479. res.status = StatusCode::NoContent_204;
  25480. });
  25481. auto port = svr.bind_to_any_port(HOST);
  25482. thread t = thread([&] { svr.listen_after_bind(); });
  25483. auto se = detail::scope_exit([&] {
  25484. svr.stop();
  25485. t.join();
  25486. });
  25487. svr.wait_until_ready();
  25488. auto error = Error::Success;
  25489. auto sock = detail::create_client_socket(
  25490. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25491. /*connection_timeout_sec=*/2, 0,
  25492. /*read_timeout_sec=*/2, 0,
  25493. /*write_timeout_sec=*/2, 0, std::string(), error);
  25494. ASSERT_NE(INVALID_SOCKET, sock);
  25495. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25496. auto send_request_and_read_response = [&](const std::string &req,
  25497. std::string &out) -> bool {
  25498. auto sent = detail::send_socket(sock, req.data(), req.size(), 0);
  25499. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  25500. char buf[4096];
  25501. for (;;) {
  25502. auto n = recv(sock, buf, sizeof(buf), 0);
  25503. if (n <= 0) { return !out.empty(); }
  25504. out.append(buf, static_cast<size_t>(n));
  25505. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  25506. }
  25507. };
  25508. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  25509. "Host: localhost\r\n"
  25510. "\r\n";
  25511. std::string resp1;
  25512. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  25513. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  25514. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  25515. "Host: localhost\r\n"
  25516. "Connection: close\r\n"
  25517. "\r\n";
  25518. std::string resp2;
  25519. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  25520. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  25521. EXPECT_EQ(2, delete_count.load());
  25522. }
  25523. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  25524. Server svr;
  25525. svr.Post("/ingest", [&](const Request &, Response &res,
  25526. const ContentReader &content_reader) {
  25527. auto consumed = content_reader([](const char *, size_t) { return false; });
  25528. EXPECT_FALSE(consumed);
  25529. res.status = StatusCode::Conflict_409;
  25530. res.set_header("Connection", "close");
  25531. });
  25532. auto port = svr.bind_to_any_port(HOST);
  25533. thread t = thread([&] { svr.listen_after_bind(); });
  25534. auto se = detail::scope_exit([&] {
  25535. svr.stop();
  25536. t.join();
  25537. });
  25538. svr.wait_until_ready();
  25539. auto error = Error::Success;
  25540. auto sock = detail::create_client_socket(
  25541. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  25542. /*connection_timeout_sec=*/2, 0,
  25543. /*read_timeout_sec=*/1, 0,
  25544. /*write_timeout_sec=*/2, 0, std::string(), error);
  25545. ASSERT_NE(INVALID_SOCKET, sock);
  25546. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  25547. std::string request = "POST /ingest HTTP/1.1\r\n"
  25548. "Host: localhost\r\n"
  25549. "Transfer-Encoding: chunked\r\n"
  25550. "\r\n"
  25551. "4\r\n"
  25552. "data\r\n";
  25553. auto sent = detail::send_socket(sock, request.data(), request.size(), 0);
  25554. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  25555. std::string response;
  25556. ssize_t received = 0;
  25557. do {
  25558. char buf[4096];
  25559. received = recv(sock, buf, sizeof(buf), 0);
  25560. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  25561. } while (received > 0);
  25562. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  25563. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  25564. EXPECT_EQ(0, received);
  25565. }
  25566. namespace no_proxy_test {
  25567. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  25568. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  25569. // calling listen().
  25570. class ScopedServer {
  25571. public:
  25572. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  25573. ~ScopedServer() {
  25574. svr_.stop();
  25575. if (th_.joinable()) { th_.join(); }
  25576. }
  25577. Server &svr() { return svr_; }
  25578. int port() const { return port_; }
  25579. void listen() {
  25580. th_ = std::thread([this] { svr_.listen_after_bind(); });
  25581. svr_.wait_until_ready();
  25582. }
  25583. private:
  25584. Server svr_;
  25585. std::thread th_;
  25586. int port_ = 0;
  25587. };
  25588. class ProxyAndTargetServers {
  25589. public:
  25590. ProxyAndTargetServers() {
  25591. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  25592. proxy_hits_++;
  25593. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25594. res.set_content("via-proxy", "text/plain");
  25595. });
  25596. target_.Get(".*", [this](const Request &req, Response &res) {
  25597. target_hits_++;
  25598. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  25599. res.set_content("direct", "text/plain");
  25600. });
  25601. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  25602. target_port_ = target_.bind_to_any_port("127.0.0.1");
  25603. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  25604. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  25605. proxy_mock_.wait_until_ready();
  25606. target_.wait_until_ready();
  25607. }
  25608. ~ProxyAndTargetServers() {
  25609. proxy_mock_.stop();
  25610. target_.stop();
  25611. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  25612. if (target_thread_.joinable()) { target_thread_.join(); }
  25613. }
  25614. Server &proxy_mock() { return proxy_mock_; }
  25615. Server &target() { return target_; }
  25616. int proxy_port() const { return proxy_port_; }
  25617. int target_port() const { return target_port_; }
  25618. int proxy_hits() const { return proxy_hits_.load(); }
  25619. int target_hits() const { return target_hits_.load(); }
  25620. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  25621. void reset_counters() {
  25622. proxy_hits_ = 0;
  25623. target_hits_ = 0;
  25624. last_had_proxy_authz_ = false;
  25625. }
  25626. private:
  25627. Server proxy_mock_;
  25628. Server target_;
  25629. std::thread proxy_thread_;
  25630. std::thread target_thread_;
  25631. int proxy_port_ = 0;
  25632. int target_port_ = 0;
  25633. std::atomic<int> proxy_hits_{0};
  25634. std::atomic<int> target_hits_{0};
  25635. std::atomic<bool> last_had_proxy_authz_{false};
  25636. };
  25637. inline std::unique_ptr<Client> make_client(const std::string &host,
  25638. ProxyAndTargetServers &s) {
  25639. auto cli = detail::make_unique<Client>(host, s.target_port());
  25640. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  25641. cli->set_proxy("127.0.0.1", s.proxy_port());
  25642. return cli;
  25643. }
  25644. } // namespace no_proxy_test
  25645. using no_proxy_test::make_client;
  25646. using no_proxy_test::ProxyAndTargetServers;
  25647. // A stream request carries the credentials a buffered request does
  25648. TEST(StreamRequestHeadTest, SendsTheClientsCredentials) {
  25649. no_proxy_test::ScopedServer origin;
  25650. origin.svr().Get("/x", [](const Request &req, Response &res) {
  25651. res.set_content(req.get_header_value("Authorization"), "text/plain");
  25652. });
  25653. origin.listen();
  25654. Client cli("127.0.0.1", origin.port());
  25655. cli.set_basic_auth("user", "pass");
  25656. auto handle = cli.open_stream("GET", "/x");
  25657. ASSERT_TRUE(handle.is_valid());
  25658. EXPECT_EQ("Basic dXNlcjpwYXNz", read_all(handle));
  25659. Client bearer("127.0.0.1", origin.port());
  25660. bearer.set_bearer_token_auth("tok");
  25661. auto handle2 = bearer.open_stream("GET", "/x");
  25662. ASSERT_TRUE(handle2.is_valid());
  25663. EXPECT_EQ("Bearer tok", read_all(handle2));
  25664. }
  25665. // A plain HTTP proxy reads the target in absolute-form (RFC 9112 3.2.2) and
  25666. // takes its own credentials, as for a buffered request
  25667. TEST(StreamRequestHeadTest, GoesThroughAPlainHttpProxy) {
  25668. std::string target, authz, proxy_authz;
  25669. no_proxy_test::ScopedServer proxy;
  25670. proxy.svr().Get(".*", [&](const Request &req, Response &res) {
  25671. target = req.target;
  25672. authz = req.get_header_value("Authorization");
  25673. proxy_authz = req.get_header_value("Proxy-Authorization");
  25674. res.set_content("ok", "text/plain");
  25675. });
  25676. proxy.listen();
  25677. Client cli("origin.example", 8080);
  25678. cli.set_proxy("127.0.0.1", proxy.port());
  25679. cli.set_proxy_basic_auth("puser", "ppass");
  25680. cli.set_basic_auth("user", "pass");
  25681. auto handle = cli.open_stream("GET", "/x");
  25682. ASSERT_TRUE(handle.is_valid());
  25683. EXPECT_EQ("ok", read_all(handle));
  25684. EXPECT_EQ("http://origin.example:8080/x", target);
  25685. EXPECT_EQ("Basic dXNlcjpwYXNz", authz);
  25686. EXPECT_EQ("Basic cHVzZXI6cHBhc3M=", proxy_authz);
  25687. }
  25688. TEST(NoProxyTest, ExactHostnameBypasses) {
  25689. ProxyAndTargetServers s;
  25690. auto cli = make_client("example.com", s);
  25691. cli->set_no_proxy({"example.com"});
  25692. auto res = cli->Get("/");
  25693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25694. EXPECT_EQ(0, s.proxy_hits());
  25695. EXPECT_EQ(1, s.target_hits());
  25696. }
  25697. TEST(NoProxyTest, SubdomainBypasses) {
  25698. ProxyAndTargetServers s;
  25699. auto cli = make_client("foo.example.com", s);
  25700. cli->set_no_proxy({"example.com"});
  25701. auto res = cli->Get("/");
  25702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25703. EXPECT_EQ(0, s.proxy_hits());
  25704. EXPECT_EQ(1, s.target_hits());
  25705. }
  25706. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  25707. // Regression guard: "evilexample.com" must not be considered a subdomain
  25708. // of "example.com". Without the dot-boundary rule, a naive endsWith
  25709. // check would let traffic bypass the proxy and leak credentials direct
  25710. // to the attacker host.
  25711. ProxyAndTargetServers s;
  25712. auto cli = make_client("evilexample.com", s);
  25713. cli->set_no_proxy({"example.com"});
  25714. auto res = cli->Get("/");
  25715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25716. EXPECT_GE(s.proxy_hits(), 1);
  25717. EXPECT_EQ(0, s.target_hits());
  25718. }
  25719. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  25720. ProxyAndTargetServers s;
  25721. auto cli = make_client("example.com.evil.com", s);
  25722. cli->set_no_proxy({"example.com"});
  25723. auto res = cli->Get("/");
  25724. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25725. EXPECT_GE(s.proxy_hits(), 1);
  25726. EXPECT_EQ(0, s.target_hits());
  25727. }
  25728. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  25729. ProxyAndTargetServers s;
  25730. auto cli = make_client("example.com", s);
  25731. cli->set_no_proxy({".example.com"});
  25732. auto res = cli->Get("/");
  25733. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25734. EXPECT_EQ(0, s.proxy_hits());
  25735. EXPECT_EQ(1, s.target_hits());
  25736. }
  25737. TEST(NoProxyTest, CaseInsensitiveHostname) {
  25738. ProxyAndTargetServers s;
  25739. auto cli = make_client("Example.COM", s);
  25740. cli->set_no_proxy({"EXAMPLE.com"});
  25741. auto res = cli->Get("/");
  25742. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25743. EXPECT_EQ(0, s.proxy_hits());
  25744. EXPECT_EQ(1, s.target_hits());
  25745. }
  25746. TEST(NoProxyTest, TrailingDotIsNormalized) {
  25747. ProxyAndTargetServers s;
  25748. auto cli = make_client("example.com.", s);
  25749. cli->set_no_proxy({"example.com"});
  25750. auto res = cli->Get("/");
  25751. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25752. EXPECT_EQ(0, s.proxy_hits());
  25753. EXPECT_EQ(1, s.target_hits());
  25754. }
  25755. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  25756. // Trailing dots must be normalized on BOTH sides — host and entry.
  25757. // An implementation that only strips the host-side trailing dot would
  25758. // fail to match host "example.com" against entry "example.com." because
  25759. // a literal substring search would compare 11 chars against 12.
  25760. ProxyAndTargetServers s;
  25761. auto cli = make_client("example.com", s);
  25762. cli->set_no_proxy({"example.com."});
  25763. auto res = cli->Get("/");
  25764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25765. EXPECT_EQ(0, s.proxy_hits());
  25766. EXPECT_EQ(1, s.target_hits());
  25767. }
  25768. TEST(NoProxyTest, WildcardBypassesEverything) {
  25769. ProxyAndTargetServers s;
  25770. auto cli = make_client("anything.invalid.test", s);
  25771. cli->set_no_proxy({"*"});
  25772. auto res = cli->Get("/");
  25773. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25774. EXPECT_EQ(0, s.proxy_hits());
  25775. EXPECT_EQ(1, s.target_hits());
  25776. }
  25777. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  25778. ProxyAndTargetServers s;
  25779. Client cli("127.0.0.1", s.target_port());
  25780. cli.set_proxy("127.0.0.1", s.proxy_port());
  25781. cli.set_no_proxy({"127.0.0.1"});
  25782. auto res = cli.Get("/");
  25783. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25784. EXPECT_EQ(0, s.proxy_hits());
  25785. EXPECT_EQ(1, s.target_hits());
  25786. }
  25787. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  25788. ProxyAndTargetServers s;
  25789. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  25790. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  25791. cli.set_proxy("127.0.0.1", s.proxy_port());
  25792. cli.set_no_proxy({"::1"});
  25793. auto res = cli.Get("/");
  25794. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25795. EXPECT_EQ(0, s.proxy_hits());
  25796. EXPECT_EQ(1, s.target_hits());
  25797. }
  25798. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  25799. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  25800. // must still be recognized as IPv6 for CIDR matching. Implementations
  25801. // that detect IPv6 only when the host begins with '[' would parse the
  25802. // host as a hostname and miss the match.
  25803. ProxyAndTargetServers s;
  25804. Client cli("fe80::1", s.target_port());
  25805. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25806. cli.set_proxy("127.0.0.1", s.proxy_port());
  25807. cli.set_no_proxy({"fe80::/10"});
  25808. auto res = cli.Get("/");
  25809. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25810. EXPECT_EQ(0, s.proxy_hits());
  25811. EXPECT_EQ(1, s.target_hits());
  25812. }
  25813. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  25814. ProxyAndTargetServers s;
  25815. Client cli("::1", s.target_port());
  25816. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  25817. cli.set_proxy("127.0.0.1", s.proxy_port());
  25818. cli.set_no_proxy({"[::1]"});
  25819. auto res = cli.Get("/");
  25820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25821. EXPECT_EQ(0, s.proxy_hits());
  25822. EXPECT_EQ(1, s.target_hits());
  25823. }
  25824. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  25825. ProxyAndTargetServers s;
  25826. Client cli("fe80::1", s.target_port());
  25827. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  25828. cli.set_proxy("127.0.0.1", s.proxy_port());
  25829. cli.set_no_proxy({"[fe80::]/10"});
  25830. auto res = cli.Get("/");
  25831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25832. EXPECT_EQ(0, s.proxy_hits());
  25833. EXPECT_EQ(1, s.target_hits());
  25834. }
  25835. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  25836. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  25837. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  25838. // tricks via address-family conversion.
  25839. ProxyAndTargetServers s;
  25840. Client cli("::ffff:127.0.0.1", s.target_port());
  25841. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  25842. cli.set_proxy("127.0.0.1", s.proxy_port());
  25843. cli.set_no_proxy({"127.0.0.1"});
  25844. auto res = cli.Get("/");
  25845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25846. EXPECT_GE(s.proxy_hits(), 1);
  25847. EXPECT_EQ(0, s.target_hits());
  25848. }
  25849. TEST(NoProxyTest, IPv4CidrMatch) {
  25850. ProxyAndTargetServers s;
  25851. Client cli("127.0.0.1", s.target_port());
  25852. cli.set_proxy("127.0.0.1", s.proxy_port());
  25853. cli.set_no_proxy({"127.0.0.0/8"});
  25854. auto res = cli.Get("/");
  25855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25856. EXPECT_EQ(0, s.proxy_hits());
  25857. EXPECT_EQ(1, s.target_hits());
  25858. }
  25859. TEST(NoProxyTest, IPv4CidrNonMatch) {
  25860. ProxyAndTargetServers s;
  25861. Client cli("127.0.0.1", s.target_port());
  25862. cli.set_proxy("127.0.0.1", s.proxy_port());
  25863. cli.set_no_proxy({"10.0.0.0/8"});
  25864. auto res = cli.Get("/");
  25865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25866. EXPECT_GE(s.proxy_hits(), 1);
  25867. EXPECT_EQ(0, s.target_hits());
  25868. }
  25869. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  25870. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  25871. // IPv4 target matches.
  25872. ProxyAndTargetServers s;
  25873. Client cli("127.0.0.1", s.target_port());
  25874. cli.set_proxy("127.0.0.1", s.proxy_port());
  25875. cli.set_no_proxy({"0.0.0.0/0"});
  25876. auto res = cli.Get("/");
  25877. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25878. EXPECT_EQ(0, s.proxy_hits());
  25879. EXPECT_EQ(1, s.target_hits());
  25880. }
  25881. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  25882. ProxyAndTargetServers s;
  25883. Client cli("127.0.0.1", s.target_port());
  25884. cli.set_proxy("127.0.0.1", s.proxy_port());
  25885. cli.set_no_proxy({"127.0.0.1"});
  25886. auto res = cli.Get("/");
  25887. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25888. EXPECT_EQ(0, s.proxy_hits());
  25889. EXPECT_EQ(1, s.target_hits());
  25890. }
  25891. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  25892. ProxyAndTargetServers s;
  25893. Client cli("127.0.0.1", s.target_port());
  25894. cli.set_proxy("127.0.0.1", s.proxy_port());
  25895. cli.set_no_proxy({"127.0.0.0/33"});
  25896. auto res = cli.Get("/");
  25897. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25898. EXPECT_GE(s.proxy_hits(), 1);
  25899. EXPECT_EQ(0, s.target_hits());
  25900. }
  25901. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  25902. // Empty prefix after the slash must be rejected, not silently treated as /32.
  25903. ProxyAndTargetServers s;
  25904. Client cli("127.0.0.1", s.target_port());
  25905. cli.set_proxy("127.0.0.1", s.proxy_port());
  25906. cli.set_no_proxy({"127.0.0.1/"});
  25907. auto res = cli.Get("/");
  25908. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25909. EXPECT_GE(s.proxy_hits(), 1);
  25910. EXPECT_EQ(0, s.target_hits());
  25911. }
  25912. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  25913. ProxyAndTargetServers s;
  25914. auto cli = make_client("internal.corp", s);
  25915. cli->set_proxy_basic_auth("u", "p");
  25916. cli->set_no_proxy({"internal.corp"});
  25917. auto res = cli->Get("/");
  25918. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25919. EXPECT_EQ(1, s.target_hits());
  25920. EXPECT_EQ(0, s.proxy_hits());
  25921. EXPECT_FALSE(s.last_had_proxy_authz())
  25922. << "Proxy-Authorization must not be sent direct to the target";
  25923. }
  25924. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  25925. ProxyAndTargetServers s;
  25926. auto cli = make_client("public.example", s);
  25927. cli->set_proxy_basic_auth("u", "p");
  25928. cli->set_no_proxy({"internal.corp"}); // does not match
  25929. auto res = cli->Get("/");
  25930. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25931. EXPECT_GE(s.proxy_hits(), 1);
  25932. EXPECT_TRUE(s.last_had_proxy_authz());
  25933. }
  25934. TEST(NoProxyTest, ProxyAuthorizationSentWithOneEmptyCredential) {
  25935. std::atomic<int> hits{0};
  25936. std::atomic<int> hits_with_authz{0};
  25937. no_proxy_test::ScopedServer proxy_mock;
  25938. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  25939. hits++;
  25940. if (req.has_header("Proxy-Authorization")) { hits_with_authz++; }
  25941. if (req.target.find("/redir") != std::string::npos) {
  25942. res.set_redirect("http://other.example/landed");
  25943. } else {
  25944. res.set_content("via-proxy", "text/plain");
  25945. }
  25946. });
  25947. proxy_mock.listen();
  25948. for (const auto &c : {std::make_pair("u", ""), std::make_pair("", "p")}) {
  25949. hits = 0;
  25950. hits_with_authz = 0;
  25951. Client cli("public.example", 80);
  25952. cli.set_proxy("127.0.0.1", proxy_mock.port());
  25953. cli.set_proxy_basic_auth(c.first, c.second);
  25954. cli.set_follow_location(true);
  25955. // The redirect to another host goes through the proxy as well
  25956. auto res = cli.Get("/redir");
  25957. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25958. EXPECT_EQ(2, hits.load());
  25959. EXPECT_EQ(2, hits_with_authz.load());
  25960. }
  25961. }
  25962. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  25963. ProxyAndTargetServers s;
  25964. auto cli = make_client("anything.test", s);
  25965. auto res = cli->Get("/");
  25966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25967. EXPECT_GE(s.proxy_hits(), 1);
  25968. EXPECT_EQ(0, s.target_hits());
  25969. }
  25970. TEST(NoProxyTest, PortSpecificEntryRejected) {
  25971. ProxyAndTargetServers s;
  25972. auto cli = make_client("example.com", s);
  25973. cli->set_no_proxy({"example.com:8080"});
  25974. auto res = cli->Get("/");
  25975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25976. EXPECT_GE(s.proxy_hits(), 1);
  25977. EXPECT_EQ(0, s.target_hits());
  25978. }
  25979. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  25980. ProxyAndTargetServers s;
  25981. auto cli = make_client("anything.test", s);
  25982. cli->set_no_proxy({"", " ", "\t"});
  25983. auto res = cli->Get("/");
  25984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25985. EXPECT_GE(s.proxy_hits(), 1);
  25986. EXPECT_EQ(0, s.target_hits());
  25987. }
  25988. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  25989. // An entry with leading/trailing whitespace must still match — env-style
  25990. // values are commonly pasted with stray spaces and an implementation
  25991. // that feeds the raw token directly to inet_pton would fail to match
  25992. // valid CIDRs because of the spaces.
  25993. ProxyAndTargetServers s;
  25994. Client cli("127.0.0.1", s.target_port());
  25995. cli.set_proxy("127.0.0.1", s.proxy_port());
  25996. cli.set_no_proxy({" 127.0.0.0/8 "});
  25997. auto res = cli.Get("/");
  25998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  25999. EXPECT_EQ(0, s.proxy_hits());
  26000. EXPECT_EQ(1, s.target_hits());
  26001. }
  26002. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  26003. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  26004. // go direct and must NOT carry Proxy-Authorization.
  26005. std::atomic<int> proxy_hits{0};
  26006. std::atomic<int> target_hits{0};
  26007. std::atomic<bool> target_saw_authz{false};
  26008. no_proxy_test::ScopedServer proxy_mock, target;
  26009. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26010. proxy_hits++;
  26011. res.status = 302;
  26012. res.set_header("Location", "http://127.0.0.1:" +
  26013. std::to_string(target.port()) + "/landed");
  26014. });
  26015. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26016. target_hits++;
  26017. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  26018. res.set_content("direct", "text/plain");
  26019. });
  26020. proxy_mock.listen();
  26021. target.listen();
  26022. Client cli("public.example", target.port());
  26023. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26024. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26025. cli.set_proxy_basic_auth("u", "p");
  26026. cli.set_no_proxy({"127.0.0.1"});
  26027. cli.set_follow_location(true);
  26028. auto res = cli.Get("/redir");
  26029. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26030. EXPECT_GE(proxy_hits.load(), 1);
  26031. EXPECT_GE(target_hits.load(), 1);
  26032. EXPECT_FALSE(target_saw_authz.load());
  26033. }
  26034. #ifdef CPPHTTPLIB_SSL_ENABLED
  26035. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  26036. // Direct origin replying 407 must not trigger the digest retry; otherwise
  26037. // proxy creds would be sent to the (possibly hostile) origin.
  26038. std::atomic<int> target_hits{0};
  26039. std::atomic<bool> target_saw_proxy_authz{false};
  26040. no_proxy_test::ScopedServer target;
  26041. target.svr().Get(".*", [&](const Request &req, Response &res) {
  26042. target_hits++;
  26043. if (req.has_header("Proxy-Authorization")) {
  26044. target_saw_proxy_authz = true;
  26045. }
  26046. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26047. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  26048. "nonce=\"abc\", algorithm=MD5");
  26049. });
  26050. target.listen();
  26051. // The proxy address is set to the target's port: the bypass MUST kick in;
  26052. // if it doesn't, the test still routes "via proxy" to the same server and
  26053. // the Proxy-Authorization assertion below catches the leak.
  26054. Client cli("evil.example", target.port());
  26055. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  26056. cli.set_proxy("127.0.0.1", target.port());
  26057. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26058. cli.set_no_proxy({"evil.example"});
  26059. auto res = cli.Get("/x");
  26060. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26061. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26062. EXPECT_EQ(1, target_hits.load());
  26063. EXPECT_FALSE(target_saw_proxy_authz.load());
  26064. }
  26065. #endif
  26066. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  26067. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  26068. std::atomic<int> proxy_hits{0};
  26069. std::atomic<int> bypass_hits{0};
  26070. std::atomic<bool> proxy_saw_c_url{false};
  26071. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  26072. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  26073. proxy_hits++;
  26074. if (req.path.find("/start") != std::string::npos) {
  26075. res.status = 302;
  26076. res.set_header("Location", "http://127.0.0.1:" +
  26077. std::to_string(bypass_server.port()) +
  26078. "/middle");
  26079. return;
  26080. }
  26081. if (req.path.find("/end") != std::string::npos) {
  26082. proxy_saw_c_url = true;
  26083. res.set_content("c-via-proxy", "text/plain");
  26084. return;
  26085. }
  26086. res.set_content("unexpected", "text/plain");
  26087. });
  26088. // public.example's "advertised" port is arbitrary (the request never lands
  26089. // there — it goes through the proxy), but use a dynamic value to stay
  26090. // friendly with sharded parallel runs.
  26091. int public_port = bypass_server.port();
  26092. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  26093. bypass_hits++;
  26094. res.status = 302;
  26095. res.set_header("Location", "http://public.example:" +
  26096. std::to_string(public_port) + "/end");
  26097. });
  26098. proxy_mock.listen();
  26099. bypass_server.listen();
  26100. Client cli("public.example", public_port);
  26101. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26102. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26103. cli.set_no_proxy({"127.0.0.1"});
  26104. cli.set_follow_location(true);
  26105. auto res = cli.Get("/start");
  26106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26107. EXPECT_EQ(StatusCode::OK_200, res->status);
  26108. EXPECT_EQ("c-via-proxy", res->body);
  26109. EXPECT_GE(proxy_hits.load(), 2);
  26110. EXPECT_GE(bypass_hits.load(), 1);
  26111. EXPECT_TRUE(proxy_saw_c_url.load());
  26112. }
  26113. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  26114. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  26115. // request reconnects to the correct endpoint.
  26116. std::atomic<int> proxy_hits{0};
  26117. std::atomic<int> target_hits{0};
  26118. no_proxy_test::ScopedServer proxy_mock, target;
  26119. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  26120. proxy_hits++;
  26121. res.set_content("via-proxy", "text/plain");
  26122. });
  26123. target.svr().Get(".*", [&](const Request &, Response &res) {
  26124. target_hits++;
  26125. res.set_content("direct", "text/plain");
  26126. });
  26127. proxy_mock.listen();
  26128. target.listen();
  26129. Client cli("public.example", target.port());
  26130. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  26131. cli.set_proxy("127.0.0.1", proxy_mock.port());
  26132. cli.set_keep_alive(true);
  26133. auto res1 = cli.Get("/a");
  26134. ASSERT_TRUE(res1);
  26135. EXPECT_EQ("via-proxy", res1->body);
  26136. EXPECT_EQ(1, proxy_hits.load());
  26137. EXPECT_EQ(0, target_hits.load());
  26138. cli.set_no_proxy({"public.example"});
  26139. auto res2 = cli.Get("/b");
  26140. ASSERT_TRUE(res2);
  26141. EXPECT_EQ("direct", res2->body);
  26142. EXPECT_EQ(1, proxy_hits.load());
  26143. EXPECT_EQ(1, target_hits.load());
  26144. }
  26145. // Forward declarations (see the base64_encode note).
  26146. namespace httplib {
  26147. namespace detail {
  26148. ssize_t select_read(socket_t sock, time_t sec, time_t usec);
  26149. int shutdown_socket(socket_t sock) noexcept;
  26150. } // namespace detail
  26151. } // namespace httplib
  26152. namespace proxy_tunnel_test {
  26153. const char *const kTunnelEstablished =
  26154. "HTTP/1.1 200 Connection established\r\n\r\n";
  26155. // Answers the head of a CONNECT request; a 200 opens the tunnel.
  26156. using ConnectReply = std::function<std::string(const std::string &head)>;
  26157. // Accepts CONNECT on 127.0.0.1, answers it with `reply` (200 by default) and,
  26158. // once tunnelled, byte-forwards to 127.0.0.1:forward_port.
  26159. class ScopedConnectProxy {
  26160. public:
  26161. explicit ScopedConnectProxy(int forward_port, ConnectReply reply = nullptr)
  26162. : forward_port_(forward_port), reply_(std::move(reply)) {
  26163. listen_sock_ = ::socket(AF_INET, SOCK_STREAM, 0);
  26164. if (listen_sock_ == INVALID_SOCKET) { return; }
  26165. auto a = loopback(0);
  26166. auto addr = reinterpret_cast<sockaddr *>(&a);
  26167. socklen_t alen = sizeof(a);
  26168. if (::bind(listen_sock_, addr, sizeof(a)) != 0 ||
  26169. ::getsockname(listen_sock_, addr, &alen) != 0 ||
  26170. ::listen(listen_sock_, 4) != 0) {
  26171. return;
  26172. }
  26173. port_ = ntohs(a.sin_port);
  26174. th_ = std::thread([this] { run(); });
  26175. }
  26176. ~ScopedConnectProxy() {
  26177. if (th_.joinable()) {
  26178. stop_ = true;
  26179. auto wake = connect_to(port_);
  26180. th_.join();
  26181. if (wake != INVALID_SOCKET) { detail::close_socket(wake); }
  26182. }
  26183. if (listen_sock_ != INVALID_SOCKET) { detail::close_socket(listen_sock_); }
  26184. }
  26185. int port() const { return port_; }
  26186. int connect_hits() const { return connect_hits_.load(); }
  26187. // Head of the last CONNECT request, as the proxy saw it on the wire.
  26188. std::string connect_request() const {
  26189. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26190. return connect_request_;
  26191. }
  26192. private:
  26193. static sockaddr_in loopback(int port) {
  26194. sockaddr_in a{};
  26195. a.sin_family = AF_INET;
  26196. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  26197. a.sin_port = htons(static_cast<unsigned short>(port));
  26198. return a;
  26199. }
  26200. static socket_t connect_to(int port) {
  26201. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  26202. if (sock == INVALID_SOCKET) { return sock; }
  26203. auto a = loopback(port);
  26204. if (::connect(sock, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  26205. detail::close_socket(sock);
  26206. return INVALID_SOCKET;
  26207. }
  26208. return sock;
  26209. }
  26210. static bool send_all(socket_t sock, const char *data, size_t size) {
  26211. while (size > 0) {
  26212. auto n = detail::send_socket(sock, data, size, 0);
  26213. if (n <= 0) { return false; }
  26214. data += n;
  26215. size -= static_cast<size_t>(n);
  26216. }
  26217. return true;
  26218. }
  26219. void run() {
  26220. for (;;) {
  26221. auto client = ::accept(listen_sock_, nullptr, nullptr);
  26222. if (stop_) {
  26223. if (client != INVALID_SOCKET) { detail::close_socket(client); }
  26224. return;
  26225. }
  26226. if (client == INVALID_SOCKET) { continue; }
  26227. serve(client);
  26228. detail::close_socket(client);
  26229. }
  26230. }
  26231. void serve(socket_t client) {
  26232. std::string head;
  26233. char buf[2048];
  26234. while (head.find("\r\n\r\n") == std::string::npos) {
  26235. if (detail::select_read(client, 5, 0) <= 0) { return; }
  26236. auto n = detail::read_socket(client, buf, sizeof(buf), 0);
  26237. if (n <= 0) { return; }
  26238. head.append(buf, static_cast<size_t>(n));
  26239. }
  26240. if (head.compare(0, 8, "CONNECT ") != 0) { return; }
  26241. connect_hits_++;
  26242. {
  26243. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  26244. connect_request_ = head;
  26245. }
  26246. auto res = reply_ ? reply_(head) : std::string(kTunnelEstablished);
  26247. if (!send_all(client, res.data(), res.size()) ||
  26248. res.compare(0, 12, "HTTP/1.1 200") != 0) {
  26249. return;
  26250. }
  26251. auto origin = connect_to(forward_port_);
  26252. if (origin == INVALID_SOCKET) { return; }
  26253. // When either side stops, shut both down so the other pump returns too.
  26254. auto pump = [&](socket_t from, socket_t to) {
  26255. char b[8192];
  26256. for (;;) {
  26257. auto n = detail::read_socket(from, b, sizeof(b), 0);
  26258. if (n <= 0 || !send_all(to, b, static_cast<size_t>(n))) { break; }
  26259. }
  26260. detail::shutdown_socket(client);
  26261. detail::shutdown_socket(origin);
  26262. };
  26263. std::thread up([&] { pump(client, origin); });
  26264. pump(origin, client);
  26265. up.join();
  26266. detail::close_socket(origin);
  26267. }
  26268. int forward_port_;
  26269. ConnectReply reply_;
  26270. socket_t listen_sock_ = INVALID_SOCKET;
  26271. int port_ = 0;
  26272. std::thread th_;
  26273. std::atomic<bool> stop_{false};
  26274. std::atomic<int> connect_hits_{0};
  26275. mutable std::mutex connect_request_mutex_;
  26276. std::string connect_request_;
  26277. };
  26278. } // namespace proxy_tunnel_test
  26279. #ifdef CPPHTTPLIB_SSL_ENABLED
  26280. namespace proxy_tunnel_test {
  26281. // SSLServer counterpart to no_proxy_test::ScopedServer.
  26282. class ScopedSSLServer {
  26283. public:
  26284. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  26285. port_ = svr_.bind_to_any_port("127.0.0.1");
  26286. }
  26287. ~ScopedSSLServer() {
  26288. svr_.stop();
  26289. if (th_.joinable()) { th_.join(); }
  26290. }
  26291. SSLServer &svr() { return svr_; }
  26292. int port() const { return port_; }
  26293. void listen() {
  26294. th_ = std::thread([this] { svr_.listen_after_bind(); });
  26295. svr_.wait_until_ready();
  26296. }
  26297. private:
  26298. SSLServer svr_;
  26299. std::thread th_;
  26300. int port_ = 0;
  26301. };
  26302. // Sends one request through the CONNECT proxy to the TLS origin with a
  26303. // credential configured for each hop, and checks that each credential reaches
  26304. // only the hop it was configured for: the proxy's on the CONNECT request, the
  26305. // origin's (every header in origin_headers) on the tunnelled request.
  26306. void CredentialsStayWithTheirHop(
  26307. const std::function<void(SSLClient &)> &set_credentials,
  26308. const std::string &scheme,
  26309. const std::vector<std::string> &origin_headers = {"Authorization"},
  26310. bool stream = false) {
  26311. std::atomic<int> origin_hits{0};
  26312. std::atomic<bool> origin_saw_proxy_authz{false};
  26313. std::atomic<bool> origin_saw_headers{false};
  26314. ScopedSSLServer origin;
  26315. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26316. origin_hits++;
  26317. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  26318. origin_saw_headers =
  26319. std::all_of(origin_headers.begin(), origin_headers.end(),
  26320. [&](const std::string &h) { return req.has_header(h); });
  26321. res.set_content("ok", "text/plain");
  26322. });
  26323. origin.listen();
  26324. ScopedConnectProxy proxy(origin.port());
  26325. ASSERT_NE(0, proxy.port());
  26326. // Pinned to 127.0.0.1 for the same reason as the test below.
  26327. SSLClient cli("127.0.0.1", origin.port());
  26328. cli.enable_server_certificate_verification(false);
  26329. cli.set_proxy("127.0.0.1", proxy.port());
  26330. set_credentials(cli);
  26331. if (stream) {
  26332. auto handle = cli.open_stream("GET", "/x");
  26333. ASSERT_TRUE(handle.is_valid()) << "Error: " << to_string(handle.error);
  26334. EXPECT_EQ(StatusCode::OK_200, handle.response->status);
  26335. } else {
  26336. auto res = cli.Get("/x");
  26337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26338. EXPECT_EQ(StatusCode::OK_200, res->status);
  26339. }
  26340. EXPECT_EQ(1, origin_hits.load());
  26341. EXPECT_EQ(1, proxy.connect_hits());
  26342. EXPECT_TRUE(origin_saw_headers.load());
  26343. EXPECT_FALSE(origin_saw_proxy_authz.load())
  26344. << "Proxy-Authorization must not be sent inside the tunnel";
  26345. auto connect_req = proxy.connect_request();
  26346. EXPECT_NE(std::string::npos,
  26347. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  26348. for (const auto &h : origin_headers) {
  26349. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  26350. << h << " must not be sent to the proxy on CONNECT";
  26351. }
  26352. }
  26353. } // namespace proxy_tunnel_test
  26354. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  26355. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26356. [](SSLClient &cli) {
  26357. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26358. cli.set_basic_auth("origin-user", "origin-pass");
  26359. },
  26360. "Basic");
  26361. }
  26362. TEST(ProxyTunnelTest, StreamCredentialsStayWithTheirHop) {
  26363. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26364. [](SSLClient &cli) {
  26365. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26366. cli.set_basic_auth("origin-user", "origin-pass");
  26367. },
  26368. "Basic", {"Authorization"}, true);
  26369. }
  26370. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  26371. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26372. [](SSLClient &cli) {
  26373. cli.set_proxy_bearer_token_auth("proxy-token");
  26374. cli.set_bearer_token_auth("origin-token");
  26375. },
  26376. "Bearer");
  26377. }
  26378. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  26379. proxy_tunnel_test::CredentialsStayWithTheirHop(
  26380. [](SSLClient &cli) {
  26381. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26382. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  26383. {"Cookie", "sid=origin-session"},
  26384. {"X-Api-Key", "origin-key"}});
  26385. },
  26386. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  26387. }
  26388. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  26389. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  26390. // retry; otherwise proxy creds would be sent to the origin.
  26391. std::atomic<int> origin_hits{0};
  26392. std::atomic<bool> origin_saw_proxy_authz{false};
  26393. proxy_tunnel_test::ScopedSSLServer origin;
  26394. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  26395. origin_hits++;
  26396. if (req.has_header("Proxy-Authorization")) {
  26397. origin_saw_proxy_authz = true;
  26398. }
  26399. res.status = StatusCode::ProxyAuthenticationRequired_407;
  26400. res.set_header("Proxy-Authenticate",
  26401. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  26402. "algorithm=MD5");
  26403. });
  26404. origin.listen();
  26405. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26406. ASSERT_NE(0, proxy.port());
  26407. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  26408. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  26409. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  26410. // and answer with its own status, making this test flaky.
  26411. SSLClient cli("127.0.0.1", origin.port());
  26412. cli.enable_server_certificate_verification(false);
  26413. cli.set_proxy("127.0.0.1", proxy.port());
  26414. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26415. auto res = cli.Get("/x");
  26416. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26417. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  26418. EXPECT_EQ(1, origin_hits.load());
  26419. EXPECT_FALSE(origin_saw_proxy_authz.load());
  26420. EXPECT_EQ(1, proxy.connect_hits());
  26421. }
  26422. #endif
  26423. namespace proxy_tunnel_test {
  26424. // Tunnels only a CONNECT carrying `expected` as its Proxy-Authorization;
  26425. // anything else gets a 407 with `challenge`.
  26426. ConnectReply require_proxy_auth(const std::string &expected,
  26427. const std::string &challenge) {
  26428. return [=](const std::string &head) -> std::string {
  26429. if (head.find("\r\nProxy-Authorization: " + expected + "\r\n") !=
  26430. std::string::npos) {
  26431. return kTunnelEstablished;
  26432. }
  26433. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26434. "Proxy-Authenticate: " +
  26435. challenge + "\r\nContent-Length: 0\r\n\r\n";
  26436. };
  26437. }
  26438. // Reports the Authorization and Proxy-Authorization headers of the upgrade
  26439. // request, then echoes.
  26440. void report_auth_then_echo(const Request &req, ws::WebSocket &ws) {
  26441. ws.send(
  26442. "authorization:" + req.get_header_value("Authorization") +
  26443. "|proxy-authorization:" + req.get_header_value("Proxy-Authorization"));
  26444. std::string msg;
  26445. while (ws.read(msg)) {
  26446. ws.send(msg);
  26447. }
  26448. }
  26449. // A WebSocket origin on 127.0.0.1 serving report_auth_then_echo at /ws.
  26450. class ScopedWebSocketOrigin {
  26451. public:
  26452. ScopedWebSocketOrigin() {
  26453. server_.svr().WebSocket("/ws", report_auth_then_echo);
  26454. server_.listen();
  26455. }
  26456. int port() const { return server_.port(); }
  26457. // Pinned to 127.0.0.1, the only address the proxy forwards to.
  26458. std::string url() const {
  26459. return "ws://127.0.0.1:" + std::to_string(port()) + "/ws";
  26460. }
  26461. private:
  26462. no_proxy_test::ScopedServer server_;
  26463. };
  26464. // Connects through a proxy that requires `proxy_authz`, with `origin_authz`
  26465. // passed as a constructor header, and checks that each reaches only its hop.
  26466. void WebSocketCredentialsStayWithTheirHop(
  26467. const std::function<void(ws::WebSocketClient &)> &set_proxy_credentials,
  26468. const std::string &proxy_authz, const std::string &origin_authz) {
  26469. ScopedWebSocketOrigin origin;
  26470. ScopedConnectProxy proxy(
  26471. origin.port(), require_proxy_auth(proxy_authz, "Basic realm=\"proxy\""));
  26472. ASSERT_NE(0, proxy.port());
  26473. ws::WebSocketClient client(origin.url(), {{"Authorization", origin_authz}});
  26474. client.set_proxy("127.0.0.1", proxy.port());
  26475. set_proxy_credentials(client);
  26476. auto res = client.connect();
  26477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26478. std::string msg;
  26479. ASSERT_TRUE(client.read(msg));
  26480. EXPECT_EQ("authorization:" + origin_authz + "|proxy-authorization:", msg);
  26481. client.close();
  26482. EXPECT_EQ(1, proxy.connect_hits());
  26483. EXPECT_EQ(std::string::npos,
  26484. proxy.connect_request().find("\r\nAuthorization: "))
  26485. << "origin credentials must not be sent to the proxy";
  26486. }
  26487. } // namespace proxy_tunnel_test
  26488. TEST(WebSocketProxyTest, TunnelsThroughConnect) {
  26489. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26490. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26491. ASSERT_NE(0, proxy.port());
  26492. ws::WebSocketClient client(origin.url());
  26493. client.set_proxy("127.0.0.1", proxy.port());
  26494. auto res = client.connect();
  26495. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26496. std::string msg;
  26497. ASSERT_TRUE(client.read(msg));
  26498. ASSERT_TRUE(client.send("hello"));
  26499. ASSERT_TRUE(client.read(msg));
  26500. EXPECT_EQ("hello", msg);
  26501. client.close();
  26502. EXPECT_EQ(1, proxy.connect_hits());
  26503. auto target = "127.0.0.1:" + std::to_string(origin.port());
  26504. auto connect_req = proxy.connect_request();
  26505. EXPECT_EQ(0u, connect_req.find("CONNECT " + target + " HTTP/1.1\r\n"));
  26506. EXPECT_NE(std::string::npos,
  26507. connect_req.find("\r\nHost: " + target + "\r\n"));
  26508. }
  26509. TEST(WebSocketProxyTest, BasicCredentialsStayWithTheirHop) {
  26510. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26511. [](ws::WebSocketClient &cli) {
  26512. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26513. },
  26514. "Basic " + detail::base64_encode("proxy-user:proxy-pass"),
  26515. "Basic " + detail::base64_encode("origin-user:origin-pass"));
  26516. }
  26517. TEST(WebSocketProxyTest, BearerCredentialsStayWithTheirHop) {
  26518. proxy_tunnel_test::WebSocketCredentialsStayWithTheirHop(
  26519. [](ws::WebSocketClient &cli) {
  26520. cli.set_proxy_bearer_token_auth("proxy-token");
  26521. },
  26522. "Bearer proxy-token", "Bearer origin-token");
  26523. }
  26524. TEST(WebSocketProxyTest, BasicCredentialsWithEmptyPasswordAreSent) {
  26525. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26526. proxy_tunnel_test::ScopedConnectProxy proxy(
  26527. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26528. "Basic " + detail::base64_encode("proxy-user:"),
  26529. "Basic realm=\"proxy\""));
  26530. ASSERT_NE(0, proxy.port());
  26531. ws::WebSocketClient client(origin.url());
  26532. client.set_proxy("127.0.0.1", proxy.port());
  26533. client.set_proxy_basic_auth("proxy-user", "");
  26534. auto res = client.connect();
  26535. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26536. client.close();
  26537. EXPECT_EQ(1, proxy.connect_hits());
  26538. }
  26539. TEST(WebSocketProxyTest, ProxyRejectionReportsProxyConnection) {
  26540. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26541. proxy_tunnel_test::ScopedConnectProxy proxy(
  26542. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26543. "Bearer proxy-token", "Basic realm=\"proxy\""));
  26544. ASSERT_NE(0, proxy.port());
  26545. ws::WebSocketClient client(origin.url());
  26546. client.set_proxy("127.0.0.1", proxy.port());
  26547. auto res = client.connect();
  26548. EXPECT_FALSE(res);
  26549. EXPECT_EQ(Error::ProxyConnection, res.error());
  26550. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res.status());
  26551. EXPECT_EQ("Basic realm=\"proxy\"",
  26552. res.get_header_value("Proxy-Authenticate"));
  26553. EXPECT_FALSE(client.is_open());
  26554. }
  26555. TEST(WebSocketProxyTest, NoProxyBypassesProxy) {
  26556. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26557. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26558. ASSERT_NE(0, proxy.port());
  26559. ws::WebSocketClient client(origin.url());
  26560. client.set_proxy("127.0.0.1", proxy.port());
  26561. client.set_proxy_basic_auth("proxy-user", "proxy-pass");
  26562. client.set_no_proxy({"127.0.0.1"});
  26563. auto res = client.connect();
  26564. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26565. std::string msg;
  26566. ASSERT_TRUE(client.read(msg));
  26567. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26568. << "proxy credentials must not reach a bypassed origin";
  26569. client.close();
  26570. EXPECT_EQ(0, proxy.connect_hits());
  26571. }
  26572. TEST(WebSocketProxyTest, ProxySettingAppliesOnReconnect) {
  26573. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26574. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  26575. ASSERT_NE(0, proxy.port());
  26576. ws::WebSocketClient client(origin.url());
  26577. client.set_proxy("127.0.0.1", proxy.port());
  26578. ASSERT_TRUE(client.connect());
  26579. ASSERT_TRUE(client.connect());
  26580. client.close();
  26581. EXPECT_EQ(2, proxy.connect_hits());
  26582. }
  26583. #ifdef CPPHTTPLIB_SSL_ENABLED
  26584. TEST(WebSocketProxyTest, DigestRetriesConnectOnFreshSocket) {
  26585. proxy_tunnel_test::ScopedWebSocketOrigin origin;
  26586. proxy_tunnel_test::ScopedConnectProxy proxy(
  26587. origin.port(), [](const std::string &head) -> std::string {
  26588. if (head.find(
  26589. "\r\nProxy-Authorization: Digest username=\"proxy-user\"") !=
  26590. std::string::npos) {
  26591. return proxy_tunnel_test::kTunnelEstablished;
  26592. }
  26593. return "HTTP/1.1 407 Proxy Authentication Required\r\n"
  26594. "Proxy-Authenticate: Digest realm=\"proxy\", qop=\"auth\", "
  26595. "nonce=\"abc\", algorithm=MD5\r\n"
  26596. "Content-Length: 0\r\n\r\n";
  26597. });
  26598. ASSERT_NE(0, proxy.port());
  26599. ws::WebSocketClient client(origin.url());
  26600. client.set_proxy("127.0.0.1", proxy.port());
  26601. client.set_proxy_digest_auth("proxy-user", "proxy-pass");
  26602. auto res = client.connect();
  26603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26604. std::string msg;
  26605. ASSERT_TRUE(client.read(msg));
  26606. EXPECT_EQ("authorization:|proxy-authorization:", msg);
  26607. client.close();
  26608. EXPECT_EQ(2, proxy.connect_hits());
  26609. }
  26610. TEST(WebSocketProxyTest, WssTunnelsThroughConnect) {
  26611. proxy_tunnel_test::ScopedSSLServer origin;
  26612. origin.svr().WebSocket("/ws", proxy_tunnel_test::report_auth_then_echo);
  26613. origin.listen();
  26614. proxy_tunnel_test::ScopedConnectProxy proxy(
  26615. origin.port(), proxy_tunnel_test::require_proxy_auth(
  26616. "Bearer proxy-token", "Bearer realm=\"proxy\""));
  26617. ASSERT_NE(0, proxy.port());
  26618. ws::WebSocketClient client(
  26619. "wss://127.0.0.1:" + std::to_string(origin.port()) + "/ws");
  26620. client.enable_server_certificate_verification(false);
  26621. client.set_proxy("127.0.0.1", proxy.port());
  26622. client.set_proxy_bearer_token_auth("proxy-token");
  26623. auto res = client.connect();
  26624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  26625. std::string msg;
  26626. ASSERT_TRUE(client.read(msg));
  26627. EXPECT_EQ("authorization:|proxy-authorization:", msg)
  26628. << "Proxy-Authorization must not be sent inside the tunnel";
  26629. client.close();
  26630. EXPECT_EQ(1, proxy.connect_hits());
  26631. }
  26632. #endif