test.cc 852 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495249624972498249925002501250225032504250525062507250825092510251125122513251425152516251725182519252025212522252325242525252625272528252925302531253225332534253525362537253825392540254125422543254425452546254725482549255025512552255325542555255625572558255925602561256225632564256525662567256825692570257125722573257425752576257725782579258025812582258325842585258625872588258925902591259225932594259525962597259825992600260126022603260426052606260726082609261026112612261326142615261626172618261926202621262226232624262526262627262826292630263126322633263426352636263726382639264026412642264326442645264626472648264926502651265226532654265526562657265826592660266126622663266426652666266726682669267026712672267326742675267626772678267926802681268226832684268526862687268826892690269126922693269426952696269726982699270027012702270327042705270627072708270927102711271227132714271527162717271827192720272127222723272427252726272727282729273027312732273327342735273627372738273927402741274227432744274527462747274827492750275127522753275427552756275727582759276027612762276327642765276627672768276927702771277227732774277527762777277827792780278127822783278427852786278727882789279027912792279327942795279627972798279928002801280228032804280528062807280828092810281128122813281428152816281728182819282028212822282328242825282628272828282928302831283228332834283528362837283828392840284128422843284428452846284728482849285028512852285328542855285628572858285928602861286228632864286528662867286828692870287128722873287428752876287728782879288028812882288328842885288628872888288928902891289228932894289528962897289828992900290129022903290429052906290729082909291029112912291329142915291629172918291929202921292229232924292529262927292829292930293129322933293429352936293729382939294029412942294329442945294629472948294929502951295229532954295529562957295829592960296129622963296429652966296729682969297029712972297329742975297629772978297929802981298229832984298529862987298829892990299129922993299429952996299729982999300030013002300330043005300630073008300930103011301230133014301530163017301830193020302130223023302430253026302730283029303030313032303330343035303630373038303930403041304230433044304530463047304830493050305130523053305430553056305730583059306030613062306330643065306630673068306930703071307230733074307530763077307830793080308130823083308430853086308730883089309030913092309330943095309630973098309931003101310231033104310531063107310831093110311131123113311431153116311731183119312031213122312331243125312631273128312931303131313231333134313531363137313831393140314131423143314431453146314731483149315031513152315331543155315631573158315931603161316231633164316531663167316831693170317131723173317431753176317731783179318031813182318331843185318631873188318931903191319231933194319531963197319831993200320132023203320432053206320732083209321032113212321332143215321632173218321932203221322232233224322532263227322832293230323132323233323432353236323732383239324032413242324332443245324632473248324932503251325232533254325532563257325832593260326132623263326432653266326732683269327032713272327332743275327632773278327932803281328232833284328532863287328832893290329132923293329432953296329732983299330033013302330333043305330633073308330933103311331233133314331533163317331833193320332133223323332433253326332733283329333033313332333333343335333633373338333933403341334233433344334533463347334833493350335133523353335433553356335733583359336033613362336333643365336633673368336933703371337233733374337533763377337833793380338133823383338433853386338733883389339033913392339333943395339633973398339934003401340234033404340534063407340834093410341134123413341434153416341734183419342034213422342334243425342634273428342934303431343234333434343534363437343834393440344134423443344434453446344734483449345034513452345334543455345634573458345934603461346234633464346534663467346834693470347134723473347434753476347734783479348034813482348334843485348634873488348934903491349234933494349534963497349834993500350135023503350435053506350735083509351035113512351335143515351635173518351935203521352235233524352535263527352835293530353135323533353435353536353735383539354035413542354335443545354635473548354935503551355235533554355535563557355835593560356135623563356435653566356735683569357035713572357335743575357635773578357935803581358235833584358535863587358835893590359135923593359435953596359735983599360036013602360336043605360636073608360936103611361236133614361536163617361836193620362136223623362436253626362736283629363036313632363336343635363636373638363936403641364236433644364536463647364836493650365136523653365436553656365736583659366036613662366336643665366636673668366936703671367236733674367536763677367836793680368136823683368436853686368736883689369036913692369336943695369636973698369937003701370237033704370537063707370837093710371137123713371437153716371737183719372037213722372337243725372637273728372937303731373237333734373537363737373837393740374137423743374437453746374737483749375037513752375337543755375637573758375937603761376237633764376537663767376837693770377137723773377437753776377737783779378037813782378337843785378637873788378937903791379237933794379537963797379837993800380138023803380438053806380738083809381038113812381338143815381638173818381938203821382238233824382538263827382838293830383138323833383438353836383738383839384038413842384338443845384638473848384938503851385238533854385538563857385838593860386138623863386438653866386738683869387038713872387338743875387638773878387938803881388238833884388538863887388838893890389138923893389438953896389738983899390039013902390339043905390639073908390939103911391239133914391539163917391839193920392139223923392439253926392739283929393039313932393339343935393639373938393939403941394239433944394539463947394839493950395139523953395439553956395739583959396039613962396339643965396639673968396939703971397239733974397539763977397839793980398139823983398439853986398739883989399039913992399339943995399639973998399940004001400240034004400540064007400840094010401140124013401440154016401740184019402040214022402340244025402640274028402940304031403240334034403540364037403840394040404140424043404440454046404740484049405040514052405340544055405640574058405940604061406240634064406540664067406840694070407140724073407440754076407740784079408040814082408340844085408640874088408940904091409240934094409540964097409840994100410141024103410441054106410741084109411041114112411341144115411641174118411941204121412241234124412541264127412841294130413141324133413441354136413741384139414041414142414341444145414641474148414941504151415241534154415541564157415841594160416141624163416441654166416741684169417041714172417341744175417641774178417941804181418241834184418541864187418841894190419141924193419441954196419741984199420042014202420342044205420642074208420942104211421242134214421542164217421842194220422142224223422442254226422742284229423042314232423342344235423642374238423942404241424242434244424542464247424842494250425142524253425442554256425742584259426042614262426342644265426642674268426942704271427242734274427542764277427842794280428142824283428442854286428742884289429042914292429342944295429642974298429943004301430243034304430543064307430843094310431143124313431443154316431743184319432043214322432343244325432643274328432943304331433243334334433543364337433843394340434143424343434443454346434743484349435043514352435343544355435643574358435943604361436243634364436543664367436843694370437143724373437443754376437743784379438043814382438343844385438643874388438943904391439243934394439543964397439843994400440144024403440444054406440744084409441044114412441344144415441644174418441944204421442244234424442544264427442844294430443144324433443444354436443744384439444044414442444344444445444644474448444944504451445244534454445544564457445844594460446144624463446444654466446744684469447044714472447344744475447644774478447944804481448244834484448544864487448844894490449144924493449444954496449744984499450045014502450345044505450645074508450945104511451245134514451545164517451845194520452145224523452445254526452745284529453045314532453345344535453645374538453945404541454245434544454545464547454845494550455145524553455445554556455745584559456045614562456345644565456645674568456945704571457245734574457545764577457845794580458145824583458445854586458745884589459045914592459345944595459645974598459946004601460246034604460546064607460846094610461146124613461446154616461746184619462046214622462346244625462646274628462946304631463246334634463546364637463846394640464146424643464446454646464746484649465046514652465346544655465646574658465946604661466246634664466546664667466846694670467146724673467446754676467746784679468046814682468346844685468646874688468946904691469246934694469546964697469846994700470147024703470447054706470747084709471047114712471347144715471647174718471947204721472247234724472547264727472847294730473147324733473447354736473747384739474047414742474347444745474647474748474947504751475247534754475547564757475847594760476147624763476447654766476747684769477047714772477347744775477647774778477947804781478247834784478547864787478847894790479147924793479447954796479747984799480048014802480348044805480648074808480948104811481248134814481548164817481848194820482148224823482448254826482748284829483048314832483348344835483648374838483948404841484248434844484548464847484848494850485148524853485448554856485748584859486048614862486348644865486648674868486948704871487248734874487548764877487848794880488148824883488448854886488748884889489048914892489348944895489648974898489949004901490249034904490549064907490849094910491149124913491449154916491749184919492049214922492349244925492649274928492949304931493249334934493549364937493849394940494149424943494449454946494749484949495049514952495349544955495649574958495949604961496249634964496549664967496849694970497149724973497449754976497749784979498049814982498349844985498649874988498949904991499249934994499549964997499849995000500150025003500450055006500750085009501050115012501350145015501650175018501950205021502250235024502550265027502850295030503150325033503450355036503750385039504050415042504350445045504650475048504950505051505250535054505550565057505850595060506150625063506450655066506750685069507050715072507350745075507650775078507950805081508250835084508550865087508850895090509150925093509450955096509750985099510051015102510351045105510651075108510951105111511251135114511551165117511851195120512151225123512451255126512751285129513051315132513351345135513651375138513951405141514251435144514551465147514851495150515151525153515451555156515751585159516051615162516351645165516651675168516951705171517251735174517551765177517851795180518151825183518451855186518751885189519051915192519351945195519651975198519952005201520252035204520552065207520852095210521152125213521452155216521752185219522052215222522352245225522652275228522952305231523252335234523552365237523852395240524152425243524452455246524752485249525052515252525352545255525652575258525952605261526252635264526552665267526852695270527152725273527452755276527752785279528052815282528352845285528652875288528952905291529252935294529552965297529852995300530153025303530453055306530753085309531053115312531353145315531653175318531953205321532253235324532553265327532853295330533153325333533453355336533753385339534053415342534353445345534653475348534953505351535253535354535553565357535853595360536153625363536453655366536753685369537053715372537353745375537653775378537953805381538253835384538553865387538853895390539153925393539453955396539753985399540054015402540354045405540654075408540954105411541254135414541554165417541854195420542154225423542454255426542754285429543054315432543354345435543654375438543954405441544254435444544554465447544854495450545154525453545454555456545754585459546054615462546354645465546654675468546954705471547254735474547554765477547854795480548154825483548454855486548754885489549054915492549354945495549654975498549955005501550255035504550555065507550855095510551155125513551455155516551755185519552055215522552355245525552655275528552955305531553255335534553555365537553855395540554155425543554455455546554755485549555055515552555355545555555655575558555955605561556255635564556555665567556855695570557155725573557455755576557755785579558055815582558355845585558655875588558955905591559255935594559555965597559855995600560156025603560456055606560756085609561056115612561356145615561656175618561956205621562256235624562556265627562856295630563156325633563456355636563756385639564056415642564356445645564656475648564956505651565256535654565556565657565856595660566156625663566456655666566756685669567056715672567356745675567656775678567956805681568256835684568556865687568856895690569156925693569456955696569756985699570057015702570357045705570657075708570957105711571257135714571557165717571857195720572157225723572457255726572757285729573057315732573357345735573657375738573957405741574257435744574557465747574857495750575157525753575457555756575757585759576057615762576357645765576657675768576957705771577257735774577557765777577857795780578157825783578457855786578757885789579057915792579357945795579657975798579958005801580258035804580558065807580858095810581158125813581458155816581758185819582058215822582358245825582658275828582958305831583258335834583558365837583858395840584158425843584458455846584758485849585058515852585358545855585658575858585958605861586258635864586558665867586858695870587158725873587458755876587758785879588058815882588358845885588658875888588958905891589258935894589558965897589858995900590159025903590459055906590759085909591059115912591359145915591659175918591959205921592259235924592559265927592859295930593159325933593459355936593759385939594059415942594359445945594659475948594959505951595259535954595559565957595859595960596159625963596459655966596759685969597059715972597359745975597659775978597959805981598259835984598559865987598859895990599159925993599459955996599759985999600060016002600360046005600660076008600960106011601260136014601560166017601860196020602160226023602460256026602760286029603060316032603360346035603660376038603960406041604260436044604560466047604860496050605160526053605460556056605760586059606060616062606360646065606660676068606960706071607260736074607560766077607860796080608160826083608460856086608760886089609060916092609360946095609660976098609961006101610261036104610561066107610861096110611161126113611461156116611761186119612061216122612361246125612661276128612961306131613261336134613561366137613861396140614161426143614461456146614761486149615061516152615361546155615661576158615961606161616261636164616561666167616861696170617161726173617461756176617761786179618061816182618361846185618661876188618961906191619261936194619561966197619861996200620162026203620462056206620762086209621062116212621362146215621662176218621962206221622262236224622562266227622862296230623162326233623462356236623762386239624062416242624362446245624662476248624962506251625262536254625562566257625862596260626162626263626462656266626762686269627062716272627362746275627662776278627962806281628262836284628562866287628862896290629162926293629462956296629762986299630063016302630363046305630663076308630963106311631263136314631563166317631863196320632163226323632463256326632763286329633063316332633363346335633663376338633963406341634263436344634563466347634863496350635163526353635463556356635763586359636063616362636363646365636663676368636963706371637263736374637563766377637863796380638163826383638463856386638763886389639063916392639363946395639663976398639964006401640264036404640564066407640864096410641164126413641464156416641764186419642064216422642364246425642664276428642964306431643264336434643564366437643864396440644164426443644464456446644764486449645064516452645364546455645664576458645964606461646264636464646564666467646864696470647164726473647464756476647764786479648064816482648364846485648664876488648964906491649264936494649564966497649864996500650165026503650465056506650765086509651065116512651365146515651665176518651965206521652265236524652565266527652865296530653165326533653465356536653765386539654065416542654365446545654665476548654965506551655265536554655565566557655865596560656165626563656465656566656765686569657065716572657365746575657665776578657965806581658265836584658565866587658865896590659165926593659465956596659765986599660066016602660366046605660666076608660966106611661266136614661566166617661866196620662166226623662466256626662766286629663066316632663366346635663666376638663966406641664266436644664566466647664866496650665166526653665466556656665766586659666066616662666366646665666666676668666966706671667266736674667566766677667866796680668166826683668466856686668766886689669066916692669366946695669666976698669967006701670267036704670567066707670867096710671167126713671467156716671767186719672067216722672367246725672667276728672967306731673267336734673567366737673867396740674167426743674467456746674767486749675067516752675367546755675667576758675967606761676267636764676567666767676867696770677167726773677467756776677767786779678067816782678367846785678667876788678967906791679267936794679567966797679867996800680168026803680468056806680768086809681068116812681368146815681668176818681968206821682268236824682568266827682868296830683168326833683468356836683768386839684068416842684368446845684668476848684968506851685268536854685568566857685868596860686168626863686468656866686768686869687068716872687368746875687668776878687968806881688268836884688568866887688868896890689168926893689468956896689768986899690069016902690369046905690669076908690969106911691269136914691569166917691869196920692169226923692469256926692769286929693069316932693369346935693669376938693969406941694269436944694569466947694869496950695169526953695469556956695769586959696069616962696369646965696669676968696969706971697269736974697569766977697869796980698169826983698469856986698769886989699069916992699369946995699669976998699970007001700270037004700570067007700870097010701170127013701470157016701770187019702070217022702370247025702670277028702970307031703270337034703570367037703870397040704170427043704470457046704770487049705070517052705370547055705670577058705970607061706270637064706570667067706870697070707170727073707470757076707770787079708070817082708370847085708670877088708970907091709270937094709570967097709870997100710171027103710471057106710771087109711071117112711371147115711671177118711971207121712271237124712571267127712871297130713171327133713471357136713771387139714071417142714371447145714671477148714971507151715271537154715571567157715871597160716171627163716471657166716771687169717071717172717371747175717671777178717971807181718271837184718571867187718871897190719171927193719471957196719771987199720072017202720372047205720672077208720972107211721272137214721572167217721872197220722172227223722472257226722772287229723072317232723372347235723672377238723972407241724272437244724572467247724872497250725172527253725472557256725772587259726072617262726372647265726672677268726972707271727272737274727572767277727872797280728172827283728472857286728772887289729072917292729372947295729672977298729973007301730273037304730573067307730873097310731173127313731473157316731773187319732073217322732373247325732673277328732973307331733273337334733573367337733873397340734173427343734473457346734773487349735073517352735373547355735673577358735973607361736273637364736573667367736873697370737173727373737473757376737773787379738073817382738373847385738673877388738973907391739273937394739573967397739873997400740174027403740474057406740774087409741074117412741374147415741674177418741974207421742274237424742574267427742874297430743174327433743474357436743774387439744074417442744374447445744674477448744974507451745274537454745574567457745874597460746174627463746474657466746774687469747074717472747374747475747674777478747974807481748274837484748574867487748874897490749174927493749474957496749774987499750075017502750375047505750675077508750975107511751275137514751575167517751875197520752175227523752475257526752775287529753075317532753375347535753675377538753975407541754275437544754575467547754875497550755175527553755475557556755775587559756075617562756375647565756675677568756975707571757275737574757575767577757875797580758175827583758475857586758775887589759075917592759375947595759675977598759976007601760276037604760576067607760876097610761176127613761476157616761776187619762076217622762376247625762676277628762976307631763276337634763576367637763876397640764176427643764476457646764776487649765076517652765376547655765676577658765976607661766276637664766576667667766876697670767176727673767476757676767776787679768076817682768376847685768676877688768976907691769276937694769576967697769876997700770177027703770477057706770777087709771077117712771377147715771677177718771977207721772277237724772577267727772877297730773177327733773477357736773777387739774077417742774377447745774677477748774977507751775277537754775577567757775877597760776177627763776477657766776777687769777077717772777377747775777677777778777977807781778277837784778577867787778877897790779177927793779477957796779777987799780078017802780378047805780678077808780978107811781278137814781578167817781878197820782178227823782478257826782778287829783078317832783378347835783678377838783978407841784278437844784578467847784878497850785178527853785478557856785778587859786078617862786378647865786678677868786978707871787278737874787578767877787878797880788178827883788478857886788778887889789078917892789378947895789678977898789979007901790279037904790579067907790879097910791179127913791479157916791779187919792079217922792379247925792679277928792979307931793279337934793579367937793879397940794179427943794479457946794779487949795079517952795379547955795679577958795979607961796279637964796579667967796879697970797179727973797479757976797779787979798079817982798379847985798679877988798979907991799279937994799579967997799879998000800180028003800480058006800780088009801080118012801380148015801680178018801980208021802280238024802580268027802880298030803180328033803480358036803780388039804080418042804380448045804680478048804980508051805280538054805580568057805880598060806180628063806480658066806780688069807080718072807380748075807680778078807980808081808280838084808580868087808880898090809180928093809480958096809780988099810081018102810381048105810681078108810981108111811281138114811581168117811881198120812181228123812481258126812781288129813081318132813381348135813681378138813981408141814281438144814581468147814881498150815181528153815481558156815781588159816081618162816381648165816681678168816981708171817281738174817581768177817881798180818181828183818481858186818781888189819081918192819381948195819681978198819982008201820282038204820582068207820882098210821182128213821482158216821782188219822082218222822382248225822682278228822982308231823282338234823582368237823882398240824182428243824482458246824782488249825082518252825382548255825682578258825982608261826282638264826582668267826882698270827182728273827482758276827782788279828082818282828382848285828682878288828982908291829282938294829582968297829882998300830183028303830483058306830783088309831083118312831383148315831683178318831983208321832283238324832583268327832883298330833183328333833483358336833783388339834083418342834383448345834683478348834983508351835283538354835583568357835883598360836183628363836483658366836783688369837083718372837383748375837683778378837983808381838283838384838583868387838883898390839183928393839483958396839783988399840084018402840384048405840684078408840984108411841284138414841584168417841884198420842184228423842484258426842784288429843084318432843384348435843684378438843984408441844284438444844584468447844884498450845184528453845484558456845784588459846084618462846384648465846684678468846984708471847284738474847584768477847884798480848184828483848484858486848784888489849084918492849384948495849684978498849985008501850285038504850585068507850885098510851185128513851485158516851785188519852085218522852385248525852685278528852985308531853285338534853585368537853885398540854185428543854485458546854785488549855085518552855385548555855685578558855985608561856285638564856585668567856885698570857185728573857485758576857785788579858085818582858385848585858685878588858985908591859285938594859585968597859885998600860186028603860486058606860786088609861086118612861386148615861686178618861986208621862286238624862586268627862886298630863186328633863486358636863786388639864086418642864386448645864686478648864986508651865286538654865586568657865886598660866186628663866486658666866786688669867086718672867386748675867686778678867986808681868286838684868586868687868886898690869186928693869486958696869786988699870087018702870387048705870687078708870987108711871287138714871587168717871887198720872187228723872487258726872787288729873087318732873387348735873687378738873987408741874287438744874587468747874887498750875187528753875487558756875787588759876087618762876387648765876687678768876987708771877287738774877587768777877887798780878187828783878487858786878787888789879087918792879387948795879687978798879988008801880288038804880588068807880888098810881188128813881488158816881788188819882088218822882388248825882688278828882988308831883288338834883588368837883888398840884188428843884488458846884788488849885088518852885388548855885688578858885988608861886288638864886588668867886888698870887188728873887488758876887788788879888088818882888388848885888688878888888988908891889288938894889588968897889888998900890189028903890489058906890789088909891089118912891389148915891689178918891989208921892289238924892589268927892889298930893189328933893489358936893789388939894089418942894389448945894689478948894989508951895289538954895589568957895889598960896189628963896489658966896789688969897089718972897389748975897689778978897989808981898289838984898589868987898889898990899189928993899489958996899789988999900090019002900390049005900690079008900990109011901290139014901590169017901890199020902190229023902490259026902790289029903090319032903390349035903690379038903990409041904290439044904590469047904890499050905190529053905490559056905790589059906090619062906390649065906690679068906990709071907290739074907590769077907890799080908190829083908490859086908790889089909090919092909390949095909690979098909991009101910291039104910591069107910891099110911191129113911491159116911791189119912091219122912391249125912691279128912991309131913291339134913591369137913891399140914191429143914491459146914791489149915091519152915391549155915691579158915991609161916291639164916591669167916891699170917191729173917491759176917791789179918091819182918391849185918691879188918991909191919291939194919591969197919891999200920192029203920492059206920792089209921092119212921392149215921692179218921992209221922292239224922592269227922892299230923192329233923492359236923792389239924092419242924392449245924692479248924992509251925292539254925592569257925892599260926192629263926492659266926792689269927092719272927392749275927692779278927992809281928292839284928592869287928892899290929192929293929492959296929792989299930093019302930393049305930693079308930993109311931293139314931593169317931893199320932193229323932493259326932793289329933093319332933393349335933693379338933993409341934293439344934593469347934893499350935193529353935493559356935793589359936093619362936393649365936693679368936993709371937293739374937593769377937893799380938193829383938493859386938793889389939093919392939393949395939693979398939994009401940294039404940594069407940894099410941194129413941494159416941794189419942094219422942394249425942694279428942994309431943294339434943594369437943894399440944194429443944494459446944794489449945094519452945394549455945694579458945994609461946294639464946594669467946894699470947194729473947494759476947794789479948094819482948394849485948694879488948994909491949294939494949594969497949894999500950195029503950495059506950795089509951095119512951395149515951695179518951995209521952295239524952595269527952895299530953195329533953495359536953795389539954095419542954395449545954695479548954995509551955295539554955595569557955895599560956195629563956495659566956795689569957095719572957395749575957695779578957995809581958295839584958595869587958895899590959195929593959495959596959795989599960096019602960396049605960696079608960996109611961296139614961596169617961896199620962196229623962496259626962796289629963096319632963396349635963696379638963996409641964296439644964596469647964896499650965196529653965496559656965796589659966096619662966396649665966696679668966996709671967296739674967596769677967896799680968196829683968496859686968796889689969096919692969396949695969696979698969997009701970297039704970597069707970897099710971197129713971497159716971797189719972097219722972397249725972697279728972997309731973297339734973597369737973897399740974197429743974497459746974797489749975097519752975397549755975697579758975997609761976297639764976597669767976897699770977197729773977497759776977797789779978097819782978397849785978697879788978997909791979297939794979597969797979897999800980198029803980498059806980798089809981098119812981398149815981698179818981998209821982298239824982598269827982898299830983198329833983498359836983798389839984098419842984398449845984698479848984998509851985298539854985598569857985898599860986198629863986498659866986798689869987098719872987398749875987698779878987998809881988298839884988598869887988898899890989198929893989498959896989798989899990099019902990399049905990699079908990999109911991299139914991599169917991899199920992199229923992499259926992799289929993099319932993399349935993699379938993999409941994299439944994599469947994899499950995199529953995499559956995799589959996099619962996399649965996699679968996999709971997299739974997599769977997899799980998199829983998499859986998799889989999099919992999399949995999699979998999910000100011000210003100041000510006100071000810009100101001110012100131001410015100161001710018100191002010021100221002310024100251002610027100281002910030100311003210033100341003510036100371003810039100401004110042100431004410045100461004710048100491005010051100521005310054100551005610057100581005910060100611006210063100641006510066100671006810069100701007110072100731007410075100761007710078100791008010081100821008310084100851008610087100881008910090100911009210093100941009510096100971009810099101001010110102101031010410105101061010710108101091011010111101121011310114101151011610117101181011910120101211012210123101241012510126101271012810129101301013110132101331013410135101361013710138101391014010141101421014310144101451014610147101481014910150101511015210153101541015510156101571015810159101601016110162101631016410165101661016710168101691017010171101721017310174101751017610177101781017910180101811018210183101841018510186101871018810189101901019110192101931019410195101961019710198101991020010201102021020310204102051020610207102081020910210102111021210213102141021510216102171021810219102201022110222102231022410225102261022710228102291023010231102321023310234102351023610237102381023910240102411024210243102441024510246102471024810249102501025110252102531025410255102561025710258102591026010261102621026310264102651026610267102681026910270102711027210273102741027510276102771027810279102801028110282102831028410285102861028710288102891029010291102921029310294102951029610297102981029910300103011030210303103041030510306103071030810309103101031110312103131031410315103161031710318103191032010321103221032310324103251032610327103281032910330103311033210333103341033510336103371033810339103401034110342103431034410345103461034710348103491035010351103521035310354103551035610357103581035910360103611036210363103641036510366103671036810369103701037110372103731037410375103761037710378103791038010381103821038310384103851038610387103881038910390103911039210393103941039510396103971039810399104001040110402104031040410405104061040710408104091041010411104121041310414104151041610417104181041910420104211042210423104241042510426104271042810429104301043110432104331043410435104361043710438104391044010441104421044310444104451044610447104481044910450104511045210453104541045510456104571045810459104601046110462104631046410465104661046710468104691047010471104721047310474104751047610477104781047910480104811048210483104841048510486104871048810489104901049110492104931049410495104961049710498104991050010501105021050310504105051050610507105081050910510105111051210513105141051510516105171051810519105201052110522105231052410525105261052710528105291053010531105321053310534105351053610537105381053910540105411054210543105441054510546105471054810549105501055110552105531055410555105561055710558105591056010561105621056310564105651056610567105681056910570105711057210573105741057510576105771057810579105801058110582105831058410585105861058710588105891059010591105921059310594105951059610597105981059910600106011060210603106041060510606106071060810609106101061110612106131061410615106161061710618106191062010621106221062310624106251062610627106281062910630106311063210633106341063510636106371063810639106401064110642106431064410645106461064710648106491065010651106521065310654106551065610657106581065910660106611066210663106641066510666106671066810669106701067110672106731067410675106761067710678106791068010681106821068310684106851068610687106881068910690106911069210693106941069510696106971069810699107001070110702107031070410705107061070710708107091071010711107121071310714107151071610717107181071910720107211072210723107241072510726107271072810729107301073110732107331073410735107361073710738107391074010741107421074310744107451074610747107481074910750107511075210753107541075510756107571075810759107601076110762107631076410765107661076710768107691077010771107721077310774107751077610777107781077910780107811078210783107841078510786107871078810789107901079110792107931079410795107961079710798107991080010801108021080310804108051080610807108081080910810108111081210813108141081510816108171081810819108201082110822108231082410825108261082710828108291083010831108321083310834108351083610837108381083910840108411084210843108441084510846108471084810849108501085110852108531085410855108561085710858108591086010861108621086310864108651086610867108681086910870108711087210873108741087510876108771087810879108801088110882108831088410885108861088710888108891089010891108921089310894108951089610897108981089910900109011090210903109041090510906109071090810909109101091110912109131091410915109161091710918109191092010921109221092310924109251092610927109281092910930109311093210933109341093510936109371093810939109401094110942109431094410945109461094710948109491095010951109521095310954109551095610957109581095910960109611096210963109641096510966109671096810969109701097110972109731097410975109761097710978109791098010981109821098310984109851098610987109881098910990109911099210993109941099510996109971099810999110001100111002110031100411005110061100711008110091101011011110121101311014110151101611017110181101911020110211102211023110241102511026110271102811029110301103111032110331103411035110361103711038110391104011041110421104311044110451104611047110481104911050110511105211053110541105511056110571105811059110601106111062110631106411065110661106711068110691107011071110721107311074110751107611077110781107911080110811108211083110841108511086110871108811089110901109111092110931109411095110961109711098110991110011101111021110311104111051110611107111081110911110111111111211113111141111511116111171111811119111201112111122111231112411125111261112711128111291113011131111321113311134111351113611137111381113911140111411114211143111441114511146111471114811149111501115111152111531115411155111561115711158111591116011161111621116311164111651116611167111681116911170111711117211173111741117511176111771117811179111801118111182111831118411185111861118711188111891119011191111921119311194111951119611197111981119911200112011120211203112041120511206112071120811209112101121111212112131121411215112161121711218112191122011221112221122311224112251122611227112281122911230112311123211233112341123511236112371123811239112401124111242112431124411245112461124711248112491125011251112521125311254112551125611257112581125911260112611126211263112641126511266112671126811269112701127111272112731127411275112761127711278112791128011281112821128311284112851128611287112881128911290112911129211293112941129511296112971129811299113001130111302113031130411305113061130711308113091131011311113121131311314113151131611317113181131911320113211132211323113241132511326113271132811329113301133111332113331133411335113361133711338113391134011341113421134311344113451134611347113481134911350113511135211353113541135511356113571135811359113601136111362113631136411365113661136711368113691137011371113721137311374113751137611377113781137911380113811138211383113841138511386113871138811389113901139111392113931139411395113961139711398113991140011401114021140311404114051140611407114081140911410114111141211413114141141511416114171141811419114201142111422114231142411425114261142711428114291143011431114321143311434114351143611437114381143911440114411144211443114441144511446114471144811449114501145111452114531145411455114561145711458114591146011461114621146311464114651146611467114681146911470114711147211473114741147511476114771147811479114801148111482114831148411485114861148711488114891149011491114921149311494114951149611497114981149911500115011150211503115041150511506115071150811509115101151111512115131151411515115161151711518115191152011521115221152311524115251152611527115281152911530115311153211533115341153511536115371153811539115401154111542115431154411545115461154711548115491155011551115521155311554115551155611557115581155911560115611156211563115641156511566115671156811569115701157111572115731157411575115761157711578115791158011581115821158311584115851158611587115881158911590115911159211593115941159511596115971159811599116001160111602116031160411605116061160711608116091161011611116121161311614116151161611617116181161911620116211162211623116241162511626116271162811629116301163111632116331163411635116361163711638116391164011641116421164311644116451164611647116481164911650116511165211653116541165511656116571165811659116601166111662116631166411665116661166711668116691167011671116721167311674116751167611677116781167911680116811168211683116841168511686116871168811689116901169111692116931169411695116961169711698116991170011701117021170311704117051170611707117081170911710117111171211713117141171511716117171171811719117201172111722117231172411725117261172711728117291173011731117321173311734117351173611737117381173911740117411174211743117441174511746117471174811749117501175111752117531175411755117561175711758117591176011761117621176311764117651176611767117681176911770117711177211773117741177511776117771177811779117801178111782117831178411785117861178711788117891179011791117921179311794117951179611797117981179911800118011180211803118041180511806118071180811809118101181111812118131181411815118161181711818118191182011821118221182311824118251182611827118281182911830118311183211833118341183511836118371183811839118401184111842118431184411845118461184711848118491185011851118521185311854118551185611857118581185911860118611186211863118641186511866118671186811869118701187111872118731187411875118761187711878118791188011881118821188311884118851188611887118881188911890118911189211893118941189511896118971189811899119001190111902119031190411905119061190711908119091191011911119121191311914119151191611917119181191911920119211192211923119241192511926119271192811929119301193111932119331193411935119361193711938119391194011941119421194311944119451194611947119481194911950119511195211953119541195511956119571195811959119601196111962119631196411965119661196711968119691197011971119721197311974119751197611977119781197911980119811198211983119841198511986119871198811989119901199111992119931199411995119961199711998119991200012001120021200312004120051200612007120081200912010120111201212013120141201512016120171201812019120201202112022120231202412025120261202712028120291203012031120321203312034120351203612037120381203912040120411204212043120441204512046120471204812049120501205112052120531205412055120561205712058120591206012061120621206312064120651206612067120681206912070120711207212073120741207512076120771207812079120801208112082120831208412085120861208712088120891209012091120921209312094120951209612097120981209912100121011210212103121041210512106121071210812109121101211112112121131211412115121161211712118121191212012121121221212312124121251212612127121281212912130121311213212133121341213512136121371213812139121401214112142121431214412145121461214712148121491215012151121521215312154121551215612157121581215912160121611216212163121641216512166121671216812169121701217112172121731217412175121761217712178121791218012181121821218312184121851218612187121881218912190121911219212193121941219512196121971219812199122001220112202122031220412205122061220712208122091221012211122121221312214122151221612217122181221912220122211222212223122241222512226122271222812229122301223112232122331223412235122361223712238122391224012241122421224312244122451224612247122481224912250122511225212253122541225512256122571225812259122601226112262122631226412265122661226712268122691227012271122721227312274122751227612277122781227912280122811228212283122841228512286122871228812289122901229112292122931229412295122961229712298122991230012301123021230312304123051230612307123081230912310123111231212313123141231512316123171231812319123201232112322123231232412325123261232712328123291233012331123321233312334123351233612337123381233912340123411234212343123441234512346123471234812349123501235112352123531235412355123561235712358123591236012361123621236312364123651236612367123681236912370123711237212373123741237512376123771237812379123801238112382123831238412385123861238712388123891239012391123921239312394123951239612397123981239912400124011240212403124041240512406124071240812409124101241112412124131241412415124161241712418124191242012421124221242312424124251242612427124281242912430124311243212433124341243512436124371243812439124401244112442124431244412445124461244712448124491245012451124521245312454124551245612457124581245912460124611246212463124641246512466124671246812469124701247112472124731247412475124761247712478124791248012481124821248312484124851248612487124881248912490124911249212493124941249512496124971249812499125001250112502125031250412505125061250712508125091251012511125121251312514125151251612517125181251912520125211252212523125241252512526125271252812529125301253112532125331253412535125361253712538125391254012541125421254312544125451254612547125481254912550125511255212553125541255512556125571255812559125601256112562125631256412565125661256712568125691257012571125721257312574125751257612577125781257912580125811258212583125841258512586125871258812589125901259112592125931259412595125961259712598125991260012601126021260312604126051260612607126081260912610126111261212613126141261512616126171261812619126201262112622126231262412625126261262712628126291263012631126321263312634126351263612637126381263912640126411264212643126441264512646126471264812649126501265112652126531265412655126561265712658126591266012661126621266312664126651266612667126681266912670126711267212673126741267512676126771267812679126801268112682126831268412685126861268712688126891269012691126921269312694126951269612697126981269912700127011270212703127041270512706127071270812709127101271112712127131271412715127161271712718127191272012721127221272312724127251272612727127281272912730127311273212733127341273512736127371273812739127401274112742127431274412745127461274712748127491275012751127521275312754127551275612757127581275912760127611276212763127641276512766127671276812769127701277112772127731277412775127761277712778127791278012781127821278312784127851278612787127881278912790127911279212793127941279512796127971279812799128001280112802128031280412805128061280712808128091281012811128121281312814128151281612817128181281912820128211282212823128241282512826128271282812829128301283112832128331283412835128361283712838128391284012841128421284312844128451284612847128481284912850128511285212853128541285512856128571285812859128601286112862128631286412865128661286712868128691287012871128721287312874128751287612877128781287912880128811288212883128841288512886128871288812889128901289112892128931289412895128961289712898128991290012901129021290312904129051290612907129081290912910129111291212913129141291512916129171291812919129201292112922129231292412925129261292712928129291293012931129321293312934129351293612937129381293912940129411294212943129441294512946129471294812949129501295112952129531295412955129561295712958129591296012961129621296312964129651296612967129681296912970129711297212973129741297512976129771297812979129801298112982129831298412985129861298712988129891299012991129921299312994129951299612997129981299913000130011300213003130041300513006130071300813009130101301113012130131301413015130161301713018130191302013021130221302313024130251302613027130281302913030130311303213033130341303513036130371303813039130401304113042130431304413045130461304713048130491305013051130521305313054130551305613057130581305913060130611306213063130641306513066130671306813069130701307113072130731307413075130761307713078130791308013081130821308313084130851308613087130881308913090130911309213093130941309513096130971309813099131001310113102131031310413105131061310713108131091311013111131121311313114131151311613117131181311913120131211312213123131241312513126131271312813129131301313113132131331313413135131361313713138131391314013141131421314313144131451314613147131481314913150131511315213153131541315513156131571315813159131601316113162131631316413165131661316713168131691317013171131721317313174131751317613177131781317913180131811318213183131841318513186131871318813189131901319113192131931319413195131961319713198131991320013201132021320313204132051320613207132081320913210132111321213213132141321513216132171321813219132201322113222132231322413225132261322713228132291323013231132321323313234132351323613237132381323913240132411324213243132441324513246132471324813249132501325113252132531325413255132561325713258132591326013261132621326313264132651326613267132681326913270132711327213273132741327513276132771327813279132801328113282132831328413285132861328713288132891329013291132921329313294132951329613297132981329913300133011330213303133041330513306133071330813309133101331113312133131331413315133161331713318133191332013321133221332313324133251332613327133281332913330133311333213333133341333513336133371333813339133401334113342133431334413345133461334713348133491335013351133521335313354133551335613357133581335913360133611336213363133641336513366133671336813369133701337113372133731337413375133761337713378133791338013381133821338313384133851338613387133881338913390133911339213393133941339513396133971339813399134001340113402134031340413405134061340713408134091341013411134121341313414134151341613417134181341913420134211342213423134241342513426134271342813429134301343113432134331343413435134361343713438134391344013441134421344313444134451344613447134481344913450134511345213453134541345513456134571345813459134601346113462134631346413465134661346713468134691347013471134721347313474134751347613477134781347913480134811348213483134841348513486134871348813489134901349113492134931349413495134961349713498134991350013501135021350313504135051350613507135081350913510135111351213513135141351513516135171351813519135201352113522135231352413525135261352713528135291353013531135321353313534135351353613537135381353913540135411354213543135441354513546135471354813549135501355113552135531355413555135561355713558135591356013561135621356313564135651356613567135681356913570135711357213573135741357513576135771357813579135801358113582135831358413585135861358713588135891359013591135921359313594135951359613597135981359913600136011360213603136041360513606136071360813609136101361113612136131361413615136161361713618136191362013621136221362313624136251362613627136281362913630136311363213633136341363513636136371363813639136401364113642136431364413645136461364713648136491365013651136521365313654136551365613657136581365913660136611366213663136641366513666136671366813669136701367113672136731367413675136761367713678136791368013681136821368313684136851368613687136881368913690136911369213693136941369513696136971369813699137001370113702137031370413705137061370713708137091371013711137121371313714137151371613717137181371913720137211372213723137241372513726137271372813729137301373113732137331373413735137361373713738137391374013741137421374313744137451374613747137481374913750137511375213753137541375513756137571375813759137601376113762137631376413765137661376713768137691377013771137721377313774137751377613777137781377913780137811378213783137841378513786137871378813789137901379113792137931379413795137961379713798137991380013801138021380313804138051380613807138081380913810138111381213813138141381513816138171381813819138201382113822138231382413825138261382713828138291383013831138321383313834138351383613837138381383913840138411384213843138441384513846138471384813849138501385113852138531385413855138561385713858138591386013861138621386313864138651386613867138681386913870138711387213873138741387513876138771387813879138801388113882138831388413885138861388713888138891389013891138921389313894138951389613897138981389913900139011390213903139041390513906139071390813909139101391113912139131391413915139161391713918139191392013921139221392313924139251392613927139281392913930139311393213933139341393513936139371393813939139401394113942139431394413945139461394713948139491395013951139521395313954139551395613957139581395913960139611396213963139641396513966139671396813969139701397113972139731397413975139761397713978139791398013981139821398313984139851398613987139881398913990139911399213993139941399513996139971399813999140001400114002140031400414005140061400714008140091401014011140121401314014140151401614017140181401914020140211402214023140241402514026140271402814029140301403114032140331403414035140361403714038140391404014041140421404314044140451404614047140481404914050140511405214053140541405514056140571405814059140601406114062140631406414065140661406714068140691407014071140721407314074140751407614077140781407914080140811408214083140841408514086140871408814089140901409114092140931409414095140961409714098140991410014101141021410314104141051410614107141081410914110141111411214113141141411514116141171411814119141201412114122141231412414125141261412714128141291413014131141321413314134141351413614137141381413914140141411414214143141441414514146141471414814149141501415114152141531415414155141561415714158141591416014161141621416314164141651416614167141681416914170141711417214173141741417514176141771417814179141801418114182141831418414185141861418714188141891419014191141921419314194141951419614197141981419914200142011420214203142041420514206142071420814209142101421114212142131421414215142161421714218142191422014221142221422314224142251422614227142281422914230142311423214233142341423514236142371423814239142401424114242142431424414245142461424714248142491425014251142521425314254142551425614257142581425914260142611426214263142641426514266142671426814269142701427114272142731427414275142761427714278142791428014281142821428314284142851428614287142881428914290142911429214293142941429514296142971429814299143001430114302143031430414305143061430714308143091431014311143121431314314143151431614317143181431914320143211432214323143241432514326143271432814329143301433114332143331433414335143361433714338143391434014341143421434314344143451434614347143481434914350143511435214353143541435514356143571435814359143601436114362143631436414365143661436714368143691437014371143721437314374143751437614377143781437914380143811438214383143841438514386143871438814389143901439114392143931439414395143961439714398143991440014401144021440314404144051440614407144081440914410144111441214413144141441514416144171441814419144201442114422144231442414425144261442714428144291443014431144321443314434144351443614437144381443914440144411444214443144441444514446144471444814449144501445114452144531445414455144561445714458144591446014461144621446314464144651446614467144681446914470144711447214473144741447514476144771447814479144801448114482144831448414485144861448714488144891449014491144921449314494144951449614497144981449914500145011450214503145041450514506145071450814509145101451114512145131451414515145161451714518145191452014521145221452314524145251452614527145281452914530145311453214533145341453514536145371453814539145401454114542145431454414545145461454714548145491455014551145521455314554145551455614557145581455914560145611456214563145641456514566145671456814569145701457114572145731457414575145761457714578145791458014581145821458314584145851458614587145881458914590145911459214593145941459514596145971459814599146001460114602146031460414605146061460714608146091461014611146121461314614146151461614617146181461914620146211462214623146241462514626146271462814629146301463114632146331463414635146361463714638146391464014641146421464314644146451464614647146481464914650146511465214653146541465514656146571465814659146601466114662146631466414665146661466714668146691467014671146721467314674146751467614677146781467914680146811468214683146841468514686146871468814689146901469114692146931469414695146961469714698146991470014701147021470314704147051470614707147081470914710147111471214713147141471514716147171471814719147201472114722147231472414725147261472714728147291473014731147321473314734147351473614737147381473914740147411474214743147441474514746147471474814749147501475114752147531475414755147561475714758147591476014761147621476314764147651476614767147681476914770147711477214773147741477514776147771477814779147801478114782147831478414785147861478714788147891479014791147921479314794147951479614797147981479914800148011480214803148041480514806148071480814809148101481114812148131481414815148161481714818148191482014821148221482314824148251482614827148281482914830148311483214833148341483514836148371483814839148401484114842148431484414845148461484714848148491485014851148521485314854148551485614857148581485914860148611486214863148641486514866148671486814869148701487114872148731487414875148761487714878148791488014881148821488314884148851488614887148881488914890148911489214893148941489514896148971489814899149001490114902149031490414905149061490714908149091491014911149121491314914149151491614917149181491914920149211492214923149241492514926149271492814929149301493114932149331493414935149361493714938149391494014941149421494314944149451494614947149481494914950149511495214953149541495514956149571495814959149601496114962149631496414965149661496714968149691497014971149721497314974149751497614977149781497914980149811498214983149841498514986149871498814989149901499114992149931499414995149961499714998149991500015001150021500315004150051500615007150081500915010150111501215013150141501515016150171501815019150201502115022150231502415025150261502715028150291503015031150321503315034150351503615037150381503915040150411504215043150441504515046150471504815049150501505115052150531505415055150561505715058150591506015061150621506315064150651506615067150681506915070150711507215073150741507515076150771507815079150801508115082150831508415085150861508715088150891509015091150921509315094150951509615097150981509915100151011510215103151041510515106151071510815109151101511115112151131511415115151161511715118151191512015121151221512315124151251512615127151281512915130151311513215133151341513515136151371513815139151401514115142151431514415145151461514715148151491515015151151521515315154151551515615157151581515915160151611516215163151641516515166151671516815169151701517115172151731517415175151761517715178151791518015181151821518315184151851518615187151881518915190151911519215193151941519515196151971519815199152001520115202152031520415205152061520715208152091521015211152121521315214152151521615217152181521915220152211522215223152241522515226152271522815229152301523115232152331523415235152361523715238152391524015241152421524315244152451524615247152481524915250152511525215253152541525515256152571525815259152601526115262152631526415265152661526715268152691527015271152721527315274152751527615277152781527915280152811528215283152841528515286152871528815289152901529115292152931529415295152961529715298152991530015301153021530315304153051530615307153081530915310153111531215313153141531515316153171531815319153201532115322153231532415325153261532715328153291533015331153321533315334153351533615337153381533915340153411534215343153441534515346153471534815349153501535115352153531535415355153561535715358153591536015361153621536315364153651536615367153681536915370153711537215373153741537515376153771537815379153801538115382153831538415385153861538715388153891539015391153921539315394153951539615397153981539915400154011540215403154041540515406154071540815409154101541115412154131541415415154161541715418154191542015421154221542315424154251542615427154281542915430154311543215433154341543515436154371543815439154401544115442154431544415445154461544715448154491545015451154521545315454154551545615457154581545915460154611546215463154641546515466154671546815469154701547115472154731547415475154761547715478154791548015481154821548315484154851548615487154881548915490154911549215493154941549515496154971549815499155001550115502155031550415505155061550715508155091551015511155121551315514155151551615517155181551915520155211552215523155241552515526155271552815529155301553115532155331553415535155361553715538155391554015541155421554315544155451554615547155481554915550155511555215553155541555515556155571555815559155601556115562155631556415565155661556715568155691557015571155721557315574155751557615577155781557915580155811558215583155841558515586155871558815589155901559115592155931559415595155961559715598155991560015601156021560315604156051560615607156081560915610156111561215613156141561515616156171561815619156201562115622156231562415625156261562715628156291563015631156321563315634156351563615637156381563915640156411564215643156441564515646156471564815649156501565115652156531565415655156561565715658156591566015661156621566315664156651566615667156681566915670156711567215673156741567515676156771567815679156801568115682156831568415685156861568715688156891569015691156921569315694156951569615697156981569915700157011570215703157041570515706157071570815709157101571115712157131571415715157161571715718157191572015721157221572315724157251572615727157281572915730157311573215733157341573515736157371573815739157401574115742157431574415745157461574715748157491575015751157521575315754157551575615757157581575915760157611576215763157641576515766157671576815769157701577115772157731577415775157761577715778157791578015781157821578315784157851578615787157881578915790157911579215793157941579515796157971579815799158001580115802158031580415805158061580715808158091581015811158121581315814158151581615817158181581915820158211582215823158241582515826158271582815829158301583115832158331583415835158361583715838158391584015841158421584315844158451584615847158481584915850158511585215853158541585515856158571585815859158601586115862158631586415865158661586715868158691587015871158721587315874158751587615877158781587915880158811588215883158841588515886158871588815889158901589115892158931589415895158961589715898158991590015901159021590315904159051590615907159081590915910159111591215913159141591515916159171591815919159201592115922159231592415925159261592715928159291593015931159321593315934159351593615937159381593915940159411594215943159441594515946159471594815949159501595115952159531595415955159561595715958159591596015961159621596315964159651596615967159681596915970159711597215973159741597515976159771597815979159801598115982159831598415985159861598715988159891599015991159921599315994159951599615997159981599916000160011600216003160041600516006160071600816009160101601116012160131601416015160161601716018160191602016021160221602316024160251602616027160281602916030160311603216033160341603516036160371603816039160401604116042160431604416045160461604716048160491605016051160521605316054160551605616057160581605916060160611606216063160641606516066160671606816069160701607116072160731607416075160761607716078160791608016081160821608316084160851608616087160881608916090160911609216093160941609516096160971609816099161001610116102161031610416105161061610716108161091611016111161121611316114161151611616117161181611916120161211612216123161241612516126161271612816129161301613116132161331613416135161361613716138161391614016141161421614316144161451614616147161481614916150161511615216153161541615516156161571615816159161601616116162161631616416165161661616716168161691617016171161721617316174161751617616177161781617916180161811618216183161841618516186161871618816189161901619116192161931619416195161961619716198161991620016201162021620316204162051620616207162081620916210162111621216213162141621516216162171621816219162201622116222162231622416225162261622716228162291623016231162321623316234162351623616237162381623916240162411624216243162441624516246162471624816249162501625116252162531625416255162561625716258162591626016261162621626316264162651626616267162681626916270162711627216273162741627516276162771627816279162801628116282162831628416285162861628716288162891629016291162921629316294162951629616297162981629916300163011630216303163041630516306163071630816309163101631116312163131631416315163161631716318163191632016321163221632316324163251632616327163281632916330163311633216333163341633516336163371633816339163401634116342163431634416345163461634716348163491635016351163521635316354163551635616357163581635916360163611636216363163641636516366163671636816369163701637116372163731637416375163761637716378163791638016381163821638316384163851638616387163881638916390163911639216393163941639516396163971639816399164001640116402164031640416405164061640716408164091641016411164121641316414164151641616417164181641916420164211642216423164241642516426164271642816429164301643116432164331643416435164361643716438164391644016441164421644316444164451644616447164481644916450164511645216453164541645516456164571645816459164601646116462164631646416465164661646716468164691647016471164721647316474164751647616477164781647916480164811648216483164841648516486164871648816489164901649116492164931649416495164961649716498164991650016501165021650316504165051650616507165081650916510165111651216513165141651516516165171651816519165201652116522165231652416525165261652716528165291653016531165321653316534165351653616537165381653916540165411654216543165441654516546165471654816549165501655116552165531655416555165561655716558165591656016561165621656316564165651656616567165681656916570165711657216573165741657516576165771657816579165801658116582165831658416585165861658716588165891659016591165921659316594165951659616597165981659916600166011660216603166041660516606166071660816609166101661116612166131661416615166161661716618166191662016621166221662316624166251662616627166281662916630166311663216633166341663516636166371663816639166401664116642166431664416645166461664716648166491665016651166521665316654166551665616657166581665916660166611666216663166641666516666166671666816669166701667116672166731667416675166761667716678166791668016681166821668316684166851668616687166881668916690166911669216693166941669516696166971669816699167001670116702167031670416705167061670716708167091671016711167121671316714167151671616717167181671916720167211672216723167241672516726167271672816729167301673116732167331673416735167361673716738167391674016741167421674316744167451674616747167481674916750167511675216753167541675516756167571675816759167601676116762167631676416765167661676716768167691677016771167721677316774167751677616777167781677916780167811678216783167841678516786167871678816789167901679116792167931679416795167961679716798167991680016801168021680316804168051680616807168081680916810168111681216813168141681516816168171681816819168201682116822168231682416825168261682716828168291683016831168321683316834168351683616837168381683916840168411684216843168441684516846168471684816849168501685116852168531685416855168561685716858168591686016861168621686316864168651686616867168681686916870168711687216873168741687516876168771687816879168801688116882168831688416885168861688716888168891689016891168921689316894168951689616897168981689916900169011690216903169041690516906169071690816909169101691116912169131691416915169161691716918169191692016921169221692316924169251692616927169281692916930169311693216933169341693516936169371693816939169401694116942169431694416945169461694716948169491695016951169521695316954169551695616957169581695916960169611696216963169641696516966169671696816969169701697116972169731697416975169761697716978169791698016981169821698316984169851698616987169881698916990169911699216993169941699516996169971699816999170001700117002170031700417005170061700717008170091701017011170121701317014170151701617017170181701917020170211702217023170241702517026170271702817029170301703117032170331703417035170361703717038170391704017041170421704317044170451704617047170481704917050170511705217053170541705517056170571705817059170601706117062170631706417065170661706717068170691707017071170721707317074170751707617077170781707917080170811708217083170841708517086170871708817089170901709117092170931709417095170961709717098170991710017101171021710317104171051710617107171081710917110171111711217113171141711517116171171711817119171201712117122171231712417125171261712717128171291713017131171321713317134171351713617137171381713917140171411714217143171441714517146171471714817149171501715117152171531715417155171561715717158171591716017161171621716317164171651716617167171681716917170171711717217173171741717517176171771717817179171801718117182171831718417185171861718717188171891719017191171921719317194171951719617197171981719917200172011720217203172041720517206172071720817209172101721117212172131721417215172161721717218172191722017221172221722317224172251722617227172281722917230172311723217233172341723517236172371723817239172401724117242172431724417245172461724717248172491725017251172521725317254172551725617257172581725917260172611726217263172641726517266172671726817269172701727117272172731727417275172761727717278172791728017281172821728317284172851728617287172881728917290172911729217293172941729517296172971729817299173001730117302173031730417305173061730717308173091731017311173121731317314173151731617317173181731917320173211732217323173241732517326173271732817329173301733117332173331733417335173361733717338173391734017341173421734317344173451734617347173481734917350173511735217353173541735517356173571735817359173601736117362173631736417365173661736717368173691737017371173721737317374173751737617377173781737917380173811738217383173841738517386173871738817389173901739117392173931739417395173961739717398173991740017401174021740317404174051740617407174081740917410174111741217413174141741517416174171741817419174201742117422174231742417425174261742717428174291743017431174321743317434174351743617437174381743917440174411744217443174441744517446174471744817449174501745117452174531745417455174561745717458174591746017461174621746317464174651746617467174681746917470174711747217473174741747517476174771747817479174801748117482174831748417485174861748717488174891749017491174921749317494174951749617497174981749917500175011750217503175041750517506175071750817509175101751117512175131751417515175161751717518175191752017521175221752317524175251752617527175281752917530175311753217533175341753517536175371753817539175401754117542175431754417545175461754717548175491755017551175521755317554175551755617557175581755917560175611756217563175641756517566175671756817569175701757117572175731757417575175761757717578175791758017581175821758317584175851758617587175881758917590175911759217593175941759517596175971759817599176001760117602176031760417605176061760717608176091761017611176121761317614176151761617617176181761917620176211762217623176241762517626176271762817629176301763117632176331763417635176361763717638176391764017641176421764317644176451764617647176481764917650176511765217653176541765517656176571765817659176601766117662176631766417665176661766717668176691767017671176721767317674176751767617677176781767917680176811768217683176841768517686176871768817689176901769117692176931769417695176961769717698176991770017701177021770317704177051770617707177081770917710177111771217713177141771517716177171771817719177201772117722177231772417725177261772717728177291773017731177321773317734177351773617737177381773917740177411774217743177441774517746177471774817749177501775117752177531775417755177561775717758177591776017761177621776317764177651776617767177681776917770177711777217773177741777517776177771777817779177801778117782177831778417785177861778717788177891779017791177921779317794177951779617797177981779917800178011780217803178041780517806178071780817809178101781117812178131781417815178161781717818178191782017821178221782317824178251782617827178281782917830178311783217833178341783517836178371783817839178401784117842178431784417845178461784717848178491785017851178521785317854178551785617857178581785917860178611786217863178641786517866178671786817869178701787117872178731787417875178761787717878178791788017881178821788317884178851788617887178881788917890178911789217893178941789517896178971789817899179001790117902179031790417905179061790717908179091791017911179121791317914179151791617917179181791917920179211792217923179241792517926179271792817929179301793117932179331793417935179361793717938179391794017941179421794317944179451794617947179481794917950179511795217953179541795517956179571795817959179601796117962179631796417965179661796717968179691797017971179721797317974179751797617977179781797917980179811798217983179841798517986179871798817989179901799117992179931799417995179961799717998179991800018001180021800318004180051800618007180081800918010180111801218013180141801518016180171801818019180201802118022180231802418025180261802718028180291803018031180321803318034180351803618037180381803918040180411804218043180441804518046180471804818049180501805118052180531805418055180561805718058180591806018061180621806318064180651806618067180681806918070180711807218073180741807518076180771807818079180801808118082180831808418085180861808718088180891809018091180921809318094180951809618097180981809918100181011810218103181041810518106181071810818109181101811118112181131811418115181161811718118181191812018121181221812318124181251812618127181281812918130181311813218133181341813518136181371813818139181401814118142181431814418145181461814718148181491815018151181521815318154181551815618157181581815918160181611816218163181641816518166181671816818169181701817118172181731817418175181761817718178181791818018181181821818318184181851818618187181881818918190181911819218193181941819518196181971819818199182001820118202182031820418205182061820718208182091821018211182121821318214182151821618217182181821918220182211822218223182241822518226182271822818229182301823118232182331823418235182361823718238182391824018241182421824318244182451824618247182481824918250182511825218253182541825518256182571825818259182601826118262182631826418265182661826718268182691827018271182721827318274182751827618277182781827918280182811828218283182841828518286182871828818289182901829118292182931829418295182961829718298182991830018301183021830318304183051830618307183081830918310183111831218313183141831518316183171831818319183201832118322183231832418325183261832718328183291833018331183321833318334183351833618337183381833918340183411834218343183441834518346183471834818349183501835118352183531835418355183561835718358183591836018361183621836318364183651836618367183681836918370183711837218373183741837518376183771837818379183801838118382183831838418385183861838718388183891839018391183921839318394183951839618397183981839918400184011840218403184041840518406184071840818409184101841118412184131841418415184161841718418184191842018421184221842318424184251842618427184281842918430184311843218433184341843518436184371843818439184401844118442184431844418445184461844718448184491845018451184521845318454184551845618457184581845918460184611846218463184641846518466184671846818469184701847118472184731847418475184761847718478184791848018481184821848318484184851848618487184881848918490184911849218493184941849518496184971849818499185001850118502185031850418505185061850718508185091851018511185121851318514185151851618517185181851918520185211852218523185241852518526185271852818529185301853118532185331853418535185361853718538185391854018541185421854318544185451854618547185481854918550185511855218553185541855518556185571855818559185601856118562185631856418565185661856718568185691857018571185721857318574185751857618577185781857918580185811858218583185841858518586185871858818589185901859118592185931859418595185961859718598185991860018601186021860318604186051860618607186081860918610186111861218613186141861518616186171861818619186201862118622186231862418625186261862718628186291863018631186321863318634186351863618637186381863918640186411864218643186441864518646186471864818649186501865118652186531865418655186561865718658186591866018661186621866318664186651866618667186681866918670186711867218673186741867518676186771867818679186801868118682186831868418685186861868718688186891869018691186921869318694186951869618697186981869918700187011870218703187041870518706187071870818709187101871118712187131871418715187161871718718187191872018721187221872318724187251872618727187281872918730187311873218733187341873518736187371873818739187401874118742187431874418745187461874718748187491875018751187521875318754187551875618757187581875918760187611876218763187641876518766187671876818769187701877118772187731877418775187761877718778187791878018781187821878318784187851878618787187881878918790187911879218793187941879518796187971879818799188001880118802188031880418805188061880718808188091881018811188121881318814188151881618817188181881918820188211882218823188241882518826188271882818829188301883118832188331883418835188361883718838188391884018841188421884318844188451884618847188481884918850188511885218853188541885518856188571885818859188601886118862188631886418865188661886718868188691887018871188721887318874188751887618877188781887918880188811888218883188841888518886188871888818889188901889118892188931889418895188961889718898188991890018901189021890318904189051890618907189081890918910189111891218913189141891518916189171891818919189201892118922189231892418925189261892718928189291893018931189321893318934189351893618937189381893918940189411894218943189441894518946189471894818949189501895118952189531895418955189561895718958189591896018961189621896318964189651896618967189681896918970189711897218973189741897518976189771897818979189801898118982189831898418985189861898718988189891899018991189921899318994189951899618997189981899919000190011900219003190041900519006190071900819009190101901119012190131901419015190161901719018190191902019021190221902319024190251902619027190281902919030190311903219033190341903519036190371903819039190401904119042190431904419045190461904719048190491905019051190521905319054190551905619057190581905919060190611906219063190641906519066190671906819069190701907119072190731907419075190761907719078190791908019081190821908319084190851908619087190881908919090190911909219093190941909519096190971909819099191001910119102191031910419105191061910719108191091911019111191121911319114191151911619117191181911919120191211912219123191241912519126191271912819129191301913119132191331913419135191361913719138191391914019141191421914319144191451914619147191481914919150191511915219153191541915519156191571915819159191601916119162191631916419165191661916719168191691917019171191721917319174191751917619177191781917919180191811918219183191841918519186191871918819189191901919119192191931919419195191961919719198191991920019201192021920319204192051920619207192081920919210192111921219213192141921519216192171921819219192201922119222192231922419225192261922719228192291923019231192321923319234192351923619237192381923919240192411924219243192441924519246192471924819249192501925119252192531925419255192561925719258192591926019261192621926319264192651926619267192681926919270192711927219273192741927519276192771927819279192801928119282192831928419285192861928719288192891929019291192921929319294192951929619297192981929919300193011930219303193041930519306193071930819309193101931119312193131931419315193161931719318193191932019321193221932319324193251932619327193281932919330193311933219333193341933519336193371933819339193401934119342193431934419345193461934719348193491935019351193521935319354193551935619357193581935919360193611936219363193641936519366193671936819369193701937119372193731937419375193761937719378193791938019381193821938319384193851938619387193881938919390193911939219393193941939519396193971939819399194001940119402194031940419405194061940719408194091941019411194121941319414194151941619417194181941919420194211942219423194241942519426194271942819429194301943119432194331943419435194361943719438194391944019441194421944319444194451944619447194481944919450194511945219453194541945519456194571945819459194601946119462194631946419465194661946719468194691947019471194721947319474194751947619477194781947919480194811948219483194841948519486194871948819489194901949119492194931949419495194961949719498194991950019501195021950319504195051950619507195081950919510195111951219513195141951519516195171951819519195201952119522195231952419525195261952719528195291953019531195321953319534195351953619537195381953919540195411954219543195441954519546195471954819549195501955119552195531955419555195561955719558195591956019561195621956319564195651956619567195681956919570195711957219573195741957519576195771957819579195801958119582195831958419585195861958719588195891959019591195921959319594195951959619597195981959919600196011960219603196041960519606196071960819609196101961119612196131961419615196161961719618196191962019621196221962319624196251962619627196281962919630196311963219633196341963519636196371963819639196401964119642196431964419645196461964719648196491965019651196521965319654196551965619657196581965919660196611966219663196641966519666196671966819669196701967119672196731967419675196761967719678196791968019681196821968319684196851968619687196881968919690196911969219693196941969519696196971969819699197001970119702197031970419705197061970719708197091971019711197121971319714197151971619717197181971919720197211972219723197241972519726197271972819729197301973119732197331973419735197361973719738197391974019741197421974319744197451974619747197481974919750197511975219753197541975519756197571975819759197601976119762197631976419765197661976719768197691977019771197721977319774197751977619777197781977919780197811978219783197841978519786197871978819789197901979119792197931979419795197961979719798197991980019801198021980319804198051980619807198081980919810198111981219813198141981519816198171981819819198201982119822198231982419825198261982719828198291983019831198321983319834198351983619837198381983919840198411984219843198441984519846198471984819849198501985119852198531985419855198561985719858198591986019861198621986319864198651986619867198681986919870198711987219873198741987519876198771987819879198801988119882198831988419885198861988719888198891989019891198921989319894198951989619897198981989919900199011990219903199041990519906199071990819909199101991119912199131991419915199161991719918199191992019921199221992319924199251992619927199281992919930199311993219933199341993519936199371993819939199401994119942199431994419945199461994719948199491995019951199521995319954199551995619957199581995919960199611996219963199641996519966199671996819969199701997119972199731997419975199761997719978199791998019981199821998319984199851998619987199881998919990199911999219993199941999519996199971999819999200002000120002200032000420005200062000720008200092001020011200122001320014200152001620017200182001920020200212002220023200242002520026200272002820029200302003120032200332003420035200362003720038200392004020041200422004320044200452004620047200482004920050200512005220053200542005520056200572005820059200602006120062200632006420065200662006720068200692007020071200722007320074200752007620077200782007920080200812008220083200842008520086200872008820089200902009120092200932009420095200962009720098200992010020101201022010320104201052010620107201082010920110201112011220113201142011520116201172011820119201202012120122201232012420125201262012720128201292013020131201322013320134201352013620137201382013920140201412014220143201442014520146201472014820149201502015120152201532015420155201562015720158201592016020161201622016320164201652016620167201682016920170201712017220173201742017520176201772017820179201802018120182201832018420185201862018720188201892019020191201922019320194201952019620197201982019920200202012020220203202042020520206202072020820209202102021120212202132021420215202162021720218202192022020221202222022320224202252022620227202282022920230202312023220233202342023520236202372023820239202402024120242202432024420245202462024720248202492025020251202522025320254202552025620257202582025920260202612026220263202642026520266202672026820269202702027120272202732027420275202762027720278202792028020281202822028320284202852028620287202882028920290202912029220293202942029520296202972029820299203002030120302203032030420305203062030720308203092031020311203122031320314203152031620317203182031920320203212032220323203242032520326203272032820329203302033120332203332033420335203362033720338203392034020341203422034320344203452034620347203482034920350203512035220353203542035520356203572035820359203602036120362203632036420365203662036720368203692037020371203722037320374203752037620377203782037920380203812038220383203842038520386203872038820389203902039120392203932039420395203962039720398203992040020401204022040320404204052040620407204082040920410204112041220413204142041520416204172041820419204202042120422204232042420425204262042720428204292043020431204322043320434204352043620437204382043920440204412044220443204442044520446204472044820449204502045120452204532045420455204562045720458204592046020461204622046320464204652046620467204682046920470204712047220473204742047520476204772047820479204802048120482204832048420485204862048720488204892049020491204922049320494204952049620497204982049920500205012050220503205042050520506205072050820509205102051120512205132051420515205162051720518205192052020521205222052320524205252052620527205282052920530205312053220533205342053520536205372053820539205402054120542205432054420545205462054720548205492055020551205522055320554205552055620557205582055920560205612056220563205642056520566205672056820569205702057120572205732057420575205762057720578205792058020581205822058320584205852058620587205882058920590205912059220593205942059520596205972059820599206002060120602206032060420605206062060720608206092061020611206122061320614206152061620617206182061920620206212062220623206242062520626206272062820629206302063120632206332063420635206362063720638206392064020641206422064320644206452064620647206482064920650206512065220653206542065520656206572065820659206602066120662206632066420665206662066720668206692067020671206722067320674206752067620677206782067920680206812068220683206842068520686206872068820689206902069120692206932069420695206962069720698206992070020701207022070320704207052070620707207082070920710207112071220713207142071520716207172071820719207202072120722207232072420725207262072720728207292073020731207322073320734207352073620737207382073920740207412074220743207442074520746207472074820749207502075120752207532075420755207562075720758207592076020761207622076320764207652076620767207682076920770207712077220773207742077520776207772077820779207802078120782207832078420785207862078720788207892079020791207922079320794207952079620797207982079920800208012080220803208042080520806208072080820809208102081120812208132081420815208162081720818208192082020821208222082320824208252082620827208282082920830208312083220833208342083520836208372083820839208402084120842208432084420845208462084720848208492085020851208522085320854208552085620857208582085920860208612086220863208642086520866208672086820869208702087120872208732087420875208762087720878208792088020881208822088320884208852088620887208882088920890208912089220893208942089520896208972089820899209002090120902209032090420905209062090720908209092091020911209122091320914209152091620917209182091920920209212092220923209242092520926209272092820929209302093120932209332093420935209362093720938209392094020941209422094320944209452094620947209482094920950209512095220953209542095520956209572095820959209602096120962209632096420965209662096720968209692097020971209722097320974209752097620977209782097920980209812098220983209842098520986209872098820989209902099120992209932099420995209962099720998209992100021001210022100321004210052100621007210082100921010210112101221013210142101521016210172101821019210202102121022210232102421025210262102721028210292103021031210322103321034210352103621037210382103921040210412104221043210442104521046210472104821049210502105121052210532105421055210562105721058210592106021061210622106321064210652106621067210682106921070210712107221073210742107521076210772107821079210802108121082210832108421085210862108721088210892109021091210922109321094210952109621097210982109921100211012110221103211042110521106211072110821109211102111121112211132111421115211162111721118211192112021121211222112321124211252112621127211282112921130211312113221133211342113521136211372113821139211402114121142211432114421145211462114721148211492115021151211522115321154211552115621157211582115921160211612116221163211642116521166211672116821169211702117121172211732117421175211762117721178211792118021181211822118321184211852118621187211882118921190211912119221193211942119521196211972119821199212002120121202212032120421205212062120721208212092121021211212122121321214212152121621217212182121921220212212122221223212242122521226212272122821229212302123121232212332123421235212362123721238212392124021241212422124321244212452124621247212482124921250212512125221253212542125521256212572125821259212602126121262212632126421265212662126721268212692127021271212722127321274212752127621277212782127921280212812128221283212842128521286212872128821289212902129121292212932129421295212962129721298212992130021301213022130321304213052130621307213082130921310213112131221313213142131521316213172131821319213202132121322213232132421325213262132721328213292133021331213322133321334213352133621337213382133921340213412134221343213442134521346213472134821349213502135121352213532135421355213562135721358213592136021361213622136321364213652136621367213682136921370213712137221373213742137521376213772137821379213802138121382213832138421385213862138721388213892139021391213922139321394213952139621397213982139921400214012140221403214042140521406214072140821409214102141121412214132141421415214162141721418214192142021421214222142321424214252142621427214282142921430214312143221433214342143521436214372143821439214402144121442214432144421445214462144721448214492145021451214522145321454214552145621457214582145921460214612146221463214642146521466214672146821469214702147121472214732147421475214762147721478214792148021481214822148321484214852148621487214882148921490214912149221493214942149521496214972149821499215002150121502215032150421505215062150721508215092151021511215122151321514215152151621517215182151921520215212152221523215242152521526215272152821529215302153121532215332153421535215362153721538215392154021541215422154321544215452154621547215482154921550215512155221553215542155521556215572155821559215602156121562215632156421565215662156721568215692157021571215722157321574215752157621577215782157921580215812158221583215842158521586215872158821589215902159121592215932159421595215962159721598215992160021601216022160321604216052160621607216082160921610216112161221613216142161521616216172161821619216202162121622216232162421625216262162721628216292163021631216322163321634216352163621637216382163921640216412164221643216442164521646216472164821649216502165121652216532165421655216562165721658216592166021661216622166321664216652166621667216682166921670216712167221673216742167521676216772167821679216802168121682216832168421685216862168721688216892169021691216922169321694216952169621697216982169921700217012170221703217042170521706217072170821709217102171121712217132171421715217162171721718217192172021721217222172321724217252172621727217282172921730217312173221733217342173521736217372173821739217402174121742217432174421745217462174721748217492175021751217522175321754217552175621757217582175921760217612176221763217642176521766217672176821769217702177121772217732177421775217762177721778217792178021781217822178321784217852178621787217882178921790217912179221793217942179521796217972179821799218002180121802218032180421805218062180721808218092181021811218122181321814218152181621817218182181921820218212182221823218242182521826218272182821829218302183121832218332183421835218362183721838218392184021841218422184321844218452184621847218482184921850218512185221853218542185521856218572185821859218602186121862218632186421865218662186721868218692187021871218722187321874218752187621877218782187921880218812188221883218842188521886218872188821889218902189121892218932189421895218962189721898218992190021901219022190321904219052190621907219082190921910219112191221913219142191521916219172191821919219202192121922219232192421925219262192721928219292193021931219322193321934219352193621937219382193921940219412194221943219442194521946219472194821949219502195121952219532195421955219562195721958219592196021961219622196321964219652196621967219682196921970219712197221973219742197521976219772197821979219802198121982219832198421985219862198721988219892199021991219922199321994219952199621997219982199922000220012200222003220042200522006220072200822009220102201122012220132201422015220162201722018220192202022021220222202322024220252202622027220282202922030220312203222033220342203522036220372203822039220402204122042220432204422045220462204722048220492205022051220522205322054220552205622057220582205922060220612206222063220642206522066220672206822069220702207122072220732207422075220762207722078220792208022081220822208322084220852208622087220882208922090220912209222093220942209522096220972209822099221002210122102221032210422105221062210722108221092211022111221122211322114221152211622117221182211922120221212212222123221242212522126221272212822129221302213122132221332213422135221362213722138221392214022141221422214322144221452214622147221482214922150221512215222153221542215522156221572215822159221602216122162221632216422165221662216722168221692217022171221722217322174221752217622177221782217922180221812218222183221842218522186221872218822189221902219122192221932219422195221962219722198221992220022201222022220322204222052220622207222082220922210222112221222213222142221522216222172221822219222202222122222222232222422225222262222722228222292223022231222322223322234222352223622237222382223922240222412224222243222442224522246222472224822249222502225122252222532225422255222562225722258222592226022261222622226322264222652226622267222682226922270222712227222273222742227522276222772227822279222802228122282222832228422285222862228722288222892229022291222922229322294222952229622297222982229922300223012230222303223042230522306223072230822309223102231122312223132231422315223162231722318223192232022321223222232322324223252232622327223282232922330223312233222333223342233522336223372233822339223402234122342223432234422345223462234722348223492235022351223522235322354223552235622357223582235922360223612236222363223642236522366223672236822369223702237122372223732237422375223762237722378223792238022381223822238322384223852238622387223882238922390223912239222393223942239522396223972239822399224002240122402224032240422405224062240722408224092241022411224122241322414224152241622417224182241922420224212242222423224242242522426224272242822429224302243122432224332243422435224362243722438224392244022441224422244322444224452244622447224482244922450224512245222453224542245522456224572245822459224602246122462224632246422465224662246722468224692247022471224722247322474224752247622477224782247922480224812248222483224842248522486224872248822489224902249122492224932249422495224962249722498224992250022501225022250322504225052250622507225082250922510225112251222513225142251522516225172251822519225202252122522225232252422525225262252722528225292253022531225322253322534225352253622537225382253922540225412254222543225442254522546225472254822549225502255122552225532255422555225562255722558225592256022561225622256322564225652256622567225682256922570225712257222573225742257522576225772257822579225802258122582225832258422585225862258722588225892259022591225922259322594225952259622597225982259922600226012260222603226042260522606226072260822609226102261122612226132261422615226162261722618226192262022621226222262322624226252262622627226282262922630226312263222633226342263522636226372263822639226402264122642226432264422645226462264722648226492265022651226522265322654226552265622657226582265922660226612266222663226642266522666226672266822669226702267122672226732267422675226762267722678226792268022681226822268322684226852268622687226882268922690226912269222693226942269522696226972269822699227002270122702227032270422705227062270722708227092271022711227122271322714227152271622717227182271922720227212272222723227242272522726227272272822729227302273122732227332273422735227362273722738227392274022741227422274322744227452274622747227482274922750227512275222753227542275522756227572275822759227602276122762227632276422765227662276722768227692277022771227722277322774227752277622777227782277922780227812278222783227842278522786227872278822789227902279122792227932279422795227962279722798227992280022801228022280322804228052280622807228082280922810228112281222813228142281522816228172281822819228202282122822228232282422825228262282722828228292283022831228322283322834228352283622837228382283922840228412284222843228442284522846228472284822849228502285122852228532285422855228562285722858228592286022861228622286322864228652286622867228682286922870228712287222873228742287522876228772287822879228802288122882228832288422885228862288722888228892289022891228922289322894228952289622897228982289922900229012290222903229042290522906229072290822909229102291122912229132291422915229162291722918229192292022921229222292322924229252292622927229282292922930229312293222933229342293522936229372293822939229402294122942229432294422945229462294722948229492295022951229522295322954229552295622957229582295922960229612296222963229642296522966229672296822969229702297122972229732297422975229762297722978229792298022981229822298322984229852298622987229882298922990229912299222993229942299522996229972299822999230002300123002230032300423005230062300723008230092301023011230122301323014230152301623017230182301923020230212302223023230242302523026230272302823029230302303123032230332303423035230362303723038230392304023041230422304323044230452304623047230482304923050230512305223053230542305523056230572305823059230602306123062230632306423065230662306723068230692307023071230722307323074230752307623077230782307923080230812308223083230842308523086230872308823089230902309123092230932309423095230962309723098230992310023101231022310323104231052310623107231082310923110231112311223113231142311523116231172311823119231202312123122231232312423125231262312723128231292313023131231322313323134231352313623137231382313923140231412314223143231442314523146231472314823149231502315123152231532315423155231562315723158231592316023161231622316323164231652316623167231682316923170231712317223173231742317523176231772317823179231802318123182231832318423185231862318723188231892319023191231922319323194231952319623197231982319923200232012320223203232042320523206232072320823209232102321123212232132321423215232162321723218232192322023221232222322323224232252322623227232282322923230232312323223233232342323523236232372323823239232402324123242232432324423245232462324723248232492325023251232522325323254232552325623257232582325923260232612326223263232642326523266232672326823269232702327123272232732327423275232762327723278232792328023281232822328323284232852328623287232882328923290232912329223293232942329523296232972329823299233002330123302233032330423305233062330723308233092331023311233122331323314233152331623317233182331923320233212332223323233242332523326233272332823329233302333123332233332333423335233362333723338233392334023341233422334323344233452334623347233482334923350233512335223353233542335523356233572335823359233602336123362233632336423365233662336723368233692337023371233722337323374233752337623377233782337923380233812338223383233842338523386233872338823389233902339123392233932339423395233962339723398233992340023401234022340323404234052340623407234082340923410234112341223413234142341523416234172341823419234202342123422234232342423425234262342723428234292343023431234322343323434234352343623437234382343923440234412344223443234442344523446234472344823449234502345123452234532345423455234562345723458234592346023461234622346323464234652346623467234682346923470234712347223473234742347523476234772347823479234802348123482234832348423485234862348723488234892349023491234922349323494234952349623497234982349923500235012350223503235042350523506235072350823509235102351123512235132351423515235162351723518235192352023521235222352323524235252352623527235282352923530235312353223533235342353523536235372353823539235402354123542235432354423545235462354723548235492355023551235522355323554235552355623557235582355923560235612356223563235642356523566235672356823569235702357123572235732357423575235762357723578235792358023581235822358323584235852358623587235882358923590235912359223593235942359523596235972359823599236002360123602236032360423605236062360723608236092361023611236122361323614236152361623617236182361923620236212362223623236242362523626236272362823629236302363123632236332363423635236362363723638236392364023641236422364323644236452364623647236482364923650236512365223653236542365523656236572365823659236602366123662236632366423665236662366723668236692367023671236722367323674236752367623677236782367923680236812368223683236842368523686236872368823689236902369123692236932369423695236962369723698236992370023701237022370323704237052370623707237082370923710237112371223713237142371523716237172371823719237202372123722237232372423725237262372723728237292373023731237322373323734237352373623737237382373923740237412374223743237442374523746237472374823749237502375123752237532375423755237562375723758237592376023761237622376323764237652376623767237682376923770237712377223773237742377523776237772377823779237802378123782237832378423785237862378723788237892379023791237922379323794237952379623797237982379923800238012380223803238042380523806238072380823809238102381123812238132381423815238162381723818238192382023821238222382323824238252382623827238282382923830238312383223833238342383523836238372383823839238402384123842238432384423845238462384723848238492385023851238522385323854238552385623857238582385923860238612386223863238642386523866238672386823869238702387123872238732387423875238762387723878238792388023881238822388323884238852388623887238882388923890238912389223893238942389523896238972389823899239002390123902239032390423905239062390723908239092391023911239122391323914239152391623917239182391923920239212392223923239242392523926239272392823929239302393123932239332393423935239362393723938239392394023941239422394323944239452394623947239482394923950239512395223953239542395523956239572395823959239602396123962239632396423965239662396723968239692397023971239722397323974239752397623977239782397923980239812398223983239842398523986239872398823989239902399123992239932399423995239962399723998239992400024001240022400324004240052400624007240082400924010240112401224013240142401524016240172401824019240202402124022240232402424025240262402724028240292403024031240322403324034240352403624037240382403924040240412404224043240442404524046240472404824049240502405124052240532405424055240562405724058240592406024061240622406324064240652406624067240682406924070240712407224073240742407524076240772407824079240802408124082240832408424085240862408724088240892409024091240922409324094240952409624097240982409924100241012410224103241042410524106241072410824109241102411124112241132411424115241162411724118241192412024121241222412324124241252412624127241282412924130241312413224133241342413524136241372413824139241402414124142241432414424145241462414724148241492415024151241522415324154241552415624157241582415924160241612416224163241642416524166241672416824169241702417124172241732417424175241762417724178241792418024181241822418324184241852418624187241882418924190241912419224193241942419524196241972419824199242002420124202242032420424205242062420724208242092421024211242122421324214242152421624217242182421924220242212422224223242242422524226242272422824229242302423124232242332423424235242362423724238242392424024241242422424324244242452424624247242482424924250242512425224253242542425524256242572425824259242602426124262242632426424265242662426724268242692427024271242722427324274242752427624277242782427924280242812428224283242842428524286242872428824289242902429124292242932429424295242962429724298242992430024301243022430324304243052430624307243082430924310243112431224313243142431524316243172431824319243202432124322243232432424325243262432724328243292433024331243322433324334243352433624337243382433924340243412434224343243442434524346243472434824349243502435124352243532435424355243562435724358243592436024361243622436324364243652436624367243682436924370243712437224373243742437524376243772437824379243802438124382243832438424385243862438724388243892439024391243922439324394243952439624397243982439924400244012440224403244042440524406244072440824409244102441124412244132441424415244162441724418244192442024421244222442324424244252442624427244282442924430244312443224433244342443524436244372443824439244402444124442244432444424445244462444724448244492445024451244522445324454244552445624457244582445924460244612446224463244642446524466244672446824469244702447124472244732447424475244762447724478244792448024481244822448324484244852448624487244882448924490244912449224493244942449524496244972449824499245002450124502245032450424505245062450724508245092451024511245122451324514245152451624517245182451924520245212452224523245242452524526245272452824529245302453124532245332453424535245362453724538245392454024541245422454324544245452454624547245482454924550245512455224553245542455524556245572455824559245602456124562245632456424565245662456724568245692457024571245722457324574245752457624577245782457924580245812458224583245842458524586245872458824589245902459124592245932459424595245962459724598245992460024601246022460324604246052460624607246082460924610246112461224613246142461524616246172461824619246202462124622246232462424625246262462724628246292463024631246322463324634246352463624637246382463924640246412464224643246442464524646246472464824649246502465124652246532465424655246562465724658246592466024661246622466324664246652466624667246682466924670246712467224673246742467524676246772467824679246802468124682246832468424685246862468724688246892469024691246922469324694246952469624697246982469924700247012470224703247042470524706247072470824709247102471124712247132471424715247162471724718247192472024721247222472324724247252472624727247282472924730247312473224733247342473524736247372473824739247402474124742247432474424745247462474724748247492475024751247522475324754247552475624757247582475924760247612476224763247642476524766247672476824769247702477124772247732477424775247762477724778247792478024781247822478324784247852478624787247882478924790247912479224793247942479524796247972479824799248002480124802248032480424805248062480724808248092481024811248122481324814248152481624817248182481924820248212482224823248242482524826248272482824829248302483124832248332483424835248362483724838248392484024841248422484324844248452484624847248482484924850248512485224853248542485524856248572485824859248602486124862248632486424865248662486724868248692487024871248722487324874248752487624877248782487924880248812488224883248842488524886248872488824889248902489124892248932489424895248962489724898248992490024901249022490324904249052490624907249082490924910249112491224913249142491524916249172491824919249202492124922249232492424925249262492724928249292493024931249322493324934249352493624937249382493924940249412494224943249442494524946249472494824949249502495124952249532495424955249562495724958249592496024961249622496324964249652496624967249682496924970249712497224973249742497524976249772497824979249802498124982249832498424985249862498724988249892499024991249922499324994249952499624997249982499925000250012500225003250042500525006250072500825009250102501125012250132501425015250162501725018250192502025021250222502325024250252502625027250282502925030250312503225033250342503525036250372503825039250402504125042250432504425045250462504725048250492505025051250522505325054250552505625057250582505925060250612506225063250642506525066250672506825069250702507125072250732507425075250762507725078250792508025081250822508325084250852508625087250882508925090250912509225093250942509525096250972509825099251002510125102251032510425105251062510725108251092511025111251122511325114251152511625117251182511925120251212512225123251242512525126251272512825129251302513125132251332513425135251362513725138251392514025141251422514325144251452514625147251482514925150251512515225153251542515525156251572515825159251602516125162251632516425165251662516725168251692517025171251722517325174251752517625177251782517925180251812518225183251842518525186251872518825189251902519125192251932519425195251962519725198251992520025201252022520325204252052520625207252082520925210252112521225213252142521525216252172521825219252202522125222252232522425225252262522725228252292523025231252322523325234252352523625237252382523925240252412524225243252442524525246252472524825249252502525125252252532525425255252562525725258252592526025261252622526325264252652526625267252682526925270252712527225273252742527525276252772527825279252802528125282252832528425285252862528725288252892529025291252922529325294252952529625297252982529925300253012530225303253042530525306253072530825309253102531125312253132531425315253162531725318253192532025321253222532325324253252532625327253282532925330253312533225333253342533525336253372533825339253402534125342253432534425345253462534725348253492535025351253522535325354253552535625357253582535925360253612536225363253642536525366253672536825369253702537125372253732537425375253762537725378253792538025381253822538325384253852538625387253882538925390253912539225393253942539525396253972539825399254002540125402254032540425405254062540725408254092541025411254122541325414254152541625417254182541925420254212542225423254242542525426254272542825429254302543125432254332543425435254362543725438254392544025441254422544325444254452544625447254482544925450254512545225453254542545525456254572545825459254602546125462254632546425465254662546725468254692547025471254722547325474254752547625477254782547925480254812548225483254842548525486254872548825489254902549125492254932549425495254962549725498254992550025501255022550325504255052550625507255082550925510255112551225513255142551525516255172551825519255202552125522255232552425525255262552725528255292553025531255322553325534255352553625537255382553925540255412554225543255442554525546255472554825549255502555125552255532555425555255562555725558255592556025561255622556325564255652556625567255682556925570255712557225573255742557525576255772557825579255802558125582255832558425585255862558725588255892559025591255922559325594255952559625597255982559925600256012560225603256042560525606256072560825609256102561125612256132561425615256162561725618256192562025621256222562325624256252562625627256282562925630256312563225633256342563525636256372563825639256402564125642256432564425645256462564725648256492565025651256522565325654256552565625657256582565925660256612566225663256642566525666256672566825669256702567125672256732567425675256762567725678256792568025681256822568325684256852568625687256882568925690256912569225693256942569525696256972569825699257002570125702257032570425705257062570725708257092571025711257122571325714257152571625717257182571925720257212572225723257242572525726257272572825729257302573125732257332573425735257362573725738257392574025741257422574325744257452574625747257482574925750257512575225753257542575525756257572575825759257602576125762257632576425765257662576725768257692577025771257722577325774257752577625777257782577925780257812578225783257842578525786257872578825789257902579125792257932579425795257962579725798257992580025801258022580325804258052580625807258082580925810258112581225813258142581525816258172581825819258202582125822258232582425825258262582725828258292583025831258322583325834258352583625837258382583925840258412584225843258442584525846258472584825849258502585125852258532585425855258562585725858258592586025861258622586325864258652586625867258682586925870258712587225873258742587525876258772587825879258802588125882258832588425885258862588725888258892589025891258922589325894258952589625897258982589925900259012590225903259042590525906259072590825909259102591125912259132591425915259162591725918259192592025921259222592325924259252592625927259282592925930259312593225933259342593525936259372593825939259402594125942259432594425945259462594725948259492595025951259522595325954259552595625957259582595925960259612596225963259642596525966259672596825969259702597125972259732597425975259762597725978259792598025981259822598325984259852598625987259882598925990259912599225993259942599525996259972599825999260002600126002260032600426005260062600726008260092601026011260122601326014260152601626017260182601926020260212602226023260242602526026260272602826029260302603126032260332603426035260362603726038260392604026041260422604326044260452604626047260482604926050260512605226053260542605526056260572605826059260602606126062260632606426065260662606726068260692607026071260722607326074260752607626077260782607926080260812608226083260842608526086260872608826089260902609126092260932609426095260962609726098260992610026101261022610326104261052610626107261082610926110261112611226113261142611526116261172611826119261202612126122261232612426125261262612726128261292613026131261322613326134261352613626137261382613926140261412614226143261442614526146261472614826149261502615126152261532615426155261562615726158261592616026161261622616326164261652616626167261682616926170261712617226173261742617526176261772617826179261802618126182261832618426185261862618726188261892619026191261922619326194261952619626197261982619926200262012620226203262042620526206262072620826209262102621126212262132621426215262162621726218262192622026221262222622326224262252622626227262282622926230262312623226233262342623526236262372623826239262402624126242262432624426245262462624726248262492625026251262522625326254262552625626257262582625926260262612626226263262642626526266262672626826269262702627126272262732627426275262762627726278262792628026281262822628326284262852628626287262882628926290262912629226293262942629526296262972629826299263002630126302263032630426305263062630726308263092631026311263122631326314263152631626317263182631926320263212632226323263242632526326263272632826329263302633126332263332633426335263362633726338263392634026341263422634326344263452634626347263482634926350263512635226353263542635526356263572635826359263602636126362263632636426365263662636726368263692637026371263722637326374263752637626377263782637926380263812638226383263842638526386263872638826389
  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_PRIVATE_KEY_FILE "./key.pem"
  42. #define CA_CERT_FILE "./ca-bundle.crt"
  43. #define CLIENT_CA_CERT_FILE "./rootCA.cert.pem"
  44. #define CLIENT_CA_CERT_DIR "."
  45. #define CLIENT_CERT_FILE "./client.cert.pem"
  46. #define CLIENT_PRIVATE_KEY_FILE "./client.key.pem"
  47. #define CLIENT_ENCRYPTED_CERT_FILE "./client_encrypted.cert.pem"
  48. // Mbed TLS < 3.6 (e.g. Ubuntu's 2.28) has no PBES2-AES and needs the PBES1-3DES
  49. // key; 3.6+/4.x (4.x dropped DES) and OpenSSL/wolfSSL use the PBES2 AES key.
  50. #if defined(CPPHTTPLIB_MBEDTLS_SUPPORT) && (MBEDTLS_VERSION_NUMBER < 0x03060000)
  51. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted_pbes1.key.pem"
  52. #else
  53. #define CLIENT_ENCRYPTED_PRIVATE_KEY_FILE "./client_encrypted.key.pem"
  54. #endif
  55. #define CLIENT_ENCRYPTED_PRIVATE_KEY_PASS "test012!"
  56. #define SERVER_ENCRYPTED_CERT_FILE "./cert_encrypted.pem"
  57. #define SERVER_ENCRYPTED_PRIVATE_KEY_FILE "./key_encrypted.pem"
  58. #define SERVER_ENCRYPTED_PRIVATE_KEY_PASS "test123!"
  59. #ifdef CPPHTTPLIB_SSL_ENABLED
  60. namespace httplib {
  61. namespace tls {
  62. // Declared here for the split build, where the TLS abstraction declarations
  63. // live below the split border; the definition is linked from httplib.cc.
  64. ca_store_t create_ca_store(const char *pem, size_t len);
  65. } // namespace tls
  66. } // namespace httplib
  67. #endif
  68. using namespace std;
  69. using namespace httplib;
  70. const char *HOST = "localhost";
  71. static int get_base_port() {
  72. const char *shard = getenv("GTEST_SHARD_INDEX");
  73. return shard ? 11234 + std::atoi(shard) * 100 : 1234;
  74. }
  75. // NOTE: PORT is only for legacy fixtures (ServerTest, etc.).
  76. // New standalone tests MUST use svr.bind_to_any_port() instead.
  77. const int PORT = get_base_port();
  78. const string LONG_QUERY_VALUE = string(25000, '@');
  79. const string LONG_QUERY_URL = "/long-query-value?key=" + LONG_QUERY_VALUE;
  80. const string TOO_LONG_QUERY_VALUE = string(35000, '@');
  81. const string TOO_LONG_QUERY_URL =
  82. "/too-long-query-value?key=" + TOO_LONG_QUERY_VALUE;
  83. const std::string JSON_DATA = "{\"hello\":\"world\"}";
  84. const string LARGE_DATA = string(1024 * 1024 * 100, '@'); // 100MB
  85. FormData &get_file_value(std::vector<FormData> &items, const char *key) {
  86. auto it = std::find_if(items.begin(), items.end(), [&](const FormData &file) {
  87. return file.name == key;
  88. });
  89. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  90. return *it;
  91. #else
  92. if (it != items.end()) { return *it; }
  93. throw std::runtime_error("invalid multipart form data name error");
  94. #endif
  95. }
  96. static void read_file(const std::string &path, std::string &out) {
  97. std::ifstream fs(path, std::ios_base::binary);
  98. if (!fs) {
  99. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  100. return;
  101. #else
  102. throw std::runtime_error("File not found: " + path);
  103. #endif
  104. }
  105. fs.seekg(0, std::ios_base::end);
  106. auto size = fs.tellg();
  107. fs.seekg(0);
  108. out.resize(static_cast<size_t>(size));
  109. fs.read(&out[0], static_cast<std::streamsize>(size));
  110. }
  111. class UnixSocketTest : public ::testing::Test {
  112. protected:
  113. void TearDown() override { std::remove(pathname_.c_str()); }
  114. void client_GET(const std::string &addr) {
  115. httplib::Client cli{addr};
  116. cli.set_address_family(AF_UNIX);
  117. ASSERT_TRUE(cli.is_valid());
  118. const auto &result = cli.Get(pattern_);
  119. ASSERT_TRUE(result) << "error: " << result.error();
  120. const auto &resp = result.value();
  121. EXPECT_EQ(resp.status, StatusCode::OK_200);
  122. EXPECT_EQ(resp.body, content_);
  123. }
  124. static std::string make_sock_path() {
  125. const char *shard = getenv("GTEST_SHARD_INDEX");
  126. return shard ? std::string("./httplib-server-") + shard + ".sock"
  127. : "./httplib-server.sock";
  128. }
  129. const std::string pathname_{make_sock_path()};
  130. const std::string pattern_{"/hi"};
  131. const std::string content_{"Hello World!"};
  132. };
  133. TEST_F(UnixSocketTest, pathname) {
  134. httplib::Server svr;
  135. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  136. res.set_content(content_, "text/plain");
  137. });
  138. std::thread t{[&] {
  139. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  140. }};
  141. auto se = detail::scope_exit([&] {
  142. svr.stop();
  143. t.join();
  144. ASSERT_FALSE(svr.is_running());
  145. });
  146. svr.wait_until_ready();
  147. ASSERT_TRUE(svr.is_running());
  148. client_GET(pathname_);
  149. }
  150. #if defined(__linux__) || \
  151. /* __APPLE__ */ (defined(SOL_LOCAL) && defined(SO_PEERPID))
  152. TEST_F(UnixSocketTest, PeerPid) {
  153. httplib::Server svr;
  154. std::string remote_port_val;
  155. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  156. res.set_content(content_, "text/plain");
  157. remote_port_val = std::to_string(req.remote_port);
  158. });
  159. std::thread t{[&] {
  160. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  161. }};
  162. auto se = detail::scope_exit([&] {
  163. svr.stop();
  164. t.join();
  165. ASSERT_FALSE(svr.is_running());
  166. });
  167. svr.wait_until_ready();
  168. ASSERT_TRUE(svr.is_running());
  169. client_GET(pathname_);
  170. EXPECT_EQ(std::to_string(getpid()), remote_port_val);
  171. }
  172. #endif
  173. #ifdef __linux__
  174. TEST_F(UnixSocketTest, abstract) {
  175. constexpr char svr_path[]{"\x00httplib-server.sock"};
  176. const std::string abstract_addr{svr_path, sizeof(svr_path) - 1};
  177. httplib::Server svr;
  178. svr.Get(pattern_, [&](const httplib::Request &, httplib::Response &res) {
  179. res.set_content(content_, "text/plain");
  180. });
  181. std::thread t{[&] {
  182. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(abstract_addr, 80));
  183. }};
  184. auto se = detail::scope_exit([&] {
  185. svr.stop();
  186. t.join();
  187. ASSERT_FALSE(svr.is_running());
  188. });
  189. svr.wait_until_ready();
  190. ASSERT_TRUE(svr.is_running());
  191. client_GET(abstract_addr);
  192. }
  193. #endif
  194. TEST_F(UnixSocketTest, HostHeaderAutoSet) {
  195. httplib::Server svr;
  196. std::string received_host_header;
  197. svr.Get(pattern_, [&](const httplib::Request &req, httplib::Response &res) {
  198. // Capture the Host header sent by the client
  199. auto host_iter = req.headers.find("Host");
  200. if (host_iter != req.headers.end()) {
  201. received_host_header = host_iter->second;
  202. }
  203. res.set_content(content_, "text/plain");
  204. });
  205. std::thread t{[&] {
  206. ASSERT_TRUE(svr.set_address_family(AF_UNIX).listen(pathname_, 80));
  207. }};
  208. auto se = detail::scope_exit([&] {
  209. svr.stop();
  210. t.join();
  211. ASSERT_FALSE(svr.is_running());
  212. });
  213. svr.wait_until_ready();
  214. ASSERT_TRUE(svr.is_running());
  215. // Test that Host header is automatically set to "localhost" for Unix socket
  216. // connections
  217. httplib::Client cli{pathname_};
  218. cli.set_address_family(AF_UNIX);
  219. ASSERT_TRUE(cli.is_valid());
  220. const auto &result = cli.Get(pattern_);
  221. ASSERT_TRUE(result) << "error: " << result.error();
  222. const auto &resp = result.value();
  223. EXPECT_EQ(resp.status, StatusCode::OK_200);
  224. EXPECT_EQ(resp.body, content_);
  225. // Verify that Host header was automatically set to "localhost"
  226. EXPECT_EQ(received_host_header, "localhost");
  227. }
  228. #ifndef _WIN32
  229. TEST(SocketStream, wait_writable_UNIX) {
  230. int fds[2];
  231. ASSERT_EQ(0, socketpair(AF_UNIX, SOCK_STREAM, 0, fds));
  232. const auto asSocketStream = [&](socket_t fd,
  233. std::function<bool(Stream &)> func) {
  234. return detail::process_client_socket(
  235. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  236. };
  237. asSocketStream(fds[0], [&](Stream &s0) {
  238. EXPECT_EQ(s0.socket(), fds[0]);
  239. EXPECT_TRUE(s0.wait_writable());
  240. EXPECT_TRUE(s0.is_peer_alive());
  241. EXPECT_EQ(0, close(fds[1]));
  242. EXPECT_FALSE(s0.is_peer_alive());
  243. return true;
  244. });
  245. EXPECT_EQ(0, close(fds[0]));
  246. }
  247. TEST(SocketStream, wait_writable_INET) {
  248. sockaddr_in addr;
  249. memset(&addr, 0, sizeof(addr));
  250. addr.sin_family = AF_INET;
  251. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  252. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  253. int disconnected_svr_sock = -1;
  254. std::thread svr{[&] {
  255. const int s = socket(AF_INET, SOCK_STREAM, 0);
  256. ASSERT_LE(0, s);
  257. // PORT + 1 is shared with the SSL redirect tests and with
  258. // VulnerabilityTest.CRLFInjectionInHeaders, all of which set this. Without
  259. // it, a TIME_WAIT one of them left behind makes bind() fail here, and
  260. // because that happens on a worker thread the ASSERT does not stop the
  261. // test: it runs on and fails at the disconnected_svr_sock check instead.
  262. default_socket_options(s);
  263. ASSERT_EQ(0, ::bind(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  264. ASSERT_EQ(0, listen(s, 1));
  265. ASSERT_LE(0, disconnected_svr_sock = accept(s, nullptr, nullptr));
  266. ASSERT_EQ(0, close(s));
  267. }};
  268. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  269. std::thread cli{[&] {
  270. const int s = socket(AF_INET, SOCK_STREAM, 0);
  271. ASSERT_LE(0, s);
  272. ASSERT_EQ(0, connect(s, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  273. ASSERT_EQ(0, close(s));
  274. }};
  275. cli.join();
  276. svr.join();
  277. ASSERT_NE(disconnected_svr_sock, -1);
  278. const auto asSocketStream = [&](socket_t fd,
  279. std::function<bool(Stream &)> func) {
  280. return detail::process_client_socket(
  281. fd, 0, 0, 0, 0, 0, std::chrono::steady_clock::time_point::min(), func);
  282. };
  283. asSocketStream(disconnected_svr_sock, [&](Stream &ss) {
  284. EXPECT_EQ(ss.socket(), disconnected_svr_sock);
  285. // wait_writable() returns true because select_write() only checks if the
  286. // send buffer has space. Peer disconnection is detected later by send().
  287. EXPECT_TRUE(ss.wait_writable());
  288. return true;
  289. });
  290. ASSERT_EQ(0, close(disconnected_svr_sock));
  291. }
  292. #endif // #ifndef _WIN32
  293. TEST(SetSocketOptTest, TcpNoDelay) {
  294. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  295. ASSERT_NE(sock, INVALID_SOCKET);
  296. EXPECT_TRUE(set_socket_opt(sock, IPPROTO_TCP, TCP_NODELAY, 1));
  297. int val = 0;
  298. socklen_t len = sizeof(val);
  299. ASSERT_EQ(0, ::getsockopt(sock, IPPROTO_TCP, TCP_NODELAY,
  300. reinterpret_cast<char *>(&val), &len));
  301. EXPECT_NE(val, 0);
  302. detail::close_socket(sock);
  303. }
  304. TEST(AcceptErrorTest, RetryableFailuresAreClassifiedPerPlatform) {
  305. // accept() reports failures through WSAGetLastError() on Windows and through
  306. // errno everywhere else. Asking the wrong one is what made the accept loop
  307. // treat every recoverable failure as fatal on Windows.
  308. struct Classification {
  309. bool resource;
  310. bool transient;
  311. };
  312. auto classify = [](int err) {
  313. #ifdef _WIN32
  314. WSASetLastError(err);
  315. #else
  316. errno = err;
  317. #endif
  318. // Read both before asserting: an assertion may clobber the error slot.
  319. Classification c;
  320. c.resource = detail::is_accept_resource_error();
  321. c.transient = detail::is_accept_transient_error();
  322. return c;
  323. };
  324. #ifdef _WIN32
  325. const std::vector<int> resource_errors = {WSAEMFILE, WSAENOBUFS};
  326. const std::vector<int> transient_errors = {WSAEINTR, WSAEWOULDBLOCK,
  327. WSAECONNRESET, WSAECONNABORTED};
  328. const std::vector<int> fatal_errors = {WSAENOTSOCK, WSAEINVAL, WSAEOPNOTSUPP};
  329. #else
  330. const std::vector<int> resource_errors = {EMFILE, ENFILE, ENOBUFS, ENOMEM};
  331. const std::vector<int> transient_errors = {EINTR, EAGAIN, EWOULDBLOCK,
  332. ECONNABORTED};
  333. const std::vector<int> fatal_errors = {EBADF, EINVAL, ENOTSOCK};
  334. #endif
  335. for (auto err : resource_errors) {
  336. const auto c = classify(err);
  337. EXPECT_TRUE(c.resource) << "error " << err;
  338. EXPECT_FALSE(c.transient) << "error " << err;
  339. }
  340. for (auto err : transient_errors) {
  341. const auto c = classify(err);
  342. EXPECT_TRUE(c.transient) << "error " << err;
  343. EXPECT_FALSE(c.resource) << "error " << err;
  344. }
  345. for (auto err : fatal_errors) {
  346. const auto c = classify(err);
  347. EXPECT_FALSE(c.resource) << "error " << err;
  348. EXPECT_FALSE(c.transient) << "error " << err;
  349. }
  350. #ifdef _WIN32
  351. WSASetLastError(0);
  352. #else
  353. errno = 0;
  354. #endif
  355. }
  356. TEST(ClientTest, MoveConstructible) {
  357. EXPECT_FALSE(std::is_copy_constructible<Client>::value);
  358. EXPECT_TRUE(std::is_nothrow_move_constructible<Client>::value);
  359. }
  360. TEST(ClientTest, MoveAssignable) {
  361. EXPECT_FALSE(std::is_copy_assignable<Client>::value);
  362. EXPECT_TRUE(std::is_nothrow_move_assignable<Client>::value);
  363. }
  364. #ifdef _WIN32
  365. TEST(StartupTest, WSAStartup) {
  366. WSADATA wsaData;
  367. int ret = WSAStartup(0x0002, &wsaData);
  368. ASSERT_EQ(0, ret);
  369. }
  370. #endif
  371. TEST(DecodePathTest, PercentCharacter) {
  372. EXPECT_EQ(
  373. decode_path_component(
  374. R"(descrip=Gastos%20%C3%A1%C3%A9%C3%AD%C3%B3%C3%BA%C3%B1%C3%91%206)"),
  375. U8("descrip=Gastos áéíóúñÑ 6"));
  376. }
  377. TEST(DecodePathTest, PercentCharacterNUL) {
  378. string expected;
  379. expected.push_back('x');
  380. expected.push_back('\0');
  381. expected.push_back('x');
  382. EXPECT_EQ(decode_path_component("x%00x"), expected);
  383. }
  384. TEST(DecodePathTest, UnicodeEncoding) {
  385. // %u0041 = 'A' (1-byte UTF-8)
  386. EXPECT_EQ("A", decode_path_component("%u0041"));
  387. // %u00E9 = 'é' (2-byte UTF-8)
  388. EXPECT_EQ(U8("é"), decode_path_component("%u00E9"));
  389. // %u3042 = 'あ' (3-byte UTF-8)
  390. EXPECT_EQ(U8("あ"), decode_path_component("%u3042"));
  391. // %uFFFF = max 4-digit hex (3-byte UTF-8, must not overflow buff[4])
  392. EXPECT_FALSE(decode_path_component("%uFFFF").empty());
  393. // %uD800 = surrogate (invalid, silently dropped)
  394. EXPECT_EQ("", decode_path_component("%uD800"));
  395. }
  396. TEST(DecodeQueryTest, RejectsNonHexEscapes) {
  397. // A sign or whitespace inside the two-character escape window must not be
  398. // accepted as a valid percent-encoding; the sequence is passed through
  399. // literally, matching decode_uri_component / decode_path_component.
  400. EXPECT_EQ("%-1", decode_query_component("%-1", false));
  401. EXPECT_EQ("%-0", decode_query_component("%-0", false));
  402. EXPECT_EQ("%+5", decode_query_component("%+5", false));
  403. EXPECT_EQ("% 5", decode_query_component("% 5", false));
  404. // Well-formed escapes still decode.
  405. EXPECT_EQ("-", decode_query_component("%2D", false));
  406. EXPECT_EQ("A", decode_query_component("%41", false));
  407. }
  408. TEST(SanitizeFilenameTest, VariousPatterns) {
  409. // Path traversal
  410. EXPECT_EQ("passwd", httplib::sanitize_filename("../../../etc/passwd"));
  411. EXPECT_EQ("passwd", httplib::sanitize_filename("..\\..\\etc\\passwd"));
  412. EXPECT_EQ("file.txt", httplib::sanitize_filename("path/to\\..\\file.txt"));
  413. // Normal and edge cases
  414. EXPECT_EQ("photo.jpg", httplib::sanitize_filename("photo.jpg"));
  415. EXPECT_EQ("filename.txt",
  416. httplib::sanitize_filename("/path/to/filename.txt"));
  417. EXPECT_EQ(".gitignore", httplib::sanitize_filename(".gitignore"));
  418. EXPECT_EQ("", httplib::sanitize_filename(".."));
  419. EXPECT_EQ("", httplib::sanitize_filename(""));
  420. // Null bytes stripped
  421. EXPECT_EQ("safe.txt",
  422. httplib::sanitize_filename(std::string("safe\0.txt", 9)));
  423. // Whitespace-only rejected
  424. EXPECT_EQ("", httplib::sanitize_filename(" "));
  425. }
  426. // Forward declaration (see the base64_encode note below): split builds move the
  427. // definition into httplib.cc, so re-declaring it here lets the test link.
  428. namespace httplib {
  429. namespace detail {
  430. bool is_chunked_transfer_encoding(const Headers &headers);
  431. } // namespace detail
  432. } // namespace httplib
  433. TEST(ChunkedTransferEncodingTest, DetectsChunkedAsFinalCoding) {
  434. // Build a Headers with the given Transfer-Encoding lines (nullptr = none).
  435. auto make = [](std::initializer_list<const char *> lines) {
  436. Headers h;
  437. for (auto te : lines) {
  438. if (te) { h.emplace("Transfer-Encoding", te); }
  439. }
  440. return h;
  441. };
  442. // Sole coding, matched case-insensitively.
  443. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"chunked"})));
  444. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"Chunked"})));
  445. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"CHUNKED"})));
  446. // RFC 9112 6.1: chunked as the final coding of a list still frames the body.
  447. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, chunked"})));
  448. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip,chunked"})));
  449. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip, Chunked "})));
  450. // Single line: chunked absent, or not the final coding -> not chunk-framed.
  451. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip"})));
  452. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked, gzip"})));
  453. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({""})));
  454. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({nullptr})));
  455. // RFC 9110 5.3: multiple Transfer-Encoding lines combine, in the order they
  456. // were received, into one list. Headers preserves that order, so the answer
  457. // is decided by the last coding of the last line and the order the lines
  458. // arrived in is significant.
  459. EXPECT_TRUE(detail::is_chunked_transfer_encoding(make({"gzip", "chunked"})));
  460. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", "gzip"})));
  461. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"gzip", "deflate"})));
  462. // The split can fall anywhere in the list.
  463. EXPECT_TRUE(
  464. detail::is_chunked_transfer_encoding(make({"deflate", "gzip, chunked"})));
  465. EXPECT_FALSE(
  466. detail::is_chunked_transfer_encoding(make({"gzip, chunked", "deflate"})));
  467. // A trailing line naming no coding leaves the list ending in nothing, so it
  468. // must not inherit the chunked from the line before it.
  469. EXPECT_FALSE(detail::is_chunked_transfer_encoding(make({"chunked", ""})));
  470. }
  471. // Forward declaration: in split builds split.py strips `inline` and moves the
  472. // definition into httplib.cc, so detail::base64_encode is not visible from the
  473. // public httplib.h. Re-declaring it here lets the tests link against the symbol
  474. // in both header-only and split builds.
  475. namespace httplib {
  476. namespace detail {
  477. std::string base64_encode(const std::string &in);
  478. } // namespace detail
  479. } // namespace httplib
  480. TEST(Base64EncodeTest, KnownAnswers) {
  481. // RFC 4648 test vectors. Inputs of four bytes or more exercise the round
  482. // where the accumulator's top bit is already set before the next shift.
  483. EXPECT_EQ("", detail::base64_encode(""));
  484. EXPECT_EQ("Zg==", detail::base64_encode("f"));
  485. EXPECT_EQ("Zm8=", detail::base64_encode("fo"));
  486. EXPECT_EQ("Zm9v", detail::base64_encode("foo"));
  487. EXPECT_EQ("Zm9vYg==", detail::base64_encode("foob"));
  488. EXPECT_EQ("Zm9vYmE=", detail::base64_encode("fooba"));
  489. EXPECT_EQ("Zm9vYmFy", detail::base64_encode("foobar"));
  490. // High bytes keep the top bit set across several rounds.
  491. EXPECT_EQ("AAECA//+wIB/", detail::base64_encode(std::string(
  492. "\x00\x01\x02\x03\xff\xfe\xc0\x80\x7f", 9)));
  493. }
  494. TEST(EncodeQueryParamTest, ParseUnescapedChararactersTest) {
  495. string unescapedCharacters = "-_.!~*'()";
  496. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  497. }
  498. TEST(EncodeQueryParamTest, ParseReservedCharactersTest) {
  499. string reservedCharacters = ";,/?:@&=+$";
  500. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  501. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  502. }
  503. TEST(ClientQueryOrder, PreserveOrder) {
  504. // This test reproduces Issue #2259: client may reorder query parameters
  505. // when sending a GET request. The expected behavior is that the client
  506. // preserves the original query string order when the caller supplied it
  507. // as part of the path.
  508. Server svr;
  509. svr.Get("/", [&](const Request &req, Response &res) {
  510. // Echo back the raw target so the test can assert ordering
  511. res.set_content(req.target, "text/plain");
  512. });
  513. std::thread t{[&] { svr.listen(HOST, PORT); }};
  514. auto se = detail::scope_exit([&] {
  515. svr.stop();
  516. t.join();
  517. ASSERT_FALSE(svr.is_running());
  518. });
  519. svr.wait_until_ready();
  520. Client cli(HOST, PORT);
  521. ASSERT_TRUE(cli.is_valid());
  522. const std::string original = "/?z=1&y=2&x=3&c=7&b=8&a=9";
  523. auto res = cli.Get(original);
  524. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  525. // Expect the echoed target to exactly match the original path (order
  526. // preserved)
  527. EXPECT_EQ(res->body, original);
  528. }
  529. TEST(EncodeQueryParamTest, TestUTF8Characters) {
  530. string chineseCharacters = U8("中国語");
  531. string russianCharacters = U8("дом");
  532. string brazilianCharacters = U8("óculos");
  533. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  534. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  535. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  536. "%D0%B4%D0%BE%D0%BC");
  537. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  538. }
  539. TEST(EncodeUriComponentTest, ParseUnescapedChararactersTest) {
  540. string unescapedCharacters = "-_.!~*'()";
  541. EXPECT_EQ(httplib::encode_uri_component(unescapedCharacters), "-_.!~*'()");
  542. }
  543. TEST(EncodeUriComponentTest, ParseReservedCharactersTest) {
  544. string reservedCharacters = ";,/?:@&=+$";
  545. EXPECT_EQ(httplib::encode_uri_component(reservedCharacters),
  546. "%3B%2C%2F%3F%3A%40%26%3D%2B%24");
  547. }
  548. TEST(EncodeUriComponentTest, TestUTF8Characters) {
  549. string chineseCharacters = U8("中国語");
  550. string russianCharacters = U8("дом");
  551. string brazilianCharacters = U8("óculos");
  552. EXPECT_EQ(httplib::encode_uri_component(chineseCharacters),
  553. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  554. EXPECT_EQ(httplib::encode_uri_component(russianCharacters),
  555. "%D0%B4%D0%BE%D0%BC");
  556. EXPECT_EQ(httplib::encode_uri_component(brazilianCharacters), "%C3%B3culos");
  557. }
  558. TEST(EncodeUriComponentTest, TestPathComponentEncoding) {
  559. // Issue #2082 use case: encoding path component with ampersand
  560. string pathWithAmpersand = "Piri Tommy Villiers - on & on";
  561. EXPECT_EQ(httplib::encode_uri_component(pathWithAmpersand),
  562. "Piri%20Tommy%20Villiers%20-%20on%20%26%20on");
  563. }
  564. TEST(EncodeUriTest, ParseUnescapedChararactersTest) {
  565. string unescapedCharacters = "-_.!~*'()";
  566. EXPECT_EQ(httplib::encode_uri(unescapedCharacters), "-_.!~*'()");
  567. }
  568. TEST(EncodeUriTest, ParseReservedCharactersTest) {
  569. string reservedCharacters = ";,/?:@&=+$#";
  570. EXPECT_EQ(httplib::encode_uri(reservedCharacters), ";,/?:@&=+$#");
  571. }
  572. TEST(EncodeUriTest, TestUTF8Characters) {
  573. string chineseCharacters = U8("中国語");
  574. string russianCharacters = U8("дом");
  575. string brazilianCharacters = U8("óculos");
  576. EXPECT_EQ(httplib::encode_uri(chineseCharacters),
  577. "%E4%B8%AD%E5%9B%BD%E8%AA%9E");
  578. EXPECT_EQ(httplib::encode_uri(russianCharacters), "%D0%B4%D0%BE%D0%BC");
  579. EXPECT_EQ(httplib::encode_uri(brazilianCharacters), "%C3%B3culos");
  580. }
  581. TEST(EncodeUriTest, TestCompleteUri) {
  582. string uri =
  583. "https://example.com/path/to/resource?query=value&param=test#fragment";
  584. EXPECT_EQ(
  585. httplib::encode_uri(uri),
  586. "https://example.com/path/to/resource?query=value&param=test#fragment");
  587. }
  588. TEST(EncodeUriTest, TestUriWithSpacesAndSpecialChars) {
  589. string uri =
  590. "https://example.com/path with spaces/file name.html?q=hello world";
  591. EXPECT_EQ(httplib::encode_uri(uri),
  592. "https://example.com/path%20with%20spaces/"
  593. "file%20name.html?q=hello%20world");
  594. }
  595. TEST(DecodeUriComponentTest, ParseEncodedChararactersTest) {
  596. string encodedString = "%3B%2C%2F%3F%3A%40%26%3D%2B%24";
  597. EXPECT_EQ(httplib::decode_uri_component(encodedString), ";,/?:@&=+$");
  598. }
  599. TEST(DecodeUriComponentTest, ParseUnescapedChararactersTest) {
  600. string unescapedCharacters = "-_.!~*'()";
  601. EXPECT_EQ(httplib::decode_uri_component(unescapedCharacters), "-_.!~*'()");
  602. }
  603. TEST(DecodeUriComponentTest, TestUTF8Characters) {
  604. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  605. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  606. string encodedBrazilian = "%C3%B3culos";
  607. EXPECT_EQ(httplib::decode_uri_component(encodedChinese), U8("中国語"));
  608. EXPECT_EQ(httplib::decode_uri_component(encodedRussian), U8("дом"));
  609. EXPECT_EQ(httplib::decode_uri_component(encodedBrazilian), U8("óculos"));
  610. }
  611. TEST(DecodeUriComponentTest, TestPathComponentDecoding) {
  612. string encodedPath = "Piri%20Tommy%20Villiers%20-%20on%20%26%20on";
  613. EXPECT_EQ(httplib::decode_uri_component(encodedPath),
  614. "Piri Tommy Villiers - on & on");
  615. }
  616. TEST(DecodeUriTest, ParseEncodedChararactersTest) {
  617. string encodedString = "%20%22%3C%3E%5C%5E%60%7B%7D%7C";
  618. EXPECT_EQ(httplib::decode_uri(encodedString), " \"<>\\^`{}|");
  619. }
  620. TEST(DecodeUriTest, ParseUnescapedChararactersTest) {
  621. string unescapedCharacters = "-_.!~*'();,/?:@&=+$#";
  622. EXPECT_EQ(httplib::decode_uri(unescapedCharacters), "-_.!~*'();,/?:@&=+$#");
  623. }
  624. TEST(DecodeUriTest, TestUTF8Characters) {
  625. string encodedChinese = "%E4%B8%AD%E5%9B%BD%E8%AA%9E";
  626. string encodedRussian = "%D0%B4%D0%BE%D0%BC";
  627. string encodedBrazilian = "%C3%B3culos";
  628. EXPECT_EQ(httplib::decode_uri(encodedChinese), U8("中国語"));
  629. EXPECT_EQ(httplib::decode_uri(encodedRussian), U8("дом"));
  630. EXPECT_EQ(httplib::decode_uri(encodedBrazilian), U8("óculos"));
  631. }
  632. TEST(DecodeUriTest, TestCompleteUri) {
  633. string encodedUri = "https://example.com/path%20with%20spaces/"
  634. "file%20name.html?q=hello%20world";
  635. EXPECT_EQ(
  636. httplib::decode_uri(encodedUri),
  637. "https://example.com/path with spaces/file name.html?q=hello world");
  638. }
  639. TEST(DecodeUriTest, TestRoundTripWithEncodeUri) {
  640. string original =
  641. "https://example.com/path with spaces/file name.html?q=hello world";
  642. string encoded = httplib::encode_uri(original);
  643. string decoded = httplib::decode_uri(encoded);
  644. EXPECT_EQ(decoded, original);
  645. }
  646. TEST(DecodeUriTest, KeepsReservedCharacterEscapes) {
  647. // decode_uri is the inverse of encode_uri: an escaped reserved character
  648. // stays encoded so it is not promoted into a real delimiter, while
  649. // non-reserved escapes still decode (like JS decodeURI).
  650. EXPECT_EQ(httplib::decode_uri("%2F"), "%2F");
  651. EXPECT_EQ(httplib::decode_uri("%23"), "%23");
  652. EXPECT_EQ(httplib::decode_uri("%3F%3A%40%26%3D%2B%24%2C%3B"),
  653. "%3F%3A%40%26%3D%2B%24%2C%3B");
  654. EXPECT_EQ(httplib::decode_uri("%2D"), "-");
  655. EXPECT_EQ(httplib::decode_uri("%20"), " ");
  656. EXPECT_EQ(httplib::decode_uri("http://example.com/a%2Fb"),
  657. "http://example.com/a%2Fb");
  658. // decode_uri_component still decodes the reserved character.
  659. EXPECT_EQ(httplib::decode_uri_component("%2F"), "/");
  660. }
  661. TEST(DecodeUriComponentTest, TestRoundTripWithEncodeUriComponent) {
  662. string original = "Piri Tommy Villiers - on & on";
  663. string encoded = httplib::encode_uri_component(original);
  664. string decoded = httplib::decode_uri_component(encoded);
  665. EXPECT_EQ(decoded, original);
  666. }
  667. TEST(TrimTests, TrimStringTests) {
  668. EXPECT_EQ("abc", detail::trim_copy("abc"));
  669. EXPECT_EQ("abc", detail::trim_copy(" abc "));
  670. EXPECT_TRUE(detail::trim_copy("").empty());
  671. }
  672. TEST(AsciiTest, LocaleIndependentClassification) {
  673. // detail::is_ascii_digit/alpha/alnum replace the <cctype> classifiers,
  674. // which consult the global C locale: std::isalnum(0xC5) can return true
  675. // once an embedder calls setlocale() (observed on macOS). The is_ascii_*
  676. // helpers must classify every byte by the ASCII grammar alone.
  677. for (int i = 0; i < 256; i++) {
  678. auto c = static_cast<char>(i);
  679. auto is_digit = i >= '0' && i <= '9';
  680. auto is_upper = i >= 'A' && i <= 'Z';
  681. auto is_lower = i >= 'a' && i <= 'z';
  682. EXPECT_EQ(is_digit, detail::is_ascii_digit(c)) << "byte " << i;
  683. EXPECT_EQ(is_upper || is_lower, detail::is_ascii_alpha(c)) << "byte " << i;
  684. EXPECT_EQ(is_digit || is_upper || is_lower, detail::is_ascii_alnum(c))
  685. << "byte " << i;
  686. }
  687. // Regression check for the reported byte: 0xC5 is not alphanumeric.
  688. EXPECT_FALSE(detail::is_ascii_alnum(static_cast<char>(0xC5)));
  689. // Non-ASCII bytes must be percent-encoded, never passed through as
  690. // alphanumeric.
  691. EXPECT_EQ("%C5", httplib::encode_uri_component("\xC5"));
  692. }
  693. TEST(FromCharsTest, Double) {
  694. // detail::from_chars(double) recognizes exactly the HTTP quality-value
  695. // grammar (RFC 9110 12.4.2): a non-negative decimal "1*DIGIT [ '.' *DIGIT ]"
  696. // with no sign, exponent, or "inf"/"nan", parsed locale-independently.
  697. auto parse = [](const std::string &s, double &v) {
  698. return detail::from_chars(s.data(), s.data() + s.size(), v);
  699. };
  700. double v = -1.0;
  701. // Representative quality values.
  702. EXPECT_EQ(parse("0", v).ec, std::errc{});
  703. EXPECT_DOUBLE_EQ(v, 0.0);
  704. EXPECT_EQ(parse("1", v).ec, std::errc{});
  705. EXPECT_DOUBLE_EQ(v, 1.0);
  706. EXPECT_EQ(parse("0.8", v).ec, std::errc{});
  707. EXPECT_DOUBLE_EQ(v, 0.8);
  708. EXPECT_EQ(parse("0.001", v).ec, std::errc{});
  709. EXPECT_DOUBLE_EQ(v, 0.001);
  710. EXPECT_EQ(parse("1.000", v).ec, std::errc{});
  711. EXPECT_DOUBLE_EQ(v, 1.0);
  712. // A missing integer or fractional part is tolerated.
  713. EXPECT_EQ(parse(".5", v).ec, std::errc{});
  714. EXPECT_DOUBLE_EQ(v, 0.5);
  715. EXPECT_EQ(parse("5.", v).ec, std::errc{});
  716. EXPECT_DOUBLE_EQ(v, 5.0);
  717. // Values outside [0, 1] still parse; the caller range-checks them.
  718. EXPECT_EQ(parse("123.456", v).ec, std::errc{});
  719. EXPECT_DOUBLE_EQ(v, 123.456);
  720. // Stops at the first byte that is not part of the number and reports where.
  721. std::string trailing = "0.9, text/html";
  722. auto r = parse(trailing, v);
  723. EXPECT_EQ(r.ec, std::errc{});
  724. EXPECT_DOUBLE_EQ(v, 0.9);
  725. EXPECT_EQ(*r.ptr, ',');
  726. // Sign and exponent are NOT part of the grammar: '+'/'-' are rejected
  727. // outright, and an 'e'/'E' simply ends the number.
  728. EXPECT_EQ(parse("-3.25", v).ec, std::errc::invalid_argument);
  729. EXPECT_EQ(parse("+2.5", v).ec, std::errc::invalid_argument);
  730. std::string exp_input = "1.5e3";
  731. r = parse(exp_input, v);
  732. EXPECT_EQ(r.ec, std::errc{});
  733. EXPECT_DOUBLE_EQ(v, 1.5);
  734. EXPECT_EQ(*r.ptr, 'e');
  735. // Invalid inputs.
  736. EXPECT_EQ(parse("", v).ec, std::errc::invalid_argument);
  737. EXPECT_EQ(parse(".", v).ec, std::errc::invalid_argument);
  738. EXPECT_EQ(parse("abc", v).ec, std::errc::invalid_argument);
  739. EXPECT_EQ(parse("nan", v).ec, std::errc::invalid_argument);
  740. EXPECT_EQ(parse("inf", v).ec, std::errc::invalid_argument);
  741. // Pathological but well-formed inputs must stay bounded (no overflow, no
  742. // out-of-bounds table access) and stay within [0, 1] for the caller.
  743. EXPECT_EQ(parse(std::string("0.") + std::string(500, '0'), v).ec,
  744. std::errc{});
  745. EXPECT_DOUBLE_EQ(v, 0.0);
  746. EXPECT_EQ(parse(std::string("0.") + std::string(500, '9'), v).ec,
  747. std::errc{});
  748. EXPECT_GE(v, 0.0);
  749. EXPECT_LE(v, 1.0);
  750. EXPECT_EQ(parse(std::string(500, '9'), v).ec, std::errc{});
  751. EXPECT_GT(v, 1.0); // huge integer: finite, > 1, so the caller rejects it
  752. }
  753. TEST(ParseAcceptHeaderTest, BasicAcceptParsing) {
  754. // Simple case without quality values
  755. std::vector<std::string> result1;
  756. EXPECT_TRUE(detail::parse_accept_header(
  757. "text/html,application/json,text/plain", result1));
  758. EXPECT_EQ(result1.size(), 3U);
  759. EXPECT_EQ(result1[0], "text/html");
  760. EXPECT_EQ(result1[1], "application/json");
  761. EXPECT_EQ(result1[2], "text/plain");
  762. // With quality values
  763. std::vector<std::string> result2;
  764. EXPECT_TRUE(detail::parse_accept_header(
  765. "text/html;q=0.9,application/json;q=1.0,text/plain;q=0.8", result2));
  766. EXPECT_EQ(result2.size(), 3U);
  767. EXPECT_EQ(result2[0], "application/json"); // highest q value
  768. EXPECT_EQ(result2[1], "text/html");
  769. EXPECT_EQ(result2[2], "text/plain"); // lowest q value
  770. }
  771. TEST(ParseAcceptHeaderTest, MixedQualityValues) {
  772. // Mixed with and without quality values
  773. std::vector<std::string> result;
  774. EXPECT_TRUE(detail::parse_accept_header(
  775. "text/html,application/json;q=0.5,text/plain;q=0.8", result));
  776. EXPECT_EQ(result.size(), 3U);
  777. EXPECT_EQ(result[0], "text/html"); // no q value means 1.0
  778. EXPECT_EQ(result[1], "text/plain"); // q=0.8
  779. EXPECT_EQ(result[2], "application/json"); // q=0.5
  780. }
  781. TEST(ParseAcceptHeaderTest, EdgeCases) {
  782. // Empty header
  783. std::vector<std::string> empty_result;
  784. EXPECT_TRUE(detail::parse_accept_header("", empty_result));
  785. EXPECT_TRUE(empty_result.empty());
  786. // Single type
  787. std::vector<std::string> single_result;
  788. EXPECT_TRUE(detail::parse_accept_header("application/json", single_result));
  789. EXPECT_EQ(single_result.size(), 1U);
  790. EXPECT_EQ(single_result[0], "application/json");
  791. // Wildcard types
  792. std::vector<std::string> wildcard_result;
  793. EXPECT_TRUE(detail::parse_accept_header(
  794. "text/*;q=0.5,*/*;q=0.1,application/json", wildcard_result));
  795. EXPECT_EQ(wildcard_result.size(), 3U);
  796. EXPECT_EQ(wildcard_result[0], "application/json");
  797. EXPECT_EQ(wildcard_result[1], "text/*");
  798. EXPECT_EQ(wildcard_result[2], "*/*");
  799. }
  800. TEST(ParseAcceptHeaderTest, RealWorldExamples) {
  801. // Common browser Accept header
  802. std::vector<std::string> browser_result;
  803. EXPECT_TRUE(
  804. detail::parse_accept_header("text/html,application/xhtml+xml,application/"
  805. "xml;q=0.9,image/webp,image/apng,*/*;q=0.8",
  806. browser_result));
  807. EXPECT_EQ(browser_result.size(), 6U);
  808. EXPECT_EQ(browser_result[0], "text/html"); // q=1.0 (default)
  809. EXPECT_EQ(browser_result[1], "application/xhtml+xml"); // q=1.0 (default)
  810. EXPECT_EQ(browser_result[2], "image/webp"); // q=1.0 (default)
  811. EXPECT_EQ(browser_result[3], "image/apng"); // q=1.0 (default)
  812. EXPECT_EQ(browser_result[4], "application/xml"); // q=0.9
  813. EXPECT_EQ(browser_result[5], "*/*"); // q=0.8
  814. // API client header
  815. std::vector<std::string> api_result;
  816. EXPECT_TRUE(detail::parse_accept_header(
  817. "application/json;q=0.9,application/xml;q=0.8,text/plain;q=0.1",
  818. api_result));
  819. EXPECT_EQ(api_result.size(), 3U);
  820. EXPECT_EQ(api_result[0], "application/json");
  821. EXPECT_EQ(api_result[1], "application/xml");
  822. EXPECT_EQ(api_result[2], "text/plain");
  823. }
  824. TEST(ParseAcceptHeaderTest, SpecialCases) {
  825. // Quality value with 3 decimal places
  826. std::vector<std::string> decimal_result;
  827. EXPECT_TRUE(detail::parse_accept_header(
  828. "text/html;q=0.123,application/json;q=0.456", decimal_result));
  829. EXPECT_EQ(decimal_result.size(), 2U);
  830. EXPECT_EQ(decimal_result[0], "application/json"); // Higher q value
  831. EXPECT_EQ(decimal_result[1], "text/html");
  832. // Zero quality (should still be included but with lowest priority)
  833. std::vector<std::string> zero_q_result;
  834. EXPECT_TRUE(detail::parse_accept_header("text/html;q=0,application/json;q=1",
  835. zero_q_result));
  836. EXPECT_EQ(zero_q_result.size(), 2U);
  837. EXPECT_EQ(zero_q_result[0], "application/json"); // q=1
  838. EXPECT_EQ(zero_q_result[1], "text/html"); // q=0
  839. // No spaces around commas
  840. std::vector<std::string> no_space_result;
  841. EXPECT_TRUE(detail::parse_accept_header(
  842. "text/html;q=0.9,application/json;q=0.8,text/plain;q=0.7",
  843. no_space_result));
  844. EXPECT_EQ(no_space_result.size(), 3U);
  845. EXPECT_EQ(no_space_result[0], "text/html");
  846. EXPECT_EQ(no_space_result[1], "application/json");
  847. EXPECT_EQ(no_space_result[2], "text/plain");
  848. }
  849. TEST(ParseAcceptHeaderTest, QualityValueLocaleIndependence) {
  850. // Quality values always use '.' as the decimal separator, so parsing must
  851. // not depend on the process locale. An embedding application may have
  852. // switched to a locale that uses ',' via setlocale(LC_ALL, "").
  853. const char *cur = std::setlocale(LC_NUMERIC, nullptr);
  854. std::string saved = cur ? cur : "C";
  855. const char *comma_locales[] = {"de_DE.UTF-8", "de_DE.utf8", "nl_NL.UTF-8",
  856. "fr_FR.UTF-8"};
  857. bool switched = false;
  858. for (const auto loc : comma_locales) {
  859. if (std::setlocale(LC_NUMERIC, loc) != nullptr &&
  860. std::localeconv()->decimal_point[0] == ',') {
  861. switched = true;
  862. break;
  863. }
  864. }
  865. if (!switched) {
  866. std::setlocale(LC_NUMERIC, saved.c_str());
  867. GTEST_SKIP() << "no comma-decimal locale available on this host";
  868. }
  869. // The higher-weighted type appears later in the list, so a correct parse
  870. // must reorder it ahead of the earlier, lower-weighted one. A locale-
  871. // sensitive parse reads both weights as 0 and leaves the original order.
  872. std::vector<std::string> result;
  873. EXPECT_TRUE(detail::parse_accept_header(
  874. "application/json;q=0.1,text/html;q=0.9", result));
  875. ASSERT_EQ(result.size(), 2U);
  876. EXPECT_EQ(result[0], "text/html");
  877. EXPECT_EQ(result[1], "application/json");
  878. std::setlocale(LC_NUMERIC, saved.c_str());
  879. }
  880. TEST(ParseAcceptHeaderTest, InvalidCases) {
  881. std::vector<std::string> result;
  882. // Invalid quality value (> 1.0)
  883. EXPECT_FALSE(
  884. detail::parse_accept_header("text/html;q=1.5,application/json", result));
  885. // Invalid quality value (< 0.0)
  886. EXPECT_FALSE(
  887. detail::parse_accept_header("text/html;q=-0.1,application/json", result));
  888. // Invalid quality value (not a number)
  889. EXPECT_FALSE(detail::parse_accept_header(
  890. "text/html;q=invalid,application/json", result));
  891. // A valid numeric prefix does not make the entire quality value valid.
  892. EXPECT_FALSE(detail::parse_accept_header(
  893. "text/html;q=0.5junk,application/json", result));
  894. // Empty quality value
  895. EXPECT_FALSE(
  896. detail::parse_accept_header("text/html;q=,application/json", result));
  897. // Invalid media type format (no slash and not wildcard)
  898. EXPECT_FALSE(
  899. detail::parse_accept_header("invalidtype,application/json", result));
  900. // Valid cases should still work
  901. EXPECT_TRUE(detail::parse_accept_header("*/*", result));
  902. EXPECT_EQ(result.size(), 1U);
  903. EXPECT_EQ(result[0], "*/*");
  904. EXPECT_TRUE(detail::parse_accept_header("*", result));
  905. EXPECT_EQ(result.size(), 1U);
  906. EXPECT_EQ(result[0], "*");
  907. EXPECT_TRUE(detail::parse_accept_header("text/*", result));
  908. EXPECT_EQ(result.size(), 1U);
  909. EXPECT_EQ(result[0], "text/*");
  910. }
  911. // RFC 9110 Section 5.6.1.2: a recipient has to parse and ignore empty list
  912. // elements, so a leading, trailing or doubled comma is a legal Accept value
  913. // and must not be answered with 400 Bad Request.
  914. TEST(ParseAcceptHeaderTest, EmptyListElementsAreIgnored) {
  915. struct {
  916. const char *value;
  917. std::vector<std::string> expected;
  918. } cases[] = {
  919. {",application/json", {"application/json"}},
  920. {"text/html,", {"text/html"}},
  921. {"text/html,,*/*", {"text/html", "*/*"}},
  922. // An empty element may be spelled with whitespace in it
  923. {"text/html, , application/json", {"text/html", "application/json"}},
  924. // Nothing but empty elements is an empty list, which means the same
  925. // thing as no Accept header at all
  926. {",,,", {}},
  927. // Quality values still apply across ignored empty elements
  928. {",text/html;q=0.5,,application/json", {"application/json", "text/html"}},
  929. };
  930. for (const auto &c : cases) {
  931. std::vector<std::string> result;
  932. EXPECT_TRUE(detail::parse_accept_header(c.value, result))
  933. << "value: " << c.value;
  934. EXPECT_EQ(c.expected, result) << "value: " << c.value;
  935. }
  936. // An invalid entry is still rejected when empty elements surround it
  937. std::vector<std::string> result;
  938. EXPECT_FALSE(detail::parse_accept_header(",invalidtype,", result));
  939. }
  940. TEST(ParseAcceptHeaderTest, ContentTypesPopulatedAndInvalidHeaderHandling) {
  941. Server svr;
  942. svr.Get("/accept_ok", [&](const Request &req, Response &res) {
  943. EXPECT_EQ(req.accept_content_types.size(), 3U);
  944. EXPECT_EQ(req.accept_content_types[0], "application/json");
  945. EXPECT_EQ(req.accept_content_types[1], "text/html");
  946. EXPECT_EQ(req.accept_content_types[2], "*/*");
  947. res.set_content("ok", "text/plain");
  948. });
  949. svr.Get("/accept_bad_request", [&](const Request & /*req*/, Response &res) {
  950. EXPECT_TRUE(false);
  951. res.set_content("bad request", "text/plain");
  952. });
  953. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  954. auto se = detail::scope_exit([&] {
  955. svr.stop();
  956. listen_thread.join();
  957. ASSERT_FALSE(svr.is_running());
  958. });
  959. svr.wait_until_ready();
  960. Client cli("localhost", PORT);
  961. {
  962. auto res = cli.Get(
  963. "/accept_ok",
  964. Headers{{"Accept", "application/json, text/html;q=0.8, */*;q=0.1"}});
  965. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  966. EXPECT_EQ(StatusCode::OK_200, res->status);
  967. }
  968. {
  969. auto res = cli.Get("/accept_bad_request",
  970. Headers{{"Accept", "text/html;q=abc,application/json"}});
  971. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  972. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  973. }
  974. }
  975. TEST(ServerStartHandlerTest, CalledOnceWhenReady) {
  976. Server svr;
  977. svr.Get("/", [](const Request & /*req*/, Response &res) {
  978. res.set_content("ok", "text/plain");
  979. });
  980. std::atomic<int> start_count{0};
  981. std::atomic<bool> running_when_called{false};
  982. svr.set_start_handler([&]() {
  983. running_when_called = svr.is_running();
  984. start_count++;
  985. });
  986. auto port = svr.bind_to_any_port(HOST);
  987. std::thread t([&]() { svr.listen_after_bind(); });
  988. auto se = detail::scope_exit([&] {
  989. svr.stop();
  990. t.join();
  991. ASSERT_FALSE(svr.is_running());
  992. });
  993. svr.wait_until_ready();
  994. // A successful request proves the accept loop is running, which the start
  995. // handler precedes; so by now the handler must have run exactly once.
  996. Client cli(HOST, port);
  997. cli.set_connection_timeout(std::chrono::seconds(5));
  998. auto res = cli.Get("/");
  999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1000. EXPECT_EQ(StatusCode::OK_200, res->status);
  1001. EXPECT_EQ(1, start_count.load());
  1002. EXPECT_TRUE(running_when_called.load());
  1003. }
  1004. TEST(DivideTest, DivideStringTests) {
  1005. auto divide = [](const std::string &str, char d) {
  1006. std::string lhs;
  1007. std::string rhs;
  1008. detail::divide(str, d,
  1009. [&](const char *lhs_data, std::size_t lhs_size,
  1010. const char *rhs_data, std::size_t rhs_size) {
  1011. lhs.assign(lhs_data, lhs_size);
  1012. rhs.assign(rhs_data, rhs_size);
  1013. });
  1014. return std::make_pair(std::move(lhs), std::move(rhs));
  1015. };
  1016. {
  1017. const auto res = divide("", '=');
  1018. EXPECT_EQ(res.first, "");
  1019. EXPECT_EQ(res.second, "");
  1020. }
  1021. {
  1022. const auto res = divide("=", '=');
  1023. EXPECT_EQ(res.first, "");
  1024. EXPECT_EQ(res.second, "");
  1025. }
  1026. {
  1027. const auto res = divide(" ", '=');
  1028. EXPECT_EQ(res.first, " ");
  1029. EXPECT_EQ(res.second, "");
  1030. }
  1031. {
  1032. const auto res = divide("a", '=');
  1033. EXPECT_EQ(res.first, "a");
  1034. EXPECT_EQ(res.second, "");
  1035. }
  1036. {
  1037. const auto res = divide("a=", '=');
  1038. EXPECT_EQ(res.first, "a");
  1039. EXPECT_EQ(res.second, "");
  1040. }
  1041. {
  1042. const auto res = divide("=b", '=');
  1043. EXPECT_EQ(res.first, "");
  1044. EXPECT_EQ(res.second, "b");
  1045. }
  1046. {
  1047. const auto res = divide("a=b", '=');
  1048. EXPECT_EQ(res.first, "a");
  1049. EXPECT_EQ(res.second, "b");
  1050. }
  1051. {
  1052. const auto res = divide("a=b=", '=');
  1053. EXPECT_EQ(res.first, "a");
  1054. EXPECT_EQ(res.second, "b=");
  1055. }
  1056. {
  1057. const auto res = divide("a=b=c", '=');
  1058. EXPECT_EQ(res.first, "a");
  1059. EXPECT_EQ(res.second, "b=c");
  1060. }
  1061. }
  1062. TEST(SplitTest, ParseQueryString) {
  1063. string s = "key1=val1&key2=val2&key3=val3";
  1064. Params dic;
  1065. detail::split(s.c_str(), s.c_str() + s.size(), '&',
  1066. [&](const char *b, const char *e) {
  1067. string key, val;
  1068. detail::split(b, e, '=', [&](const char *b2, const char *e2) {
  1069. if (key.empty()) {
  1070. key.assign(b2, e2);
  1071. } else {
  1072. val.assign(b2, e2);
  1073. }
  1074. });
  1075. dic.emplace(key, val);
  1076. });
  1077. EXPECT_EQ("val1", dic.find("key1")->second);
  1078. EXPECT_EQ("val2", dic.find("key2")->second);
  1079. EXPECT_EQ("val3", dic.find("key3")->second);
  1080. }
  1081. TEST(SplitTest, ParseInvalidQueryTests) {
  1082. {
  1083. string s = " ";
  1084. Params dict;
  1085. detail::parse_query_text(s, dict);
  1086. EXPECT_TRUE(dict.empty());
  1087. }
  1088. {
  1089. string s = " = =";
  1090. Params dict;
  1091. detail::parse_query_text(s, dict);
  1092. EXPECT_TRUE(dict.empty());
  1093. }
  1094. }
  1095. TEST(ParseQueryTest, ParseQueryString) {
  1096. {
  1097. std::string s = "key1=val1&key2=val2&key3=val3";
  1098. Params dic;
  1099. detail::parse_query_text(s, dic);
  1100. EXPECT_EQ("val1", dic.find("key1")->second);
  1101. EXPECT_EQ("val2", dic.find("key2")->second);
  1102. EXPECT_EQ("val3", dic.find("key3")->second);
  1103. }
  1104. {
  1105. std::string s = "key1&key2=val1&key3=val1=val2&key4=val1=val2=val3";
  1106. Params dic;
  1107. detail::parse_query_text(s, dic);
  1108. EXPECT_EQ("", dic.find("key1")->second);
  1109. EXPECT_EQ("val1", dic.find("key2")->second);
  1110. EXPECT_EQ("val1=val2", dic.find("key3")->second);
  1111. EXPECT_EQ("val1=val2=val3", dic.find("key4")->second);
  1112. }
  1113. }
  1114. TEST(ParamsToQueryTest, ConvertParamsToQuery) {
  1115. Params dic;
  1116. EXPECT_EQ(detail::params_to_query_str(dic), "");
  1117. dic.emplace("key1", "val1");
  1118. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1");
  1119. dic.emplace("key2", "val2");
  1120. dic.emplace("key3", "val3");
  1121. EXPECT_EQ(detail::params_to_query_str(dic), "key1=val1&key2=val2&key3=val3");
  1122. }
  1123. // Joins every entry of a Headers or Params into "key=value " so a whole
  1124. // traversal can be compared in one assertion. Both are instantiations of the
  1125. // same insertion-ordered container, so one helper serves both.
  1126. template <typename Map> static std::string entries_to_string(const Map &m) {
  1127. std::string s;
  1128. for (const auto &entry : m) {
  1129. s += entry.first + "=" + entry.second + " ";
  1130. }
  1131. return s;
  1132. }
  1133. TEST(ParamsOrderTest, QueryIsBuiltInInsertionOrderNotSorted) {
  1134. // Params used to be a std::multimap, which sorted by name and handed the
  1135. // caller's query back alphabetised. A client signing its query string could
  1136. // not reproduce the order it asked for.
  1137. Params dic;
  1138. dic.emplace("zulu", "1");
  1139. dic.emplace("alpha", "2");
  1140. dic.emplace("mike", "3");
  1141. EXPECT_EQ("zulu=1&alpha=2&mike=3", detail::params_to_query_str(dic));
  1142. EXPECT_EQ("/p?zulu=1&alpha=2&mike=3", append_query_params("/p", dic));
  1143. }
  1144. TEST(ParamsOrderTest, ParsingKeepsTheOrderReceived) {
  1145. Params dic;
  1146. detail::parse_query_text("zulu=1&alpha=2&mike=3", dic);
  1147. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", entries_to_string(dic));
  1148. }
  1149. TEST(ParamsOrderTest, RepeatedNamesKeepTheirOrder) {
  1150. Request req;
  1151. detail::parse_query_text("tag=first&other=x&tag=second&tag=third",
  1152. req.params);
  1153. EXPECT_EQ(3U, req.get_param_value_count("tag"));
  1154. EXPECT_EQ("first", req.get_param_value("tag"));
  1155. EXPECT_EQ("first", req.get_param_value("tag", 0));
  1156. EXPECT_EQ("second", req.get_param_value("tag", 1));
  1157. EXPECT_EQ("third", req.get_param_value("tag", 2));
  1158. EXPECT_EQ("", req.get_param_value("tag", 3));
  1159. }
  1160. TEST(ParamsOrderTest, LookupStaysCaseSensitive) {
  1161. // Params shares its container with Headers, which matches field names
  1162. // case-insensitively. Parameter names must not pick that up.
  1163. Params dic;
  1164. dic.emplace("Key", "upper");
  1165. dic.emplace("key", "lower");
  1166. EXPECT_EQ(2U, dic.size());
  1167. EXPECT_EQ(1U, dic.count("Key"));
  1168. EXPECT_EQ(1U, dic.count("key"));
  1169. EXPECT_EQ("upper", dic.find("Key")->second);
  1170. EXPECT_EQ("lower", dic.find("key")->second);
  1171. EXPECT_TRUE(dic.find("KEY") == dic.end());
  1172. }
  1173. TEST(ParamsOrderTest, ServerSeesTheOrderTheClientSent) {
  1174. Server svr;
  1175. std::string order;
  1176. svr.Get("/order", [&](const Request &req, Response &res) {
  1177. order = entries_to_string(req.params);
  1178. res.set_content("ok", "text/plain");
  1179. });
  1180. auto port = svr.bind_to_any_port(HOST);
  1181. thread t = thread([&] { svr.listen_after_bind(); });
  1182. auto se = detail::scope_exit([&] {
  1183. svr.stop();
  1184. t.join();
  1185. ASSERT_FALSE(svr.is_running());
  1186. });
  1187. svr.wait_until_ready();
  1188. Client cli(HOST, port);
  1189. auto res = cli.Get("/order?zulu=1&alpha=2&tag=x&mike=3&tag=y");
  1190. ASSERT_TRUE(res);
  1191. EXPECT_EQ("zulu=1 alpha=2 tag=x mike=3 tag=y ", order);
  1192. }
  1193. TEST(MultipartOrderTest, PartsKeepTheOrderSent) {
  1194. Server svr;
  1195. std::string field_order, file_order;
  1196. svr.Post("/order", [&](const Request &req, Response &res) {
  1197. for (const auto &field : req.form.fields) {
  1198. field_order += field.first + "=" + field.second.content + " ";
  1199. }
  1200. for (const auto &file : req.form.files) {
  1201. file_order += file.first + "=" + file.second.filename + " ";
  1202. }
  1203. res.set_content("ok", "text/plain");
  1204. });
  1205. auto port = svr.bind_to_any_port(HOST);
  1206. thread t = thread([&] { svr.listen_after_bind(); });
  1207. auto se = detail::scope_exit([&] {
  1208. svr.stop();
  1209. t.join();
  1210. ASSERT_FALSE(svr.is_running());
  1211. });
  1212. svr.wait_until_ready();
  1213. UploadFormDataItems items = {
  1214. {"zulu", "1", "", ""},
  1215. {"alpha", "2", "", ""},
  1216. {"mike", "3", "", ""},
  1217. {"zebra", "z", "z.txt", "text/plain"},
  1218. {"apple", "a", "a.txt", "text/plain"},
  1219. };
  1220. Client cli(HOST, port);
  1221. auto res = cli.Post("/order", items);
  1222. ASSERT_TRUE(res);
  1223. EXPECT_EQ("zulu=1 alpha=2 mike=3 ", field_order);
  1224. EXPECT_EQ("zebra=z.txt apple=a.txt ", file_order);
  1225. }
  1226. TEST(MultipartOrderTest, RepeatedNamesKeepTheirOrder) {
  1227. Server svr;
  1228. std::vector<std::string> values;
  1229. std::string first, second, out_of_range, order;
  1230. svr.Post("/repeated", [&](const Request &req, Response &res) {
  1231. values = req.form.get_fields("tag");
  1232. first = req.form.get_field("tag", 0);
  1233. second = req.form.get_field("tag", 1);
  1234. out_of_range = req.form.get_field("tag", 2);
  1235. for (const auto &field : req.form.fields) {
  1236. order += field.first + "=" + field.second.content + " ";
  1237. }
  1238. res.set_content("ok", "text/plain");
  1239. });
  1240. auto port = svr.bind_to_any_port(HOST);
  1241. thread t = thread([&] { svr.listen_after_bind(); });
  1242. auto se = detail::scope_exit([&] {
  1243. svr.stop();
  1244. t.join();
  1245. ASSERT_FALSE(svr.is_running());
  1246. });
  1247. svr.wait_until_ready();
  1248. // "other" sits between the two "tag" parts, so the entries sharing a name are
  1249. // not adjacent in the container.
  1250. UploadFormDataItems items = {
  1251. {"tag", "first", "", ""},
  1252. {"other", "x", "", ""},
  1253. {"tag", "second", "", ""},
  1254. };
  1255. Client cli(HOST, port);
  1256. auto res = cli.Post("/repeated", items);
  1257. ASSERT_TRUE(res);
  1258. ASSERT_EQ(2U, values.size());
  1259. EXPECT_EQ("first", values[0]);
  1260. EXPECT_EQ("second", values[1]);
  1261. EXPECT_EQ("first", first);
  1262. EXPECT_EQ("second", second);
  1263. // std::multimap already kept entries sharing a name in insertion order, so
  1264. // everything above passes without this change too. The whole traversal is
  1265. // what tells the two apart: sorting by name would hoist "other" to the front
  1266. // and the two "tag" parts would end up adjacent.
  1267. EXPECT_EQ("tag=first other=x tag=second ", order);
  1268. // Advancing past the last entry of a name used to run off the container;
  1269. // the container's saturating increment makes it return the default instead.
  1270. EXPECT_EQ("", out_of_range);
  1271. }
  1272. TEST(MultipartOrderTest, ContentSurvivesContainerGrowth) {
  1273. // Server::read_content() keeps a FormFields::iterator alive across the
  1274. // content callbacks that fill the part it points at. The container is
  1275. // vector-backed, so a later emplace can reallocate and invalidate an older
  1276. // iterator; 64 parts grow the vector through seven reallocations, which
  1277. // checks that every part's content still lands in its own entry.
  1278. const size_t part_count = 64;
  1279. // One formula for both the parts sent and the values expected back, so the
  1280. // two cannot drift apart.
  1281. auto name_of = [](size_t i) { return "f" + std::to_string(i); };
  1282. auto content_of = [](size_t i) {
  1283. return std::string(64, static_cast<char>('a' + (i % 26)));
  1284. };
  1285. Server svr;
  1286. std::vector<std::pair<std::string, std::string>> received;
  1287. svr.Post("/many", [&](const Request &req, Response &res) {
  1288. for (const auto &field : req.form.fields) {
  1289. received.emplace_back(field.first, field.second.content);
  1290. }
  1291. res.set_content("ok", "text/plain");
  1292. });
  1293. auto port = svr.bind_to_any_port(HOST);
  1294. thread t = thread([&] { svr.listen_after_bind(); });
  1295. auto se = detail::scope_exit([&] {
  1296. svr.stop();
  1297. t.join();
  1298. ASSERT_FALSE(svr.is_running());
  1299. });
  1300. svr.wait_until_ready();
  1301. UploadFormDataItems items;
  1302. for (size_t i = 0; i < part_count; i++) {
  1303. items.push_back({name_of(i), content_of(i), "", ""});
  1304. }
  1305. Client cli(HOST, port);
  1306. auto res = cli.Post("/many", items);
  1307. ASSERT_TRUE(res);
  1308. ASSERT_EQ(part_count, received.size());
  1309. for (size_t i = 0; i < part_count; i++) {
  1310. EXPECT_EQ(name_of(i), received[i].first) << "part " << i;
  1311. EXPECT_EQ(content_of(i), received[i].second) << "part " << i;
  1312. }
  1313. }
  1314. TEST(ParseMultipartBoundaryTest, DefaultValue) {
  1315. string content_type = "multipart/form-data; boundary=something";
  1316. string boundary;
  1317. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1318. EXPECT_TRUE(ret);
  1319. EXPECT_EQ(boundary, "something");
  1320. }
  1321. TEST(ParseMultipartBoundaryTest, ValueWithQuote) {
  1322. string content_type = "multipart/form-data; boundary=\"gc0pJq0M:08jU534c0p\"";
  1323. string boundary;
  1324. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1325. EXPECT_TRUE(ret);
  1326. EXPECT_EQ(boundary, "gc0pJq0M:08jU534c0p");
  1327. }
  1328. TEST(ParseMultipartBoundaryTest, ValueWithCharset) {
  1329. string content_type =
  1330. "multipart/mixed; boundary=THIS_STRING_SEPARATES;charset=UTF-8";
  1331. string boundary;
  1332. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1333. EXPECT_TRUE(ret);
  1334. EXPECT_EQ(boundary, "THIS_STRING_SEPARATES");
  1335. }
  1336. TEST(ParseMultipartBoundaryTest, ValueWithQuotesAndCharset) {
  1337. string content_type =
  1338. "multipart/mixed; boundary=\"cpp-httplib-multipart-data\"; charset=UTF-8";
  1339. string boundary;
  1340. auto ret = detail::parse_multipart_boundary(content_type, boundary);
  1341. EXPECT_TRUE(ret);
  1342. EXPECT_EQ(boundary, "cpp-httplib-multipart-data");
  1343. }
  1344. TEST(ParseMultipartBoundaryTest, LongestAllowedValue) {
  1345. const string boundary(70, 'a');
  1346. string content_type = "multipart/form-data; boundary=" + boundary;
  1347. string parsed;
  1348. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1349. EXPECT_TRUE(ret);
  1350. EXPECT_EQ(parsed, boundary);
  1351. }
  1352. TEST(ParseMultipartBoundaryTest, ValueLongerThanRFCLimit) {
  1353. // RFC 2046 5.1.1 caps a boundary at 70 characters.
  1354. string content_type = "multipart/form-data; boundary=" + string(71, 'a');
  1355. string parsed;
  1356. auto ret = detail::parse_multipart_boundary(content_type, parsed);
  1357. EXPECT_FALSE(ret);
  1358. }
  1359. TEST(ParseMultipartBoundaryTest, QuotedValueIsMeasuredAfterUnquoting) {
  1360. // The limit applies to the unquoted value, so a quoted 70 character boundary
  1361. // is 72 characters on the wire and still valid.
  1362. const string boundary(70, 'a');
  1363. string content_type = "multipart/form-data; boundary=\"" + boundary + "\"";
  1364. string parsed;
  1365. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1366. EXPECT_EQ(parsed, boundary);
  1367. content_type = "multipart/form-data; boundary=\"" + string(71, 'a') + "\"";
  1368. parsed.clear();
  1369. EXPECT_FALSE(detail::parse_multipart_boundary(content_type, parsed));
  1370. }
  1371. TEST(ParseMultipartBoundaryTest, QuotedValueWithEqualsSign) {
  1372. // RFC 2046 5.1.1 allows '=' in a boundary, so a MIME sender has to quote it.
  1373. // The parameter parser must not treat that '=' as the key/value separator.
  1374. string content_type =
  1375. "multipart/mixed; boundary=\"----=_NextPart_000_0000_01D9\"; "
  1376. "charset=UTF-8";
  1377. string parsed;
  1378. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1379. EXPECT_EQ(parsed, "----=_NextPart_000_0000_01D9");
  1380. }
  1381. TEST(ParseMultipartBoundaryTest, QuotedValueWithSemicolon) {
  1382. // A ';' inside the quoted-string is part of the value, not a parameter
  1383. // separator, so it must not truncate the boundary.
  1384. string content_type = "multipart/mixed; boundary=\"a;b\"; charset=UTF-8";
  1385. string parsed;
  1386. EXPECT_TRUE(detail::parse_multipart_boundary(content_type, parsed));
  1387. EXPECT_EQ(parsed, "a;b");
  1388. }
  1389. TEST(ParseDispositionParamsTest, QuotedValues) {
  1390. // RFC 9110 Section 5.6.6: a parameter value may be a quoted-string, and
  1391. // ';' and '=' are ordinary characters inside one.
  1392. struct {
  1393. const char *value;
  1394. std::vector<std::pair<const char *, const char *>> expected;
  1395. } cases[] = {
  1396. {"name=\"file1\"; filename=\"a.txt\"",
  1397. {{"name", "file1"}, {"filename", "a.txt"}}},
  1398. // Whitespace around '=' and ';' is still trimmed
  1399. {"name=\"file2\" ;filename = \"a.html\"",
  1400. {{"name", "file2"}, {"filename", "a.html"}}},
  1401. // '=' inside the value used to leave only the text after the last one
  1402. {"name=\"file1\"; filename=\"report=v2.pdf\"",
  1403. {{"name", "file1"}, {"filename", "report=v2.pdf"}}},
  1404. {"name=\"x=y\"", {{"name", "x=y"}}},
  1405. // ';' inside the value used to truncate the pair and leave a bogus one
  1406. {"name=\"file3\"; filename=\"a;b.txt\"",
  1407. {{"name", "file3"}, {"filename", "a;b.txt"}}},
  1408. // An unquoted value keeps working, and so does filename*
  1409. {"filename*=UTF-8''%41.txt; filename=\"a.txt\"",
  1410. {{"filename*", "UTF-8''%41.txt"}, {"filename", "a.txt"}}},
  1411. // A parameter with no key is dropped rather than turned into one whose
  1412. // key is the value
  1413. {"=nokey; name=\"file5\"", {{"name", "file5"}}},
  1414. };
  1415. for (const auto &c : cases) {
  1416. Params params;
  1417. detail::parse_disposition_params(c.value, params);
  1418. for (const auto &kv : c.expected) {
  1419. auto it = params.find(kv.first);
  1420. ASSERT_NE(it, params.end())
  1421. << "value: " << c.value << ", key: " << kv.first;
  1422. EXPECT_EQ(kv.second, it->second) << "value: " << c.value;
  1423. }
  1424. EXPECT_EQ(c.expected.size(), params.size()) << "value: " << c.value;
  1425. }
  1426. }
  1427. TEST(ParseDispositionParamsTest, QuotedValuesSurviveTheRoundTrip) {
  1428. // escape_multipart_field() only escapes '"', CR and LF, so a name or
  1429. // filename holding '=' or ';' reaches the server's parameter parser as is.
  1430. Server svr;
  1431. std::string field_value, file_name, file_filename;
  1432. bool has_field = false, has_file = false;
  1433. svr.Post("/quoted", [&](const Request &req, Response &res) {
  1434. has_field = req.form.has_field("x=y");
  1435. field_value = req.form.get_field("x=y");
  1436. has_file = req.form.has_file("file1");
  1437. const auto &file = req.form.get_file("file1");
  1438. file_name = file.name;
  1439. file_filename = file.filename;
  1440. res.set_content("ok", "text/plain");
  1441. });
  1442. auto port = svr.bind_to_any_port(HOST);
  1443. thread t = thread([&] { svr.listen_after_bind(); });
  1444. auto se = detail::scope_exit([&] {
  1445. svr.stop();
  1446. t.join();
  1447. ASSERT_FALSE(svr.is_running());
  1448. });
  1449. svr.wait_until_ready();
  1450. UploadFormDataItems items = {
  1451. {"x=y", "field-value", "", ""},
  1452. {"file1", "pdf-bytes", "a;b=report.pdf", "application/pdf"},
  1453. };
  1454. Client cli(HOST, port);
  1455. auto res = cli.Post("/quoted", items);
  1456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1457. ASSERT_EQ(StatusCode::OK_200, res->status);
  1458. EXPECT_TRUE(has_field);
  1459. EXPECT_EQ("field-value", field_value);
  1460. EXPECT_TRUE(has_file);
  1461. EXPECT_EQ("file1", file_name);
  1462. EXPECT_EQ("a;b=report.pdf", file_filename);
  1463. }
  1464. TEST(GetHeaderValueTest, DefaultValue) {
  1465. Headers headers = {{"Dummy", "Dummy"}};
  1466. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1467. EXPECT_STREQ("text/plain", val);
  1468. }
  1469. TEST(GetHeaderValueTest, DefaultValueInt) {
  1470. Headers headers = {{"Dummy", "Dummy"}};
  1471. auto val = detail::get_header_value_u64(headers, "Content-Length", 100, 0);
  1472. EXPECT_EQ(100ull, val);
  1473. }
  1474. TEST(GetHeaderValueTest, RegularValue) {
  1475. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1476. auto val = detail::get_header_value(headers, "Content-Type", "text/plain", 0);
  1477. EXPECT_STREQ("text/html", val);
  1478. }
  1479. TEST(GetHeaderValueTest, RegularValueWithDifferentCase) {
  1480. Headers headers = {{"Content-Type", "text/html"}, {"Dummy", "Dummy"}};
  1481. auto val = detail::get_header_value(headers, "content-type", "text/plain", 0);
  1482. EXPECT_STREQ("text/html", val);
  1483. }
  1484. TEST(GetHeaderValueTest, SetContent) {
  1485. Response res;
  1486. res.set_content("html", "text/html");
  1487. EXPECT_EQ("text/html", res.get_header_value("Content-Type"));
  1488. res.set_content("text", "text/plain");
  1489. EXPECT_EQ(1U, res.get_header_value_count("Content-Type"));
  1490. EXPECT_EQ("text/plain", res.get_header_value("Content-Type"));
  1491. }
  1492. TEST(GetHeaderValueTest, RegularValueInt) {
  1493. Headers headers = {{"Content-Length", "100"}, {"Dummy", "Dummy"}};
  1494. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0);
  1495. EXPECT_EQ(100ull, val);
  1496. }
  1497. TEST(GetHeaderValueTest, RegularInvalidValueInt) {
  1498. Headers headers = {{"Content-Length", "x"}};
  1499. auto is_invalid_value = false;
  1500. auto val = detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1501. is_invalid_value);
  1502. EXPECT_EQ(0ull, val);
  1503. EXPECT_TRUE(is_invalid_value);
  1504. }
  1505. TEST(GetHeaderValueTest, OutOfRangeValueInt) {
  1506. // An all-digit value that overflows size_t must be reported as invalid, not
  1507. // silently saturated/truncated: parsing at size_t width would otherwise wrap
  1508. // a large length to a small one on 32-bit builds, leaving the framing length
  1509. // wrong while is_invalid_value stayed false.
  1510. Headers headers = {{"Content-Length", "99999999999999999999999999"}};
  1511. auto is_invalid_value = false;
  1512. detail::get_header_value_u64(headers, "Content-Length", 0, 0,
  1513. is_invalid_value);
  1514. EXPECT_TRUE(is_invalid_value);
  1515. // A well-formed length is unaffected.
  1516. Headers ok = {{"Content-Length", "1234"}};
  1517. is_invalid_value = false;
  1518. auto val = detail::get_header_value_u64(ok, "Content-Length", 0, 0,
  1519. is_invalid_value);
  1520. EXPECT_EQ(1234ull, val);
  1521. EXPECT_FALSE(is_invalid_value);
  1522. }
  1523. TEST(GetHeaderValueTest, Range) {
  1524. {
  1525. Headers headers = {make_range_header({{1, -1}})};
  1526. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1527. EXPECT_STREQ("bytes=1-", val);
  1528. }
  1529. {
  1530. Headers headers = {make_range_header({{-1, 1}})};
  1531. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1532. EXPECT_STREQ("bytes=-1", val);
  1533. }
  1534. {
  1535. Headers headers = {make_range_header({{1, 10}})};
  1536. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1537. EXPECT_STREQ("bytes=1-10", val);
  1538. }
  1539. {
  1540. Headers headers = {make_range_header({{1, 10}, {100, -1}})};
  1541. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1542. EXPECT_STREQ("bytes=1-10, 100-", val);
  1543. }
  1544. {
  1545. Headers headers = {make_range_header({{1, 10}, {100, 200}})};
  1546. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1547. EXPECT_STREQ("bytes=1-10, 100-200", val);
  1548. }
  1549. {
  1550. Headers headers = {make_range_header({{0, 0}, {-1, 1}})};
  1551. auto val = detail::get_header_value(headers, "Range", 0, 0);
  1552. EXPECT_STREQ("bytes=0-0, -1", val);
  1553. }
  1554. }
  1555. TEST(BearerTokenAuthTest, SchemeValidation) {
  1556. // A value shorter than "Bearer " must not throw from the fixed-length
  1557. // substr, and a non-Bearer scheme must not be reported as a token.
  1558. struct {
  1559. const char *value;
  1560. const char *expected;
  1561. } cases[] = {
  1562. {"x", ""},
  1563. {"Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==", ""},
  1564. {"Bearer abc123", "abc123"},
  1565. {"bearer abc123", "abc123"}, // scheme match is case-insensitive
  1566. };
  1567. for (const auto &c : cases) {
  1568. Request req;
  1569. req.set_header("Authorization", c.value);
  1570. EXPECT_EQ(c.expected, get_bearer_token_auth(req)) << "value: " << c.value;
  1571. }
  1572. }
  1573. TEST(HeadersOrderTest, DuplicateFieldsKeepInsertionOrder) {
  1574. // RFC 9110 5.3: the order of fields sharing a name is significant. This used
  1575. // to depend on the standard library (libstdc++ handed back duplicates in
  1576. // reverse insertion order, libc++ in insertion order).
  1577. Request req;
  1578. req.set_header("Accept-Encoding", "gzip");
  1579. req.set_header("Accept-Encoding", "deflate");
  1580. req.set_header("Accept-Encoding", "br");
  1581. EXPECT_EQ(3U, req.get_header_value_count("Accept-Encoding"));
  1582. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding"));
  1583. EXPECT_EQ("gzip", req.get_header_value("Accept-Encoding", "", 0));
  1584. EXPECT_EQ("deflate", req.get_header_value("Accept-Encoding", "", 1));
  1585. EXPECT_EQ("br", req.get_header_value("Accept-Encoding", "", 2));
  1586. }
  1587. TEST(HeadersOrderTest, IdBeyondTheLastDuplicateYieldsDefault) {
  1588. Request req;
  1589. req.set_header("X-Test", "only");
  1590. EXPECT_EQ("only", req.get_header_value("X-Test", "def", 0));
  1591. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 1));
  1592. EXPECT_EQ("def", req.get_header_value("X-Test", "def", 99));
  1593. EXPECT_EQ("def", req.get_header_value("X-Missing", "def", 3));
  1594. }
  1595. TEST(HeadersOrderTest, TraversalFollowsInsertionOrder) {
  1596. Headers headers;
  1597. headers.emplace("Host", "example.com");
  1598. headers.emplace("Accept-Encoding", "gzip");
  1599. headers.emplace("User-Agent", "test");
  1600. headers.emplace("Accept-Encoding", "deflate");
  1601. EXPECT_EQ("Host=example.com Accept-Encoding=gzip User-Agent=test "
  1602. "Accept-Encoding=deflate ",
  1603. entries_to_string(headers));
  1604. }
  1605. TEST(HeadersOrderTest, LookupIsCaseInsensitiveAndPicksTheFirstField) {
  1606. Headers headers = {{"Content-Type", "text/html"},
  1607. {"CONTENT-TYPE", "text/xml"}};
  1608. EXPECT_EQ(2U, headers.count("content-type"));
  1609. auto it = headers.find("content-type");
  1610. ASSERT_TRUE(it != headers.end());
  1611. EXPECT_EQ("text/html", it->second);
  1612. }
  1613. TEST(HeadersOrderTest, ErasingAnEqualRangeSparesInterleavedFields) {
  1614. // The fields sharing a name are not adjacent, so an equal_range() erase must
  1615. // drop only those fields and leave everything positioned between them.
  1616. Headers headers = {{"A", "1"}, {"X", "x"}, {"A", "2"},
  1617. {"Y", "y"}, {"A", "3"}, {"Z", "z"}};
  1618. auto rng = headers.equal_range("a");
  1619. headers.erase(rng.first, rng.second);
  1620. EXPECT_EQ("X=x Y=y Z=z ", entries_to_string(headers));
  1621. }
  1622. TEST(HeadersOrderTest, ErasingByNameKeepsTheRemainingOrder) {
  1623. Headers headers = {
  1624. {"A", "1"}, {"B", "2"}, {"a", "3"}, {"C", "4"}, {"A", "5"}};
  1625. EXPECT_EQ(3U, headers.erase("A"));
  1626. EXPECT_EQ(0U, headers.count("A"));
  1627. EXPECT_EQ("B=2 C=4 ", entries_to_string(headers));
  1628. }
  1629. TEST(HeadersOrderTest, EmplaceFrontPrepends) {
  1630. Headers headers = {{"Accept", "*/*"}, {"User-Agent", "test"}};
  1631. headers.emplace_front("Host", "example.com");
  1632. EXPECT_EQ("Host=example.com Accept=*/* User-Agent=test ",
  1633. entries_to_string(headers));
  1634. }
  1635. TEST(ParseHeaderValueTest, Range) {
  1636. {
  1637. Ranges ranges;
  1638. auto ret = detail::parse_range_header("bytes=1-", ranges);
  1639. EXPECT_TRUE(ret);
  1640. EXPECT_EQ(1u, ranges.size());
  1641. EXPECT_EQ(1u, ranges[0].first);
  1642. EXPECT_EQ(-1, ranges[0].second);
  1643. }
  1644. {
  1645. Ranges ranges;
  1646. auto ret = detail::parse_range_header("bytes=-1", ranges);
  1647. EXPECT_TRUE(ret);
  1648. EXPECT_EQ(1u, ranges.size());
  1649. EXPECT_EQ(-1, ranges[0].first);
  1650. EXPECT_EQ(1u, ranges[0].second);
  1651. }
  1652. {
  1653. Ranges ranges;
  1654. auto ret = detail::parse_range_header("bytes=1-10", ranges);
  1655. EXPECT_TRUE(ret);
  1656. EXPECT_EQ(1u, ranges.size());
  1657. EXPECT_EQ(1u, ranges[0].first);
  1658. EXPECT_EQ(10u, ranges[0].second);
  1659. }
  1660. {
  1661. Ranges ranges;
  1662. auto ret = detail::parse_range_header("bytes=10-1", ranges);
  1663. EXPECT_FALSE(ret);
  1664. }
  1665. {
  1666. Ranges ranges;
  1667. auto ret = detail::parse_range_header("bytes=1-10, 100-", ranges);
  1668. EXPECT_TRUE(ret);
  1669. EXPECT_EQ(2u, ranges.size());
  1670. EXPECT_EQ(1u, ranges[0].first);
  1671. EXPECT_EQ(10u, ranges[0].second);
  1672. EXPECT_EQ(100u, ranges[1].first);
  1673. EXPECT_EQ(-1, ranges[1].second);
  1674. }
  1675. {
  1676. Ranges ranges;
  1677. auto ret =
  1678. detail::parse_range_header("bytes=1-10, 100-200, 300-400", ranges);
  1679. EXPECT_TRUE(ret);
  1680. EXPECT_EQ(3u, ranges.size());
  1681. EXPECT_EQ(1u, ranges[0].first);
  1682. EXPECT_EQ(10u, ranges[0].second);
  1683. EXPECT_EQ(100u, ranges[1].first);
  1684. EXPECT_EQ(200u, ranges[1].second);
  1685. EXPECT_EQ(300u, ranges[2].first);
  1686. EXPECT_EQ(400u, ranges[2].second);
  1687. }
  1688. {
  1689. Ranges ranges;
  1690. EXPECT_FALSE(detail::parse_range_header("bytes", ranges));
  1691. EXPECT_FALSE(detail::parse_range_header("bytes=", ranges));
  1692. EXPECT_FALSE(detail::parse_range_header("bytes=0", ranges));
  1693. EXPECT_FALSE(detail::parse_range_header("bytes=-", ranges));
  1694. EXPECT_FALSE(detail::parse_range_header("bytes= ", ranges));
  1695. EXPECT_FALSE(detail::parse_range_header("bytes=,", ranges));
  1696. EXPECT_FALSE(detail::parse_range_header("bytes=,,", ranges));
  1697. EXPECT_FALSE(detail::parse_range_header("bytes=,,,", ranges));
  1698. EXPECT_FALSE(detail::parse_range_header("bytes=a-b", ranges));
  1699. EXPECT_FALSE(detail::parse_range_header("bytes=1-0", ranges));
  1700. EXPECT_FALSE(detail::parse_range_header("bytes=0--1", ranges));
  1701. EXPECT_FALSE(detail::parse_range_header("bytes=0- 1", ranges));
  1702. EXPECT_FALSE(detail::parse_range_header("bytes=0 -1", ranges));
  1703. // Overflows ssize_t; must not be read as the suffix range "bytes=-100".
  1704. EXPECT_FALSE(
  1705. detail::parse_range_header("bytes=9223372036854775808-100", ranges));
  1706. EXPECT_TRUE(ranges.empty());
  1707. }
  1708. {
  1709. // RFC 9110 14.1.2: a last-byte-pos greater than the content length is the
  1710. // remainder of the representation, so it stays accepted.
  1711. Ranges ranges;
  1712. auto ret =
  1713. detail::parse_range_header("bytes=0-99999999999999999999", ranges);
  1714. EXPECT_TRUE(ret);
  1715. ASSERT_EQ(1u, ranges.size());
  1716. EXPECT_EQ(0, ranges[0].first);
  1717. EXPECT_EQ(-1, ranges[0].second);
  1718. }
  1719. }
  1720. TEST(ParseAcceptEncoding1, AcceptEncoding) {
  1721. Request req;
  1722. req.set_header("Accept-Encoding", "gzip");
  1723. Response res;
  1724. res.set_header("Content-Type", "text/plain");
  1725. auto ret = detail::encoding_type(req, res);
  1726. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1727. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1728. #else
  1729. EXPECT_TRUE(ret == detail::EncodingType::None);
  1730. #endif
  1731. }
  1732. TEST(ParseAcceptEncoding2, AcceptEncoding) {
  1733. Request req;
  1734. req.set_header("Accept-Encoding", "gzip, deflate, br, zstd");
  1735. Response res;
  1736. res.set_header("Content-Type", "text/plain");
  1737. auto ret = detail::encoding_type(req, res);
  1738. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1739. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1740. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1741. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1742. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1743. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1744. #else
  1745. EXPECT_TRUE(ret == detail::EncodingType::None);
  1746. #endif
  1747. }
  1748. TEST(ParseAcceptEncoding3, AcceptEncoding) {
  1749. Request req;
  1750. req.set_header("Accept-Encoding",
  1751. "br;q=1.0, gzip;q=0.8, zstd;q=0.8, *;q=0.1");
  1752. Response res;
  1753. res.set_header("Content-Type", "text/plain");
  1754. auto ret = detail::encoding_type(req, res);
  1755. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1756. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1757. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1758. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1759. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1760. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1761. #else
  1762. EXPECT_TRUE(ret == detail::EncodingType::None);
  1763. #endif
  1764. }
  1765. TEST(ParseAcceptEncoding4, AcceptEncodingQZero) {
  1766. // All supported encodings rejected with q=0 should return None
  1767. Request req;
  1768. req.set_header("Accept-Encoding", "gzip;q=0, br;q=0, zstd;q=0, deflate");
  1769. Response res;
  1770. res.set_header("Content-Type", "text/plain");
  1771. auto ret = detail::encoding_type(req, res);
  1772. EXPECT_TRUE(ret == detail::EncodingType::None);
  1773. }
  1774. TEST(ParseAcceptEncoding5, AcceptEncodingQZeroVariants) {
  1775. // q=0.0, q=0.00, q=0.000 should also be treated as rejected
  1776. Request req;
  1777. req.set_header("Accept-Encoding", "gzip;q=0.000, br;q=0.0, zstd;q=0.00");
  1778. Response res;
  1779. res.set_header("Content-Type", "text/plain");
  1780. auto ret = detail::encoding_type(req, res);
  1781. EXPECT_TRUE(ret == detail::EncodingType::None);
  1782. }
  1783. TEST(ParseAcceptEncodingTest, RejectsTrailingQualityCharacters) {
  1784. Request req;
  1785. req.set_header("Accept-Encoding", "gzip;q=0.5junk");
  1786. Response res;
  1787. res.set_header("Content-Type", "text/plain");
  1788. EXPECT_EQ(detail::EncodingType::None, detail::encoding_type(req, res));
  1789. }
  1790. TEST(ParseAcceptEncoding6, AcceptEncodingXGzipQZero) {
  1791. // x-gzip;q=0 should not cause "gzip" to be incorrectly detected
  1792. Request req;
  1793. req.set_header("Accept-Encoding", "x-gzip;q=0");
  1794. Response res;
  1795. res.set_header("Content-Type", "text/plain");
  1796. auto ret = detail::encoding_type(req, res);
  1797. EXPECT_TRUE(ret == detail::EncodingType::None);
  1798. }
  1799. TEST(ParseAcceptEncoding7, AcceptEncodingCaseInsensitive) {
  1800. // RFC 7231: Accept-Encoding values are case-insensitive
  1801. Request req;
  1802. req.set_header("Accept-Encoding", "GZIP, BR, ZSTD");
  1803. Response res;
  1804. res.set_header("Content-Type", "text/plain");
  1805. auto ret = detail::encoding_type(req, res);
  1806. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  1807. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1808. #elif CPPHTTPLIB_ZLIB_SUPPORT
  1809. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1810. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1811. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1812. #else
  1813. EXPECT_TRUE(ret == detail::EncodingType::None);
  1814. #endif
  1815. }
  1816. TEST(ParseAcceptEncoding8, AcceptEncodingQValuePriority) {
  1817. // q value should determine priority, not hardcoded order
  1818. Request req;
  1819. req.set_header("Accept-Encoding", "br;q=0.5, gzip;q=1.0, zstd;q=0.8");
  1820. Response res;
  1821. res.set_header("Content-Type", "text/plain");
  1822. auto ret = detail::encoding_type(req, res);
  1823. // gzip has highest q=1.0, so it should be selected even though
  1824. // br and zstd are also supported
  1825. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  1826. EXPECT_TRUE(ret == detail::EncodingType::Gzip);
  1827. #elif CPPHTTPLIB_ZSTD_SUPPORT
  1828. EXPECT_TRUE(ret == detail::EncodingType::Zstd);
  1829. #elif CPPHTTPLIB_BROTLI_SUPPORT
  1830. EXPECT_TRUE(ret == detail::EncodingType::Brotli);
  1831. #else
  1832. EXPECT_TRUE(ret == detail::EncodingType::None);
  1833. #endif
  1834. }
  1835. TEST(BufferStreamTest, read) {
  1836. detail::BufferStream strm1;
  1837. Stream &strm = strm1;
  1838. EXPECT_EQ(5, strm.write("hello"));
  1839. char buf[512];
  1840. EXPECT_EQ(2, strm.read(buf, 2));
  1841. EXPECT_EQ('h', buf[0]);
  1842. EXPECT_EQ('e', buf[1]);
  1843. EXPECT_EQ(2, strm.read(buf, 2));
  1844. EXPECT_EQ('l', buf[0]);
  1845. EXPECT_EQ('l', buf[1]);
  1846. EXPECT_EQ(1, strm.read(buf, 1));
  1847. EXPECT_EQ('o', buf[0]);
  1848. EXPECT_EQ(0, strm.read(buf, 1));
  1849. }
  1850. TEST(HostnameToIPConversionTest, HTTPWatch_Online) {
  1851. auto host = "www.httpwatch.com";
  1852. auto ip = hosted_at(host);
  1853. EXPECT_EQ("23.96.13.243", ip);
  1854. std::vector<std::string> addrs;
  1855. hosted_at(host, addrs);
  1856. EXPECT_EQ(1u, addrs.size());
  1857. }
  1858. #if 0 // It depends on each test environment...
  1859. TEST(HostnameToIPConversionTest, YouTube_Online) {
  1860. auto host = "www.youtube.com";
  1861. std::vector<std::string> addrs;
  1862. hosted_at(host, addrs);
  1863. EXPECT_EQ(20u, addrs.size());
  1864. auto it = std::find(addrs.begin(), addrs.end(), "2607:f8b0:4006:809::200e");
  1865. EXPECT_TRUE(it != addrs.end());
  1866. }
  1867. #endif
  1868. class ChunkedEncodingTest : public ::testing::Test {
  1869. protected:
  1870. ChunkedEncodingTest()
  1871. : cli_(HOST, PORT)
  1872. #ifdef CPPHTTPLIB_SSL_ENABLED
  1873. ,
  1874. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  1875. #endif
  1876. {
  1877. cli_.set_connection_timeout(2);
  1878. #ifdef CPPHTTPLIB_SSL_ENABLED
  1879. cli_.enable_server_certificate_verification(false);
  1880. #endif
  1881. }
  1882. virtual void SetUp() {
  1883. read_file("./image.jpg", image_data_);
  1884. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  1885. res.set_content("Hello World!", "text/plain");
  1886. });
  1887. svr_.Get(
  1888. "/chunked", [this](const httplib::Request &, httplib::Response &res) {
  1889. res.set_chunked_content_provider(
  1890. "image/jpeg", [this](size_t offset, httplib::DataSink &sink) {
  1891. size_t remaining = image_data_.size() - offset;
  1892. if (remaining == 0) {
  1893. sink.done();
  1894. } else {
  1895. constexpr size_t CHUNK_SIZE = 1024;
  1896. size_t send_size = std::min(CHUNK_SIZE, remaining);
  1897. sink.write(&image_data_[offset], send_size);
  1898. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  1899. }
  1900. return true;
  1901. });
  1902. });
  1903. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  1904. svr_.wait_until_ready();
  1905. }
  1906. virtual void TearDown() {
  1907. svr_.stop();
  1908. if (!request_threads_.empty()) {
  1909. std::this_thread::sleep_for(std::chrono::seconds(1));
  1910. for (auto &t : request_threads_) {
  1911. t.join();
  1912. }
  1913. }
  1914. t_.join();
  1915. }
  1916. #ifdef CPPHTTPLIB_SSL_ENABLED
  1917. SSLClient cli_;
  1918. SSLServer svr_;
  1919. #else
  1920. Client cli_;
  1921. Server svr_;
  1922. #endif
  1923. thread t_;
  1924. std::vector<thread> request_threads_;
  1925. std::string image_data_;
  1926. };
  1927. TEST_F(ChunkedEncodingTest, NormalGet) {
  1928. auto res = cli_.Get("/chunked");
  1929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1930. std::string out;
  1931. read_file("./image.jpg", out);
  1932. EXPECT_EQ(StatusCode::OK_200, res->status);
  1933. EXPECT_EQ(out, res->body);
  1934. }
  1935. TEST_F(ChunkedEncodingTest, WithContentReceiver) {
  1936. std::string body;
  1937. auto res = cli_.Get("/chunked", [&](const char *data, size_t data_length) {
  1938. body.append(data, data_length);
  1939. return true;
  1940. });
  1941. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1942. std::string out;
  1943. read_file("./image.jpg", out);
  1944. EXPECT_EQ(StatusCode::OK_200, res->status);
  1945. EXPECT_EQ(out, body);
  1946. }
  1947. TEST_F(ChunkedEncodingTest, WithResponseHandlerAndContentReceiver) {
  1948. std::string body;
  1949. auto res = cli_.Get(
  1950. "/chunked",
  1951. [&](const Response &response) {
  1952. EXPECT_EQ(StatusCode::OK_200, response.status);
  1953. return true;
  1954. },
  1955. [&](const char *data, size_t data_length) {
  1956. body.append(data, data_length);
  1957. return true;
  1958. });
  1959. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1960. std::string out;
  1961. read_file("./image.jpg", out);
  1962. EXPECT_EQ(StatusCode::OK_200, res->status);
  1963. EXPECT_EQ(out, body);
  1964. }
  1965. TEST(RangeTest, FromHTTPBin_Online) {
  1966. auto host = "httpbingo.org";
  1967. auto path = std::string{"/range/32"};
  1968. #ifdef CPPHTTPLIB_SSL_ENABLED
  1969. auto port = 443;
  1970. SSLClient cli(host, port);
  1971. #else
  1972. auto port = 80;
  1973. Client cli(host, port);
  1974. #endif
  1975. cli.set_connection_timeout(5);
  1976. {
  1977. auto res = cli.Get(path);
  1978. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1979. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1980. EXPECT_EQ(StatusCode::OK_200, res->status);
  1981. }
  1982. {
  1983. Headers headers = {make_range_header({{1, -1}})};
  1984. auto res = cli.Get(path, headers);
  1985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1986. EXPECT_EQ("bcdefghijklmnopqrstuvwxyzabcdef", res->body);
  1987. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1988. }
  1989. {
  1990. Headers headers = {make_range_header({{1, 10}})};
  1991. auto res = cli.Get(path, headers);
  1992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  1993. EXPECT_EQ("bcdefghijk", res->body);
  1994. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  1995. }
  1996. // go-httpbin (httpbingo.org) returns 206 even when the range covers the
  1997. // entire resource, while the original httpbin returned 200. Both are
  1998. // acceptable per RFC 9110 §15.3.7, so we accept either status code.
  1999. {
  2000. Headers headers = {make_range_header({{0, 31}})};
  2001. auto res = cli.Get(path, headers);
  2002. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2003. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2004. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2005. res->status == StatusCode::PartialContent_206);
  2006. }
  2007. {
  2008. Headers headers = {make_range_header({{0, -1}})};
  2009. auto res = cli.Get(path, headers);
  2010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2011. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2012. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  2013. res->status == StatusCode::PartialContent_206);
  2014. }
  2015. // go-httpbin returns 206 with clamped range for over-range requests,
  2016. // while the original httpbin returned 416. Both behaviors are observed
  2017. // in real servers, so we only verify the request succeeds.
  2018. {
  2019. Headers headers = {make_range_header({{0, 32}})};
  2020. auto res = cli.Get(path, headers);
  2021. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2022. }
  2023. }
  2024. TEST(GetAddrInfoDanglingRefTest, LongTimeout) {
  2025. auto host = "unresolvableaddress.local";
  2026. auto path = std::string{"/"};
  2027. #ifdef CPPHTTPLIB_SSL_ENABLED
  2028. auto port = 443;
  2029. SSLClient cli(host, port);
  2030. #else
  2031. auto port = 80;
  2032. Client cli(host, port);
  2033. #endif
  2034. cli.set_connection_timeout(1);
  2035. {
  2036. auto res = cli.Get(path);
  2037. ASSERT_FALSE(res);
  2038. }
  2039. std::this_thread::sleep_for(std::chrono::seconds(8));
  2040. }
  2041. #if defined(__linux__) && defined(__GLIBC__) && \
  2042. defined(CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO)
  2043. // Forward declaration: in split builds split.py strips `inline` and moves the
  2044. // definition into httplib.cc, so detail::getaddrinfo_with_timeout is not
  2045. // visible from the public httplib.h. Re-declaring it here lets the tests link
  2046. // against the symbol in both header-only and split builds.
  2047. namespace httplib {
  2048. namespace detail {
  2049. int getaddrinfo_with_timeout(const char *node, const char *service,
  2050. const struct addrinfo *hints,
  2051. struct addrinfo **res, time_t timeout_sec);
  2052. } // namespace detail
  2053. } // namespace httplib
  2054. // Reproducer for https://github.com/yhirose/cpp-httplib/issues/2431.
  2055. //
  2056. // On Linux/glibc, getaddrinfo_with_timeout() runs the lookup via
  2057. // getaddrinfo_a(GAI_NOWAIT) using a stack-local `struct gaicb`. When the
  2058. // gai_suspend() call hits the connection timeout the function calls
  2059. // gai_cancel() and returns immediately. gai_cancel() is non-blocking and
  2060. // can return EAI_NOTCANCELED, in which case the resolver worker thread is
  2061. // still alive and still references the now-destroyed stack frame.
  2062. //
  2063. // Triggering the bug requires DNS to actually hang (UDP/53 dropped, etc.),
  2064. // so these tests are gated on CPPHTTPLIB_TEST_ISSUE_2431=1 and are skipped
  2065. // during normal runs. test/run_issue_2431_repro.sh sets up the environment
  2066. // and runs them in a container.
  2067. namespace {
  2068. bool should_run_issue_2431_tests() {
  2069. const char *v = getenv("CPPHTTPLIB_TEST_ISSUE_2431");
  2070. return v && *v && std::string(v) != "0";
  2071. }
  2072. std::string unique_unresolvable_host(int n) {
  2073. // .invalid is reserved (RFC 6761) and is never served by real DNS, but
  2074. // glibc still asks the configured nameserver — which is exactly the path
  2075. // we want to exercise. A unique label per call avoids the resolver cache.
  2076. auto t = std::chrono::steady_clock::now().time_since_epoch().count();
  2077. return "h-" + std::to_string(::getpid()) + "-" + std::to_string(t) + "-" +
  2078. std::to_string(n) + ".invalid";
  2079. }
  2080. } // namespace
  2081. TEST(GetAddrInfoAsyncCancelTest, DirectCallSingleThread) {
  2082. if (!should_run_issue_2431_tests()) {
  2083. GTEST_SKIP()
  2084. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2085. }
  2086. for (int i = 0; i < 8; ++i) {
  2087. struct addrinfo hints;
  2088. memset(&hints, 0, sizeof(hints));
  2089. hints.ai_family = AF_UNSPEC;
  2090. hints.ai_socktype = SOCK_STREAM;
  2091. auto host = unique_unresolvable_host(i);
  2092. struct addrinfo *result = nullptr;
  2093. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2094. &result, /*timeout_sec=*/1);
  2095. if (rc == 0 && result) { freeaddrinfo(result); }
  2096. }
  2097. // Give orphaned getaddrinfo_a worker threads a chance to write into the
  2098. // stack region they still believe holds their gaicb.
  2099. std::this_thread::sleep_for(std::chrono::seconds(3));
  2100. }
  2101. TEST(GetAddrInfoAsyncCancelTest, DirectCallMultiThread) {
  2102. if (!should_run_issue_2431_tests()) {
  2103. GTEST_SKIP()
  2104. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2105. }
  2106. std::atomic<bool> stop{false};
  2107. std::vector<std::thread> threads;
  2108. for (int t = 0; t < 8; ++t) {
  2109. threads.emplace_back([t, &stop] {
  2110. int i = 0;
  2111. while (!stop.load(std::memory_order_relaxed)) {
  2112. struct addrinfo hints;
  2113. memset(&hints, 0, sizeof(hints));
  2114. hints.ai_family = AF_UNSPEC;
  2115. hints.ai_socktype = SOCK_STREAM;
  2116. auto host = unique_unresolvable_host(t * 100000 + i++);
  2117. struct addrinfo *result = nullptr;
  2118. int rc = detail::getaddrinfo_with_timeout(host.c_str(), "80", &hints,
  2119. &result, /*timeout_sec=*/1);
  2120. if (rc == 0 && result) { freeaddrinfo(result); }
  2121. }
  2122. });
  2123. }
  2124. std::this_thread::sleep_for(std::chrono::seconds(8));
  2125. stop.store(true, std::memory_order_relaxed);
  2126. for (auto &th : threads) {
  2127. th.join();
  2128. }
  2129. std::this_thread::sleep_for(std::chrono::seconds(3));
  2130. }
  2131. TEST(GetAddrInfoAsyncCancelTest, ClientGetMultiThread) {
  2132. if (!should_run_issue_2431_tests()) {
  2133. GTEST_SKIP()
  2134. << "Set CPPHTTPLIB_TEST_ISSUE_2431=1 (and sinkhole DNS) to run";
  2135. }
  2136. std::atomic<bool> stop{false};
  2137. std::vector<std::thread> threads;
  2138. for (int t = 0; t < 8; ++t) {
  2139. threads.emplace_back([t, &stop] {
  2140. int i = 0;
  2141. while (!stop.load(std::memory_order_relaxed)) {
  2142. auto host = unique_unresolvable_host(t * 100000 + i++);
  2143. Client cli(host, 80);
  2144. cli.set_connection_timeout(1, 0);
  2145. cli.set_read_timeout(1, 0);
  2146. cli.set_write_timeout(1, 0);
  2147. (void)cli.Get("/");
  2148. }
  2149. });
  2150. }
  2151. std::this_thread::sleep_for(std::chrono::seconds(8));
  2152. stop.store(true, std::memory_order_relaxed);
  2153. for (auto &th : threads) {
  2154. th.join();
  2155. }
  2156. std::this_thread::sleep_for(std::chrono::seconds(3));
  2157. }
  2158. #endif // __linux__ && __GLIBC__ && CPPHTTPLIB_USE_NON_BLOCKING_GETADDRINFO
  2159. TEST(ConnectionErrorTest, InvalidHost) {
  2160. auto host = "-abcde.com";
  2161. #ifdef CPPHTTPLIB_SSL_ENABLED
  2162. auto port = 443;
  2163. SSLClient cli(host, port);
  2164. #else
  2165. auto port = 80;
  2166. Client cli(host, port);
  2167. #endif
  2168. cli.set_connection_timeout(std::chrono::seconds(2));
  2169. auto res = cli.Get("/");
  2170. ASSERT_TRUE(!res);
  2171. EXPECT_EQ(Error::Connection, res.error());
  2172. }
  2173. TEST(ConnectionErrorTest, InvalidHost2) {
  2174. auto host = "httpcan.org/";
  2175. #ifdef CPPHTTPLIB_SSL_ENABLED
  2176. SSLClient cli(host);
  2177. #else
  2178. Client cli(host);
  2179. #endif
  2180. cli.set_connection_timeout(std::chrono::seconds(2));
  2181. auto res = cli.Get("/");
  2182. ASSERT_TRUE(!res);
  2183. EXPECT_EQ(Error::Connection, res.error());
  2184. }
  2185. TEST(ConnectionErrorTest, InvalidHostCheckResultErrorToString) {
  2186. auto host = "httpcan.org/";
  2187. #ifdef CPPHTTPLIB_SSL_ENABLED
  2188. SSLClient cli(host);
  2189. #else
  2190. Client cli(host);
  2191. #endif
  2192. cli.set_connection_timeout(std::chrono::seconds(2));
  2193. auto res = cli.Get("/");
  2194. ASSERT_TRUE(!res);
  2195. stringstream s;
  2196. s << "error code: " << res.error();
  2197. EXPECT_EQ("error code: Could not establish connection (2)", s.str());
  2198. }
  2199. TEST(ConnectionErrorTest, InvalidPort) {
  2200. auto host = "localhost";
  2201. auto port = 44380;
  2202. #ifdef CPPHTTPLIB_SSL_ENABLED
  2203. SSLClient cli(host, port);
  2204. #else
  2205. Client cli(host, port);
  2206. #endif
  2207. cli.set_connection_timeout(std::chrono::seconds(2));
  2208. auto res = cli.Get("/");
  2209. ASSERT_TRUE(!res);
  2210. EXPECT_TRUE(Error::Connection == res.error() ||
  2211. Error::ConnectionTimeout == res.error());
  2212. }
  2213. TEST(ConnectionErrorTest, Timeout_Online) {
  2214. auto host = "google.com";
  2215. #ifdef CPPHTTPLIB_SSL_ENABLED
  2216. auto port = 44380;
  2217. SSLClient cli(host, port);
  2218. #else
  2219. auto port = 8080;
  2220. Client cli(host, port);
  2221. #endif
  2222. cli.set_connection_timeout(std::chrono::seconds(2));
  2223. // only probe one address type so that the error reason
  2224. // correlates to the timed-out IPv4, not the unsupported
  2225. // IPv6 connection attempt
  2226. cli.set_address_family(AF_INET);
  2227. auto res = cli.Get("/");
  2228. ASSERT_TRUE(!res);
  2229. EXPECT_EQ(Error::ConnectionTimeout, res.error());
  2230. }
  2231. TEST(CancelTest, NoCancel_Online) {
  2232. auto host = "httpbingo.org";
  2233. auto path = std::string{"/range/32"};
  2234. #ifdef CPPHTTPLIB_SSL_ENABLED
  2235. auto port = 443;
  2236. SSLClient cli(host, port);
  2237. #else
  2238. auto port = 80;
  2239. Client cli(host, port);
  2240. #endif
  2241. cli.set_connection_timeout(std::chrono::seconds(5));
  2242. auto res = cli.Get(path, [](uint64_t, uint64_t) { return true; });
  2243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2244. EXPECT_EQ("abcdefghijklmnopqrstuvwxyzabcdef", res->body);
  2245. EXPECT_EQ(StatusCode::OK_200, res->status);
  2246. }
  2247. TEST(CancelTest, WithCancelSmallPayload_Online) {
  2248. // Use /bytes with a large payload so that the DownloadProgress callback
  2249. // (which only fires for Content-Length responses) is invoked before the
  2250. // entire body is received, giving cancellation a chance to fire.
  2251. auto host = "httpbingo.org";
  2252. auto path = std::string{"/bytes/524288"};
  2253. #ifdef CPPHTTPLIB_SSL_ENABLED
  2254. auto port = 443;
  2255. SSLClient cli(host, port);
  2256. #else
  2257. auto port = 80;
  2258. Client cli(host, port);
  2259. #endif
  2260. auto res = cli.Get(path, [](uint64_t, uint64_t) { return false; });
  2261. cli.set_connection_timeout(std::chrono::seconds(5));
  2262. ASSERT_TRUE(!res);
  2263. EXPECT_EQ(Error::Canceled, res.error());
  2264. }
  2265. TEST(CancelTest, WithCancelLargePayload_Online) {
  2266. auto host = "httpbingo.org";
  2267. auto path = std::string{"/bytes/524288"};
  2268. #ifdef CPPHTTPLIB_SSL_ENABLED
  2269. auto port = 443;
  2270. SSLClient cli(host, port);
  2271. #else
  2272. auto port = 80;
  2273. Client cli(host, port);
  2274. #endif
  2275. cli.set_connection_timeout(std::chrono::seconds(5));
  2276. uint32_t count = 0;
  2277. auto res =
  2278. cli.Get(path, [&count](uint64_t, uint64_t) { return (count++ == 0); });
  2279. ASSERT_TRUE(!res);
  2280. EXPECT_EQ(Error::Canceled, res.error());
  2281. }
  2282. TEST(CancelTest, NoCancelPost) {
  2283. Server svr;
  2284. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2285. res.set_content("Hello World!", "text/plain");
  2286. });
  2287. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2288. auto se = detail::scope_exit([&] {
  2289. svr.stop();
  2290. thread.join();
  2291. ASSERT_FALSE(svr.is_running());
  2292. });
  2293. svr.wait_until_ready();
  2294. Client cli(HOST, PORT);
  2295. cli.set_connection_timeout(std::chrono::seconds(5));
  2296. auto res =
  2297. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2298. "application/json", [](uint64_t, uint64_t) { return true; });
  2299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2300. EXPECT_EQ("Hello World!", res->body);
  2301. EXPECT_EQ(StatusCode::OK_200, res->status);
  2302. }
  2303. TEST(CancelTest, WithCancelSmallPayloadPost) {
  2304. Server svr;
  2305. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2306. res.set_content("Hello World!", "text/plain");
  2307. });
  2308. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2309. auto se = detail::scope_exit([&] {
  2310. svr.stop();
  2311. thread.join();
  2312. ASSERT_FALSE(svr.is_running());
  2313. });
  2314. svr.wait_until_ready();
  2315. Client cli(HOST, PORT);
  2316. cli.set_connection_timeout(std::chrono::seconds(5));
  2317. auto res =
  2318. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2319. "application/json", [](uint64_t, uint64_t) { return false; });
  2320. ASSERT_TRUE(!res);
  2321. EXPECT_EQ(Error::Canceled, res.error());
  2322. }
  2323. TEST(CancelTest, WithCancelLargePayloadPost) {
  2324. Server svr;
  2325. svr.set_payload_max_length(200 * 1024 * 1024);
  2326. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  2327. res.set_content(LARGE_DATA, "text/plain");
  2328. });
  2329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2330. auto se = detail::scope_exit([&] {
  2331. svr.stop();
  2332. thread.join();
  2333. ASSERT_FALSE(svr.is_running());
  2334. });
  2335. svr.wait_until_ready();
  2336. Client cli(HOST, PORT);
  2337. cli.set_payload_max_length(200 * 1024 * 1024);
  2338. cli.set_connection_timeout(std::chrono::seconds(5));
  2339. auto res =
  2340. cli.Post("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2341. "application/json", [](uint64_t, uint64_t) { return false; });
  2342. ASSERT_TRUE(!res);
  2343. EXPECT_EQ(Error::Canceled, res.error());
  2344. }
  2345. TEST(CancelTest, NoCancelPut) {
  2346. Server svr;
  2347. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2348. res.set_content("Hello World!", "text/plain");
  2349. });
  2350. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2351. auto se = detail::scope_exit([&] {
  2352. svr.stop();
  2353. thread.join();
  2354. ASSERT_FALSE(svr.is_running());
  2355. });
  2356. svr.wait_until_ready();
  2357. Client cli(HOST, PORT);
  2358. cli.set_connection_timeout(std::chrono::seconds(5));
  2359. auto res =
  2360. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2361. "application/json", [](uint64_t, uint64_t) { return true; });
  2362. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2363. EXPECT_EQ("Hello World!", res->body);
  2364. EXPECT_EQ(StatusCode::OK_200, res->status);
  2365. }
  2366. TEST(CancelTest, WithCancelSmallPayloadPut) {
  2367. Server svr;
  2368. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2369. res.set_content("Hello World!", "text/plain");
  2370. });
  2371. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2372. auto se = detail::scope_exit([&] {
  2373. svr.stop();
  2374. thread.join();
  2375. ASSERT_FALSE(svr.is_running());
  2376. });
  2377. svr.wait_until_ready();
  2378. Client cli(HOST, PORT);
  2379. cli.set_connection_timeout(std::chrono::seconds(5));
  2380. auto res =
  2381. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2382. "application/json", [](uint64_t, uint64_t) { return false; });
  2383. ASSERT_TRUE(!res);
  2384. EXPECT_EQ(Error::Canceled, res.error());
  2385. }
  2386. TEST(CancelTest, WithCancelLargePayloadPut) {
  2387. Server svr;
  2388. svr.set_payload_max_length(200 * 1024 * 1024);
  2389. svr.Put("/", [&](const Request & /*req*/, Response &res) {
  2390. res.set_content(LARGE_DATA, "text/plain");
  2391. });
  2392. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2393. auto se = detail::scope_exit([&] {
  2394. svr.stop();
  2395. thread.join();
  2396. ASSERT_FALSE(svr.is_running());
  2397. });
  2398. svr.wait_until_ready();
  2399. Client cli(HOST, PORT);
  2400. cli.set_payload_max_length(200 * 1024 * 1024);
  2401. cli.set_connection_timeout(std::chrono::seconds(5));
  2402. auto res =
  2403. cli.Put("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2404. "application/json", [](uint64_t, uint64_t) { return false; });
  2405. ASSERT_TRUE(!res);
  2406. EXPECT_EQ(Error::Canceled, res.error());
  2407. }
  2408. TEST(CancelTest, NoCancelPatch) {
  2409. Server svr;
  2410. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2411. res.set_content("Hello World!", "text/plain");
  2412. });
  2413. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2414. auto se = detail::scope_exit([&] {
  2415. svr.stop();
  2416. thread.join();
  2417. ASSERT_FALSE(svr.is_running());
  2418. });
  2419. svr.wait_until_ready();
  2420. Client cli(HOST, PORT);
  2421. cli.set_connection_timeout(std::chrono::seconds(5));
  2422. auto res =
  2423. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2424. "application/json", [](uint64_t, uint64_t) { return true; });
  2425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2426. EXPECT_EQ("Hello World!", res->body);
  2427. EXPECT_EQ(StatusCode::OK_200, res->status);
  2428. }
  2429. TEST(CancelTest, WithCancelSmallPayloadPatch) {
  2430. Server svr;
  2431. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2432. res.set_content("Hello World!", "text/plain");
  2433. });
  2434. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2435. auto se = detail::scope_exit([&] {
  2436. svr.stop();
  2437. thread.join();
  2438. ASSERT_FALSE(svr.is_running());
  2439. });
  2440. svr.wait_until_ready();
  2441. Client cli(HOST, PORT);
  2442. cli.set_connection_timeout(std::chrono::seconds(5));
  2443. auto res =
  2444. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2445. "application/json", [](uint64_t, uint64_t) { return false; });
  2446. ASSERT_TRUE(!res);
  2447. EXPECT_EQ(Error::Canceled, res.error());
  2448. }
  2449. TEST(CancelTest, WithCancelLargePayloadPatch) {
  2450. Server svr;
  2451. svr.set_payload_max_length(200 * 1024 * 1024);
  2452. svr.Patch("/", [&](const Request & /*req*/, Response &res) {
  2453. res.set_content(LARGE_DATA, "text/plain");
  2454. });
  2455. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2456. auto se = detail::scope_exit([&] {
  2457. svr.stop();
  2458. thread.join();
  2459. ASSERT_FALSE(svr.is_running());
  2460. });
  2461. svr.wait_until_ready();
  2462. Client cli(HOST, PORT);
  2463. cli.set_payload_max_length(200 * 1024 * 1024);
  2464. cli.set_connection_timeout(std::chrono::seconds(5));
  2465. auto res =
  2466. cli.Patch("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2467. "application/json", [](uint64_t, uint64_t) { return false; });
  2468. ASSERT_TRUE(!res);
  2469. EXPECT_EQ(Error::Canceled, res.error());
  2470. }
  2471. TEST(CancelTest, NoCancelDelete) {
  2472. Server svr;
  2473. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2474. res.set_content("Hello World!", "text/plain");
  2475. });
  2476. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2477. auto se = detail::scope_exit([&] {
  2478. svr.stop();
  2479. thread.join();
  2480. ASSERT_FALSE(svr.is_running());
  2481. });
  2482. svr.wait_until_ready();
  2483. Client cli(HOST, PORT);
  2484. cli.set_connection_timeout(std::chrono::seconds(5));
  2485. auto res =
  2486. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2487. "application/json", [](uint64_t, uint64_t) { return true; });
  2488. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2489. EXPECT_EQ("Hello World!", res->body);
  2490. EXPECT_EQ(StatusCode::OK_200, res->status);
  2491. }
  2492. TEST(CancelTest, WithCancelSmallPayloadDelete) {
  2493. Server svr;
  2494. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2495. res.set_content("Hello World!", "text/plain");
  2496. });
  2497. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2498. auto se = detail::scope_exit([&] {
  2499. svr.stop();
  2500. thread.join();
  2501. ASSERT_FALSE(svr.is_running());
  2502. });
  2503. svr.wait_until_ready();
  2504. Client cli(HOST, PORT);
  2505. cli.set_connection_timeout(std::chrono::seconds(5));
  2506. auto res =
  2507. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2508. "application/json", [](uint64_t, uint64_t) { return false; });
  2509. ASSERT_TRUE(!res);
  2510. EXPECT_EQ(Error::Canceled, res.error());
  2511. }
  2512. TEST(CancelTest, WithCancelLargePayloadDelete) {
  2513. Server svr;
  2514. svr.set_payload_max_length(200 * 1024 * 1024);
  2515. svr.Delete("/", [&](const Request & /*req*/, Response &res) {
  2516. res.set_content(LARGE_DATA, "text/plain");
  2517. });
  2518. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  2519. auto se = detail::scope_exit([&] {
  2520. svr.stop();
  2521. thread.join();
  2522. ASSERT_FALSE(svr.is_running());
  2523. });
  2524. svr.wait_until_ready();
  2525. Client cli(HOST, PORT);
  2526. cli.set_payload_max_length(200 * 1024 * 1024);
  2527. cli.set_connection_timeout(std::chrono::seconds(5));
  2528. auto res =
  2529. cli.Delete("/", Headers(), JSON_DATA.data(), JSON_DATA.size(),
  2530. "application/json", [](uint64_t, uint64_t) { return false; });
  2531. ASSERT_TRUE(!res);
  2532. EXPECT_EQ(Error::Canceled, res.error());
  2533. }
  2534. static std::string remove_whitespace(const std::string &input) {
  2535. std::string output;
  2536. output.reserve(input.size());
  2537. std::copy_if(input.begin(), input.end(), std::back_inserter(output),
  2538. [](unsigned char c) { return !std::isspace(c); });
  2539. return output;
  2540. }
  2541. TEST(BaseAuthTest, FromHTTPWatch_Online) {
  2542. auto host = "httpbingo.org";
  2543. auto path = std::string{"/basic-auth/hello/world"};
  2544. #ifdef CPPHTTPLIB_SSL_ENABLED
  2545. auto port = 443;
  2546. SSLClient cli(host, port);
  2547. #else
  2548. auto port = 80;
  2549. Client cli(host, port);
  2550. #endif
  2551. {
  2552. auto res = cli.Get(path);
  2553. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2554. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2555. }
  2556. {
  2557. auto res = cli.Get(
  2558. path, Headers{make_basic_authentication_header("hello", "world")});
  2559. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2560. auto body = remove_whitespace(res->body);
  2561. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2562. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2563. EXPECT_EQ(StatusCode::OK_200, res->status);
  2564. }
  2565. {
  2566. cli.set_basic_auth("hello", "world");
  2567. auto res = cli.Get(path);
  2568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2569. auto body = remove_whitespace(res->body);
  2570. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2571. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2572. EXPECT_EQ(StatusCode::OK_200, res->status);
  2573. }
  2574. {
  2575. cli.set_basic_auth("hello", "bad");
  2576. auto res = cli.Get(path);
  2577. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2578. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2579. }
  2580. {
  2581. cli.set_basic_auth("bad", "world");
  2582. auto res = cli.Get(path);
  2583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2584. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2585. }
  2586. }
  2587. #ifdef CPPHTTPLIB_SSL_ENABLED
  2588. TEST(DigestAuthTest, FromHTTPWatch_Online) {
  2589. auto host = "httpbingo.org";
  2590. auto unauth_path = std::string{"/digest-auth/auth/hello/world"};
  2591. auto paths = std::vector<std::string>{
  2592. "/digest-auth/auth/hello/world/MD5",
  2593. "/digest-auth/auth/hello/world/SHA-256",
  2594. };
  2595. auto port = 443;
  2596. SSLClient cli(host, port);
  2597. {
  2598. auto res = cli.Get(unauth_path);
  2599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2600. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2601. }
  2602. {
  2603. cli.set_digest_auth("hello", "world");
  2604. for (const auto &path : paths) {
  2605. auto res = cli.Get(path.c_str());
  2606. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2607. auto body = remove_whitespace(res->body);
  2608. EXPECT_TRUE(body.find("\"authenticated\":true") != std::string::npos);
  2609. EXPECT_TRUE(body.find("\"user\":\"hello\"") != std::string::npos);
  2610. EXPECT_EQ(StatusCode::OK_200, res->status);
  2611. }
  2612. cli.set_digest_auth("hello", "bad");
  2613. for (const auto &path : paths) {
  2614. auto res = cli.Get(path.c_str());
  2615. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2616. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2617. }
  2618. }
  2619. }
  2620. // RFC 9110 Section 11.6.1: a WWW-Authenticate field value is a
  2621. // comma-separated list of challenges, and each challenge may itself carry a
  2622. // comma-separated auth-param list, so a server can legally offer Basic
  2623. // before Digest, either as two field lines or packed into one. Runs one 401
  2624. // -> Digest-retry round trip with the given field lines (get_combined_header_
  2625. // value() joins them in receipt order) and checks that the retry carries a
  2626. // well-formed Digest Authorization header naming expected_realm.
  2627. static void
  2628. run_digest_challenge_list_test(const std::vector<std::string> &challenges,
  2629. const std::string &expected_realm) {
  2630. std::atomic<int> hits{0};
  2631. Server svr;
  2632. svr.Get("/x", [&](const Request &req, Response &res) {
  2633. if (++hits == 1) {
  2634. res.status = StatusCode::Unauthorized_401;
  2635. for (const auto &challenge : challenges) {
  2636. res.set_header("WWW-Authenticate", challenge);
  2637. }
  2638. } else {
  2639. auto authorization = req.get_header_value("Authorization");
  2640. EXPECT_EQ(0u, authorization.rfind("Digest ", 0));
  2641. EXPECT_NE(std::string::npos,
  2642. authorization.find("realm=\"" + expected_realm + "\""));
  2643. EXPECT_EQ(std::string::npos, authorization.find("Basic"));
  2644. res.set_content("ok", "text/plain");
  2645. }
  2646. });
  2647. auto port = svr.bind_to_any_port(HOST);
  2648. std::thread t([&]() { svr.listen_after_bind(); });
  2649. auto se = detail::scope_exit([&] {
  2650. svr.stop();
  2651. t.join();
  2652. });
  2653. svr.wait_until_ready();
  2654. Client cli(HOST, port);
  2655. cli.set_digest_auth("hello", "world");
  2656. auto res = cli.Get("/x");
  2657. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2658. EXPECT_EQ(2, hits.load());
  2659. }
  2660. static const char *kBasicChallenge = "Basic realm=\"decoy\"";
  2661. static const char *kDigestChallenge =
  2662. "Digest realm=\"testrealm\", qop=\"auth\", nonce=\"abc123\", "
  2663. "algorithm=MD5";
  2664. TEST(DigestAuthTest, BasicChallengeListedBeforeDigest) {
  2665. run_digest_challenge_list_test({kBasicChallenge, kDigestChallenge},
  2666. "testrealm");
  2667. }
  2668. // Same challenge list with the schemes in the opposite order, to make sure
  2669. // the fix above didn't just special-case "Basic first".
  2670. TEST(DigestAuthTest, DigestChallengeListedBeforeBasic) {
  2671. run_digest_challenge_list_test({kDigestChallenge, kBasicChallenge},
  2672. "testrealm");
  2673. }
  2674. // A comma inside a quoted auth-param value must not be mistaken for the
  2675. // separator between two challenges (or two auth-params).
  2676. TEST(DigestAuthTest, RealmContainingCommaIsNotSplit) {
  2677. run_digest_challenge_list_test(
  2678. {"Digest realm=\"test,realm\", qop=\"auth\", nonce=\"abc123\", "
  2679. "algorithm=MD5"},
  2680. "test,realm");
  2681. }
  2682. // RFC 7616 Section 3.3 requires realm and nonce on every Digest challenge.
  2683. // make_digest_authentication_header() dereferences both unconditionally, so
  2684. // a server sending a challenge missing either one must not be treated as
  2685. // usable -- doing so used to crash the client with std::out_of_range.
  2686. static void run_digest_challenge_missing_field_test(const char *challenge) {
  2687. Server svr;
  2688. svr.Get("/x", [&](const Request & /*req*/, Response &res) {
  2689. res.status = StatusCode::Unauthorized_401;
  2690. res.set_header("WWW-Authenticate", challenge);
  2691. });
  2692. auto port = svr.bind_to_any_port(HOST);
  2693. std::thread t([&]() { svr.listen_after_bind(); });
  2694. auto se = detail::scope_exit([&] {
  2695. svr.stop();
  2696. t.join();
  2697. });
  2698. svr.wait_until_ready();
  2699. Client cli(HOST, port);
  2700. cli.set_digest_auth("hello", "world");
  2701. auto res = cli.Get("/x");
  2702. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2703. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  2704. }
  2705. TEST(DigestAuthTest, ChallengeMissingRealmAndNonceDoesNotCrash) {
  2706. run_digest_challenge_missing_field_test("Digest qop=\"auth\"");
  2707. }
  2708. TEST(DigestAuthTest, ChallengeMissingNonceDoesNotCrash) {
  2709. run_digest_challenge_missing_field_test("Digest realm=\"r\", qop=\"auth\"");
  2710. }
  2711. TEST(DigestAuthTest, ChallengeMissingRealmDoesNotCrash) {
  2712. run_digest_challenge_missing_field_test("Digest nonce=\"n\", qop=\"auth\"");
  2713. }
  2714. #endif
  2715. TEST(SpecifyServerIPAddressTest, AnotherHostname_Online) {
  2716. auto host = "google.com";
  2717. auto another_host = "example.com";
  2718. auto wrong_ip = "0.0.0.0";
  2719. #ifdef CPPHTTPLIB_SSL_ENABLED
  2720. SSLClient cli(host);
  2721. #else
  2722. Client cli(host);
  2723. #endif
  2724. cli.set_hostname_addr_map({{another_host, wrong_ip}});
  2725. auto res = cli.Get("/");
  2726. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2727. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  2728. }
  2729. TEST(SpecifyServerIPAddressTest, RealHostname_Online) {
  2730. auto host = "google.com";
  2731. auto wrong_ip = "0.0.0.0";
  2732. #ifdef CPPHTTPLIB_SSL_ENABLED
  2733. SSLClient cli(host);
  2734. #else
  2735. Client cli(host);
  2736. #endif
  2737. cli.set_hostname_addr_map({{host, wrong_ip}});
  2738. auto res = cli.Get("/");
  2739. ASSERT_TRUE(!res);
  2740. EXPECT_EQ(Error::Connection, res.error());
  2741. }
  2742. TEST(SpecifyServerIPAddressTest, HostnameAsAddrMapValue) {
  2743. // A mapped value that is not an IP literal must be resolved. "localhost"
  2744. // resolves from the hosts file, so this test needs no external DNS.
  2745. // "target.invalid" (RFC 6761) is only a map key and the Host header value.
  2746. auto host = "target.invalid";
  2747. Server svr;
  2748. std::string received_host;
  2749. svr.Get("/hi", [&](const Request &req, Response &res) {
  2750. received_host = req.get_header_value("Host");
  2751. res.set_content("Hello World!", "text/plain");
  2752. });
  2753. auto port = svr.bind_to_any_port(HOST);
  2754. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2755. auto se = detail::scope_exit([&] {
  2756. svr.stop();
  2757. thread.join();
  2758. ASSERT_FALSE(svr.is_running());
  2759. });
  2760. svr.wait_until_ready();
  2761. Client cli(host, port);
  2762. cli.set_hostname_addr_map({{host, HOST}});
  2763. auto res = cli.Get("/hi");
  2764. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2765. EXPECT_EQ(StatusCode::OK_200, res->status);
  2766. // The mapping only redirects the connection; the identity stays host_.
  2767. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  2768. }
  2769. TEST(SpecifyServerIPAddressTest, IPAddressAsAddrMapValue) {
  2770. // A mapped value that is an IP literal keeps the AI_NUMERICHOST path.
  2771. auto host = "target.invalid";
  2772. Server svr;
  2773. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2774. res.set_content("Hello World!", "text/plain");
  2775. });
  2776. auto port = svr.bind_to_any_port("127.0.0.1");
  2777. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2778. auto se = detail::scope_exit([&] {
  2779. svr.stop();
  2780. thread.join();
  2781. ASSERT_FALSE(svr.is_running());
  2782. });
  2783. svr.wait_until_ready();
  2784. Client cli(host, port);
  2785. cli.set_hostname_addr_map({{host, "127.0.0.1"}});
  2786. auto res = cli.Get("/hi");
  2787. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2788. EXPECT_EQ(StatusCode::OK_200, res->status);
  2789. }
  2790. TEST(SpecifyServerIPAddressTest, EmptyAddrMapValueIsIgnored) {
  2791. // An empty mapped value must leave host_ as the connection target. Without
  2792. // that guard the empty value would become the host argument, getaddrinfo
  2793. // would be called with a null node, and (no AI_PASSIVE) it would resolve to
  2794. // loopback - silently connecting somewhere the caller never asked for.
  2795. // The server listens on loopback, so such a fallback would succeed and is
  2796. // therefore observable as a failure of this test.
  2797. auto blackhole = "192.0.2.1"; // TEST-NET-1, never routable
  2798. Server svr;
  2799. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  2800. res.set_content("Hello World!", "text/plain");
  2801. });
  2802. auto port = svr.bind_to_any_port(HOST);
  2803. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  2804. auto se = detail::scope_exit([&] {
  2805. svr.stop();
  2806. thread.join();
  2807. ASSERT_FALSE(svr.is_running());
  2808. });
  2809. svr.wait_until_ready();
  2810. Client cli(blackhole, port);
  2811. cli.set_hostname_addr_map({{blackhole, ""}});
  2812. cli.set_connection_timeout(1);
  2813. auto res = cli.Get("/hi");
  2814. EXPECT_FALSE(res) << "empty mapping must not redirect to loopback";
  2815. }
  2816. TEST(AbsoluteRedirectTest, Redirect_Online) {
  2817. auto host = "httpbingo.org";
  2818. auto path = std::string{"/absolute-redirect/3"};
  2819. #ifdef CPPHTTPLIB_SSL_ENABLED
  2820. SSLClient cli(host);
  2821. #else
  2822. Client cli(host);
  2823. #endif
  2824. cli.set_follow_location(true);
  2825. auto res = cli.Get(path);
  2826. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2827. EXPECT_EQ(StatusCode::OK_200, res->status);
  2828. }
  2829. TEST(RedirectTest, Redirect_Online) {
  2830. auto host = "httpbingo.org";
  2831. auto path = std::string{"/redirect/3"};
  2832. #ifdef CPPHTTPLIB_SSL_ENABLED
  2833. SSLClient cli(host);
  2834. #else
  2835. Client cli(host);
  2836. #endif
  2837. cli.set_follow_location(true);
  2838. auto res = cli.Get(path);
  2839. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2840. EXPECT_EQ(StatusCode::OK_200, res->status);
  2841. }
  2842. TEST(RelativeRedirectTest, Redirect_Online) {
  2843. auto host = "httpbingo.org";
  2844. auto path = std::string{"/relative-redirect/3"};
  2845. #ifdef CPPHTTPLIB_SSL_ENABLED
  2846. SSLClient cli(host);
  2847. #else
  2848. Client cli(host);
  2849. #endif
  2850. cli.set_follow_location(true);
  2851. auto res = cli.Get(path);
  2852. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2853. EXPECT_EQ(StatusCode::OK_200, res->status);
  2854. }
  2855. TEST(TooManyRedirectTest, Redirect_Online) {
  2856. auto host = "httpbingo.org";
  2857. auto path = std::string{"/redirect/21"};
  2858. #ifdef CPPHTTPLIB_SSL_ENABLED
  2859. SSLClient cli(host);
  2860. #else
  2861. Client cli(host);
  2862. #endif
  2863. cli.set_follow_location(true);
  2864. auto res = cli.Get(path);
  2865. ASSERT_TRUE(!res);
  2866. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  2867. }
  2868. #ifdef CPPHTTPLIB_SSL_ENABLED
  2869. TEST(YahooRedirectTest, Redirect_Online) {
  2870. Client cli("yahoo.com");
  2871. auto res = cli.Get("/");
  2872. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2873. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  2874. cli.set_follow_location(true);
  2875. res = cli.Get("/");
  2876. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2877. EXPECT_EQ(StatusCode::OK_200, res->status);
  2878. EXPECT_EQ("https://www.yahoo.com/", res->location);
  2879. }
  2880. // Previously "nghttp2.org" "/httpbin/redirect-to"
  2881. #define REDIR_HOST "httpbingo.org"
  2882. #define REDIR_PATH "/redirect-to"
  2883. TEST(HttpsToHttpRedirectTest, Redirect_Online) {
  2884. SSLClient cli(REDIR_HOST);
  2885. cli.set_follow_location(true);
  2886. auto res =
  2887. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  2888. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2889. EXPECT_EQ(StatusCode::OK_200, res->status);
  2890. }
  2891. TEST(HttpsToHttpRedirectTest2, Redirect_Online) {
  2892. SSLClient cli(REDIR_HOST);
  2893. cli.set_follow_location(true);
  2894. Params params;
  2895. params.emplace("url", "http://example.com");
  2896. params.emplace("status_code", "302");
  2897. auto res = cli.Get(REDIR_PATH, params, Headers{});
  2898. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2899. EXPECT_EQ(StatusCode::OK_200, res->status);
  2900. }
  2901. TEST(HttpsToHttpRedirectTest3, Redirect_Online) {
  2902. SSLClient cli(REDIR_HOST);
  2903. cli.set_follow_location(true);
  2904. Params params;
  2905. params.emplace("url", "http://example.com");
  2906. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  2907. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2908. EXPECT_EQ(StatusCode::OK_200, res->status);
  2909. }
  2910. TEST(UrlWithSpace, Redirect_Online) {
  2911. SSLClient cli("edge.forgecdn.net");
  2912. cli.set_follow_location(true);
  2913. auto res = cli.Get("/files/2595/310/Neat 1.4-17.jar");
  2914. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2915. EXPECT_EQ(StatusCode::OK_200, res->status);
  2916. EXPECT_EQ(18527U, res->get_header_value_u64("Content-Length"));
  2917. }
  2918. #endif
  2919. #if !defined(_WIN32) && !defined(_WIN64)
  2920. TEST(ReceiveSignals, Signal) {
  2921. auto setupSignalHandlers = []() {
  2922. struct sigaction act;
  2923. sigemptyset(&act.sa_mask);
  2924. act.sa_flags = SA_SIGINFO;
  2925. act.sa_sigaction = [](int sig, siginfo_t *, void *) {
  2926. switch (sig) {
  2927. case SIGINT:
  2928. default: break;
  2929. }
  2930. };
  2931. ::sigaction(SIGINT, &act, nullptr);
  2932. };
  2933. Server svr;
  2934. int port = 0;
  2935. auto thread = std::thread([&]() {
  2936. setupSignalHandlers();
  2937. port = svr.bind_to_any_port(HOST);
  2938. svr.listen_after_bind();
  2939. });
  2940. auto se = detail::scope_exit([&] {
  2941. svr.stop();
  2942. thread.join();
  2943. ASSERT_FALSE(svr.is_running());
  2944. });
  2945. svr.wait_until_ready();
  2946. ASSERT_TRUE(svr.is_running());
  2947. pthread_kill(thread.native_handle(), SIGINT);
  2948. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  2949. ASSERT_TRUE(svr.is_running());
  2950. }
  2951. #endif
  2952. TEST(RedirectToDifferentPort, Redirect) {
  2953. Server svr1;
  2954. svr1.Get("/1", [&](const Request & /*req*/, Response &res) {
  2955. res.set_content("Hello World!", "text/plain");
  2956. });
  2957. int svr1_port = 0;
  2958. auto thread1 = std::thread([&]() {
  2959. svr1_port = svr1.bind_to_any_port(HOST);
  2960. svr1.listen_after_bind();
  2961. });
  2962. Server svr2;
  2963. svr2.Get("/2", [&](const Request & /*req*/, Response &res) {
  2964. res.set_redirect("http://localhost:" + std::to_string(svr1_port) + "/1");
  2965. });
  2966. int svr2_port = 0;
  2967. auto thread2 = std::thread([&]() {
  2968. svr2_port = svr2.bind_to_any_port(HOST);
  2969. svr2.listen_after_bind();
  2970. });
  2971. auto se = detail::scope_exit([&] {
  2972. svr2.stop();
  2973. thread2.join();
  2974. svr1.stop();
  2975. thread1.join();
  2976. ASSERT_FALSE(svr2.is_running());
  2977. ASSERT_FALSE(svr1.is_running());
  2978. });
  2979. svr1.wait_until_ready();
  2980. svr2.wait_until_ready();
  2981. Client cli("localhost", svr2_port);
  2982. cli.set_follow_location(true);
  2983. auto res = cli.Get("/2");
  2984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  2985. EXPECT_EQ(StatusCode::OK_200, res->status);
  2986. EXPECT_EQ("Hello World!", res->body);
  2987. }
  2988. static void
  2989. TestDoNotForwardCredentialsOnRedirect(std::function<void(Client &)> set_auth) {
  2990. Server svr1;
  2991. std::string captured_authorization;
  2992. svr1.Get("/target", [&](const Request &req, Response &res) {
  2993. captured_authorization = req.get_header_value("Authorization");
  2994. res.set_content("OK", "text/plain");
  2995. });
  2996. int svr1_port = 0;
  2997. auto thread1 = std::thread([&]() {
  2998. svr1_port = svr1.bind_to_any_port(HOST);
  2999. svr1.listen_after_bind();
  3000. });
  3001. Server svr2;
  3002. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3003. res.set_redirect(
  3004. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3005. });
  3006. int svr2_port = 0;
  3007. auto thread2 = std::thread([&]() {
  3008. svr2_port = svr2.bind_to_any_port(HOST);
  3009. svr2.listen_after_bind();
  3010. });
  3011. auto se = detail::scope_exit([&] {
  3012. svr2.stop();
  3013. thread2.join();
  3014. svr1.stop();
  3015. thread1.join();
  3016. ASSERT_FALSE(svr2.is_running());
  3017. ASSERT_FALSE(svr1.is_running());
  3018. });
  3019. svr1.wait_until_ready();
  3020. svr2.wait_until_ready();
  3021. Client cli("localhost", svr2_port);
  3022. cli.set_follow_location(true);
  3023. set_auth(cli);
  3024. auto res = cli.Get("/redir");
  3025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3026. EXPECT_EQ(StatusCode::OK_200, res->status);
  3027. // RFC 9110: credentials MUST NOT be forwarded to a different host
  3028. EXPECT_TRUE(captured_authorization.empty());
  3029. }
  3030. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBasicAuth) {
  3031. TestDoNotForwardCredentialsOnRedirect(
  3032. [](Client &cli) { cli.set_basic_auth("admin", "secret"); });
  3033. }
  3034. TEST(RedirectToDifferentPort, DoNotForwardCredentialsBearerToken) {
  3035. TestDoNotForwardCredentialsOnRedirect(
  3036. [](Client &cli) { cli.set_bearer_token_auth("my-secret-token"); });
  3037. }
  3038. TEST(RedirectToDifferentPort, DoNotForwardCookie) {
  3039. Server svr1;
  3040. std::string captured_cookie;
  3041. bool target_hit = false;
  3042. svr1.Get("/target", [&](const Request &req, Response &res) {
  3043. captured_cookie = req.get_header_value("Cookie");
  3044. target_hit = true;
  3045. res.set_content("OK", "text/plain");
  3046. });
  3047. int svr1_port = 0;
  3048. auto thread1 = std::thread([&]() {
  3049. svr1_port = svr1.bind_to_any_port(HOST);
  3050. svr1.listen_after_bind();
  3051. });
  3052. Server svr2;
  3053. svr2.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3054. res.set_redirect(
  3055. "http://localhost:" + std::to_string(svr1_port) + "/target", 302);
  3056. });
  3057. int svr2_port = 0;
  3058. auto thread2 = std::thread([&]() {
  3059. svr2_port = svr2.bind_to_any_port(HOST);
  3060. svr2.listen_after_bind();
  3061. });
  3062. auto se = detail::scope_exit([&] {
  3063. svr2.stop();
  3064. thread2.join();
  3065. svr1.stop();
  3066. thread1.join();
  3067. ASSERT_FALSE(svr2.is_running());
  3068. ASSERT_FALSE(svr1.is_running());
  3069. });
  3070. svr1.wait_until_ready();
  3071. svr2.wait_until_ready();
  3072. Client cli("localhost", svr2_port);
  3073. cli.set_follow_location(true);
  3074. Headers headers = {{"Cookie", "session_id=SECRET; auth=PRIVATE"}};
  3075. auto res = cli.Get("/redir", headers);
  3076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3077. EXPECT_EQ(StatusCode::OK_200, res->status);
  3078. EXPECT_TRUE(target_hit);
  3079. // Cookie MUST NOT be forwarded to a different host (GHSA-22mf-w2v3-r2jv)
  3080. EXPECT_TRUE(captured_cookie.empty());
  3081. }
  3082. TEST(RedirectToSamePort, ForwardCookie) {
  3083. // A same-origin redirect (same scheme/host/port) should preserve the Cookie
  3084. // header so that ordinary session flows keep working.
  3085. Server svr;
  3086. std::string captured_cookie;
  3087. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3088. res.set_redirect("/target", 302);
  3089. });
  3090. svr.Get("/target", [&](const Request &req, Response &res) {
  3091. captured_cookie = req.get_header_value("Cookie");
  3092. res.set_content("OK", "text/plain");
  3093. });
  3094. auto port = svr.bind_to_any_port(HOST);
  3095. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3096. auto se = detail::scope_exit([&] {
  3097. svr.stop();
  3098. thread.join();
  3099. ASSERT_FALSE(svr.is_running());
  3100. });
  3101. svr.wait_until_ready();
  3102. Client cli(HOST, port);
  3103. cli.set_follow_location(true);
  3104. Headers headers = {{"Cookie", "session_id=SECRET"}};
  3105. auto res = cli.Get("/redir", headers);
  3106. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3107. EXPECT_EQ(StatusCode::OK_200, res->status);
  3108. EXPECT_EQ("session_id=SECRET", captured_cookie);
  3109. }
  3110. TEST(RedirectToDifferentPort, OverflowPortNumber) {
  3111. Server svr;
  3112. svr.Get("/redir", [&](const Request & /*req*/, Response &res) {
  3113. // Port number that overflows int — should not crash
  3114. res.set_redirect("http://localhost:99999999999999999999/target");
  3115. });
  3116. auto port = svr.bind_to_any_port(HOST);
  3117. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3118. auto se = detail::scope_exit([&] {
  3119. svr.stop();
  3120. thread.join();
  3121. ASSERT_FALSE(svr.is_running());
  3122. });
  3123. svr.wait_until_ready();
  3124. Client cli(HOST, port);
  3125. cli.set_follow_location(true);
  3126. auto res = cli.Get("/redir");
  3127. // Should fail gracefully, not crash (no valid response due to bad port)
  3128. EXPECT_FALSE(res);
  3129. }
  3130. TEST(RedirectFromPageWithContent, Redirect) {
  3131. Server svr;
  3132. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3133. res.set_content("___", "text/plain");
  3134. res.set_redirect("/2");
  3135. });
  3136. svr.Get("/2", [&](const Request & /*req*/, Response &res) {
  3137. res.set_content("Hello World!", "text/plain");
  3138. });
  3139. auto th = std::thread([&]() { svr.listen("localhost", PORT); });
  3140. auto se = detail::scope_exit([&] {
  3141. svr.stop();
  3142. th.join();
  3143. ASSERT_FALSE(svr.is_running());
  3144. });
  3145. svr.wait_until_ready();
  3146. {
  3147. Client cli("localhost", PORT);
  3148. cli.set_follow_location(true);
  3149. std::string body;
  3150. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3151. body.append(data, data_length);
  3152. return true;
  3153. });
  3154. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3155. EXPECT_EQ(StatusCode::OK_200, res->status);
  3156. EXPECT_EQ("Hello World!", body);
  3157. }
  3158. {
  3159. Client cli("localhost", PORT);
  3160. std::string body;
  3161. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3162. body.append(data, data_length);
  3163. return true;
  3164. });
  3165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3166. EXPECT_EQ(StatusCode::Found_302, res->status);
  3167. EXPECT_EQ("___", body);
  3168. }
  3169. }
  3170. TEST(RedirectFromPageWithContentIP6, Redirect) {
  3171. Server svr;
  3172. auto port_str = std::to_string(PORT);
  3173. auto redirect_url = "http://[::1]:" + port_str + "/2";
  3174. auto expected_host = "[::1]:" + port_str;
  3175. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3176. res.set_content("___", "text/plain");
  3177. // res.set_redirect("/2");
  3178. res.set_redirect(redirect_url);
  3179. });
  3180. svr.Get("/2", [&](const Request &req, Response &res) {
  3181. auto host_header = req.headers.find("Host");
  3182. ASSERT_TRUE(host_header != req.headers.end());
  3183. EXPECT_EQ(expected_host, host_header->second);
  3184. res.set_content("Hello World!", "text/plain");
  3185. });
  3186. auto th = std::thread([&]() { svr.listen("::1", PORT); });
  3187. auto se = detail::scope_exit([&] {
  3188. svr.stop();
  3189. th.join();
  3190. ASSERT_FALSE(svr.is_running());
  3191. });
  3192. // When IPV6 support isn't available svr.listen("::1", PORT) never
  3193. // actually starts anything, so the condition !svr.is_running() will
  3194. // always remain true, and the loop never stops.
  3195. // This basically counts how many milliseconds have passed since the
  3196. // call to svr.listen(), and if after 5 seconds nothing started yet
  3197. // aborts the test.
  3198. for (unsigned int milliseconds = 0; !svr.is_running(); milliseconds++) {
  3199. std::this_thread::sleep_for(std::chrono::milliseconds(1));
  3200. ASSERT_LT(milliseconds, 5000U);
  3201. }
  3202. {
  3203. Client cli("::1", PORT);
  3204. cli.set_follow_location(true);
  3205. std::string body;
  3206. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3207. body.append(data, data_length);
  3208. return true;
  3209. });
  3210. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3211. EXPECT_EQ(StatusCode::OK_200, res->status);
  3212. EXPECT_EQ("Hello World!", body);
  3213. }
  3214. {
  3215. Client cli("::1", PORT);
  3216. std::string body;
  3217. auto res = cli.Get("/1", [&](const char *data, size_t data_length) {
  3218. body.append(data, data_length);
  3219. return true;
  3220. });
  3221. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3222. EXPECT_EQ(StatusCode::Found_302, res->status);
  3223. EXPECT_EQ("___", body);
  3224. }
  3225. }
  3226. TEST(PathUrlEncodeTest, PathUrlEncode) {
  3227. Server svr;
  3228. svr.Get("/foo", [](const Request &req, Response &res) {
  3229. auto a = req.params.find("a");
  3230. if (a != req.params.end()) {
  3231. res.set_content((*a).second, "text/plain");
  3232. res.status = StatusCode::OK_200;
  3233. } else {
  3234. res.status = StatusCode::BadRequest_400;
  3235. }
  3236. });
  3237. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3238. auto se = detail::scope_exit([&] {
  3239. svr.stop();
  3240. thread.join();
  3241. ASSERT_FALSE(svr.is_running());
  3242. });
  3243. svr.wait_until_ready();
  3244. {
  3245. Client cli(HOST, PORT);
  3246. cli.set_path_encode(false);
  3247. auto res = cli.Get("/foo?a=explicitly+encoded");
  3248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3249. EXPECT_EQ(StatusCode::OK_200, res->status);
  3250. // This expects it back with a space, as the `+` won't have been
  3251. // url-encoded, and server-side the params get decoded turning `+`
  3252. // into spaces.
  3253. EXPECT_EQ("explicitly encoded", res->body);
  3254. }
  3255. }
  3256. TEST(PathUrlEncodeTest, PreEncodedQueryNotReencoded) {
  3257. // When path encoding is disabled the client must transmit the supplied
  3258. // query verbatim. Decoding-then-re-encoding it (the previous behavior)
  3259. // corrupts pre-encoded binary payloads: e.g. `%20` would be turned into
  3260. // `+`, which a strict RFC 3986 server decodes back as `+` (0x2B) rather
  3261. // than a space (0x20). Assert on the raw wire target to catch this.
  3262. Server svr;
  3263. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3264. svr.Get("/foo", [&](const Request &req, Response &res) {
  3265. EXPECT_EQ(expected_target, req.target);
  3266. res.status = StatusCode::OK_200;
  3267. });
  3268. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3269. auto se = detail::scope_exit([&] {
  3270. svr.stop();
  3271. thread.join();
  3272. ASSERT_FALSE(svr.is_running());
  3273. });
  3274. svr.wait_until_ready();
  3275. {
  3276. Client cli(HOST, PORT);
  3277. cli.set_path_encode(false);
  3278. auto res = cli.Get(expected_target.c_str());
  3279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3280. EXPECT_EQ(StatusCode::OK_200, res->status);
  3281. }
  3282. }
  3283. TEST(PathUrlEncodeTest, StreamingMatchesBufferedTarget) {
  3284. // `open_stream()` used to skip the path encoding that the buffered send
  3285. // path applies, so the same `path` produced different bytes in the request
  3286. // line depending on which API was used. Assert the two agree.
  3287. Server svr;
  3288. std::string target;
  3289. svr.Get(".*", [&](const Request &req, Response &res) {
  3290. target = req.target;
  3291. res.status = StatusCode::OK_200;
  3292. });
  3293. auto port = svr.bind_to_any_port(HOST);
  3294. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3295. auto se = detail::scope_exit([&] {
  3296. svr.stop();
  3297. thread.join();
  3298. ASSERT_FALSE(svr.is_running());
  3299. });
  3300. svr.wait_until_ready();
  3301. struct {
  3302. const char *path;
  3303. const char *expected;
  3304. } cases[] = {
  3305. {"/a b?x=1", "/a%20b?x=1"},
  3306. {"/\xE6\x97\xA5\xE6\x9C\xAC", "/%E6%97%A5%E6%9C%AC"},
  3307. {"/a,b;c+d", "/a%2Cb%3Bc%2Bd"},
  3308. };
  3309. for (const auto &c : cases) {
  3310. Client cli(HOST, port);
  3311. target.clear();
  3312. auto res = cli.Get(c.path);
  3313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3314. EXPECT_EQ(c.expected, target) << "buffered path: " << c.path;
  3315. auto buffered_target = target;
  3316. target.clear();
  3317. auto handle = cli.open_stream("GET", c.path);
  3318. EXPECT_TRUE(handle.is_valid())
  3319. << "streaming path: " << c.path << ", " << to_string(handle.error);
  3320. EXPECT_EQ(buffered_target, target) << "streaming path: " << c.path;
  3321. }
  3322. }
  3323. TEST(PathUrlEncodeTest, StreamingPreEncodedQueryNotReencoded) {
  3324. // The `set_path_encode(false)` contract — transmit the supplied target
  3325. // verbatim — must hold for the streaming API too.
  3326. Server svr;
  3327. const std::string expected_target = "/foo?q=a%20b%2Cc%24d%3Bx&a=%00%FF";
  3328. std::string target;
  3329. svr.Get("/foo", [&](const Request &req, Response &res) {
  3330. target = req.target;
  3331. res.status = StatusCode::OK_200;
  3332. });
  3333. auto port = svr.bind_to_any_port(HOST);
  3334. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3335. auto se = detail::scope_exit([&] {
  3336. svr.stop();
  3337. thread.join();
  3338. ASSERT_FALSE(svr.is_running());
  3339. });
  3340. svr.wait_until_ready();
  3341. {
  3342. Client cli(HOST, port);
  3343. cli.set_path_encode(false);
  3344. auto handle = cli.open_stream("GET", expected_target);
  3345. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3346. EXPECT_EQ(expected_target, target);
  3347. }
  3348. }
  3349. TEST(PathUrlEncodeTest, StreamingCRLFInTargetIsEncoded) {
  3350. // With path encoding enabled a CR/LF in the target is percent-encoded
  3351. // rather than rejected, matching the buffered send path. The CR/LF guard in
  3352. // write_request_line still backstops `set_path_encode(false)`, which is
  3353. // covered by StreamingCRLFRejectedWhenPathEncodeDisabled.
  3354. Server svr;
  3355. // Captured before routing: the decoded path contains a newline, which a
  3356. // `.*` handler pattern would not match (`.` excludes `\n` in std::regex).
  3357. std::string target;
  3358. svr.set_pre_routing_handler([&](const Request &req, Response &res) {
  3359. target = req.target;
  3360. res.status = StatusCode::OK_200;
  3361. return Server::HandlerResponse::Handled;
  3362. });
  3363. auto port = svr.bind_to_any_port(HOST);
  3364. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3365. auto se = detail::scope_exit([&] {
  3366. svr.stop();
  3367. thread.join();
  3368. ASSERT_FALSE(svr.is_running());
  3369. });
  3370. svr.wait_until_ready();
  3371. {
  3372. Client cli(HOST, port);
  3373. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3374. EXPECT_TRUE(handle.is_valid()) << to_string(handle.error);
  3375. EXPECT_EQ("/a%0D%0AX-Injected:%201", target);
  3376. }
  3377. }
  3378. TEST(PathUrlEncodeTest, StreamingCRLFRejectedWhenPathEncodeDisabled) {
  3379. // Nothing may reach the wire: a raw CR/LF target would split the request
  3380. // line and inject headers.
  3381. Server svr;
  3382. // Pre-routing so that "not called" means nothing reached the server at all,
  3383. // rather than merely failing to match a handler pattern.
  3384. auto handler_called = false;
  3385. svr.set_pre_routing_handler([&](const Request & /*req*/, Response &res) {
  3386. handler_called = true;
  3387. res.status = StatusCode::OK_200;
  3388. return Server::HandlerResponse::Handled;
  3389. });
  3390. auto port = svr.bind_to_any_port(HOST);
  3391. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3392. auto se = detail::scope_exit([&] {
  3393. svr.stop();
  3394. thread.join();
  3395. ASSERT_FALSE(svr.is_running());
  3396. });
  3397. svr.wait_until_ready();
  3398. {
  3399. Client cli(HOST, port);
  3400. cli.set_path_encode(false);
  3401. auto handle = cli.open_stream("GET", "/a\r\nX-Injected: 1");
  3402. EXPECT_FALSE(handle.is_valid());
  3403. EXPECT_EQ(Error::Write, handle.error);
  3404. EXPECT_FALSE(handler_called);
  3405. }
  3406. }
  3407. TEST(PathUrlEncodeTest, RequestParamsBranchSelection) {
  3408. // Which of the two branches runs is decided by whether the query component
  3409. // is empty, not by whether `req.path` contains a `?`: a trailing `?` yields
  3410. // an empty query and must still fall back to building one from
  3411. // `req.params`, while a non-empty query must win over `req.params`.
  3412. Server svr;
  3413. std::string target;
  3414. svr.Get("/foo", [&](const Request &req, Response &res) {
  3415. target = req.target;
  3416. res.status = StatusCode::OK_200;
  3417. });
  3418. auto port = svr.bind_to_any_port(HOST);
  3419. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  3420. auto se = detail::scope_exit([&] {
  3421. svr.stop();
  3422. thread.join();
  3423. ASSERT_FALSE(svr.is_running());
  3424. });
  3425. svr.wait_until_ready();
  3426. {
  3427. // Trailing `?` -> empty query component -> `req.params` is used.
  3428. Client cli(HOST, port);
  3429. Request req;
  3430. req.method = "GET";
  3431. req.path = "/foo?";
  3432. req.params.emplace("a", "1");
  3433. target.clear();
  3434. auto res = cli.send(req);
  3435. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3436. EXPECT_EQ("/foo?a=1", target);
  3437. }
  3438. {
  3439. // Non-empty query in `req.path` -> `req.params` is not appended.
  3440. Client cli(HOST, port);
  3441. Request req;
  3442. req.method = "GET";
  3443. req.path = "/foo?b=2";
  3444. req.params.emplace("a", "1");
  3445. target.clear();
  3446. auto res = cli.send(req);
  3447. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3448. EXPECT_EQ("/foo?b=2", target);
  3449. }
  3450. }
  3451. TEST(PathUrlEncodeTest, IncludePercentEncodingLF) {
  3452. Server svr;
  3453. svr.Get("/", [](const Request &req, Response &) {
  3454. EXPECT_EQ("\x0A", req.get_param_value("something"));
  3455. });
  3456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3457. auto se = detail::scope_exit([&] {
  3458. svr.stop();
  3459. thread.join();
  3460. ASSERT_FALSE(svr.is_running());
  3461. });
  3462. svr.wait_until_ready();
  3463. {
  3464. Client cli(HOST, PORT);
  3465. cli.set_path_encode(false);
  3466. auto res = cli.Get("/?something=%0A");
  3467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3468. EXPECT_EQ(StatusCode::OK_200, res->status);
  3469. }
  3470. }
  3471. TEST(BindServerTest, BindDualStack) {
  3472. Server svr;
  3473. svr.Get("/1", [&](const Request & /*req*/, Response &res) {
  3474. res.set_content("Hello World!", "text/plain");
  3475. });
  3476. auto thread = std::thread([&]() { svr.listen("::", PORT); });
  3477. auto se = detail::scope_exit([&] {
  3478. svr.stop();
  3479. thread.join();
  3480. ASSERT_FALSE(svr.is_running());
  3481. });
  3482. svr.wait_until_ready();
  3483. {
  3484. Client cli("127.0.0.1", PORT);
  3485. auto res = cli.Get("/1");
  3486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3487. EXPECT_EQ(StatusCode::OK_200, res->status);
  3488. EXPECT_EQ("Hello World!", res->body);
  3489. }
  3490. {
  3491. Client cli("::1", PORT);
  3492. auto res = cli.Get("/1");
  3493. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3494. EXPECT_EQ(StatusCode::OK_200, res->status);
  3495. EXPECT_EQ("Hello World!", res->body);
  3496. }
  3497. }
  3498. TEST(BindServerTest, BindAndListenSeparately) {
  3499. Server svr;
  3500. int port = svr.bind_to_any_port("0.0.0.0");
  3501. ASSERT_TRUE(svr.is_valid());
  3502. ASSERT_TRUE(port > 0);
  3503. svr.stop();
  3504. }
  3505. // Reports whether anything is still listening on a loopback port. A plain
  3506. // connect() is used instead of a Client request because a socket left bound by
  3507. // mistake accepts the connection into its backlog and never answers, which
  3508. // would hang the test instead of failing it.
  3509. static bool is_loopback_port_accepting(int port) {
  3510. sockaddr_in addr{};
  3511. addr.sin_family = AF_INET;
  3512. addr.sin_port = htons(static_cast<uint16_t>(port));
  3513. addr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  3514. socket_t sock = ::socket(AF_INET, SOCK_STREAM, 0);
  3515. EXPECT_NE(sock, INVALID_SOCKET);
  3516. if (sock == INVALID_SOCKET) { return false; }
  3517. auto ret = ::connect(sock, reinterpret_cast<sockaddr *>(&addr),
  3518. static_cast<socklen_t>(sizeof(addr)));
  3519. detail::close_socket(sock);
  3520. return ret == 0;
  3521. }
  3522. TEST(BindServerTest, StopClosesBoundSocketWithoutListen) {
  3523. Server svr;
  3524. auto port = svr.bind_to_any_port("127.0.0.1");
  3525. ASSERT_TRUE(port > 0);
  3526. svr.stop();
  3527. // bind_to_any_port() already called listen(2), so until stop() closed the
  3528. // descriptor the port kept accepting connections into the backlog. ASSERT
  3529. // rather than EXPECT: with the socket still open, the listen_after_bind()
  3530. // below blocks forever in the accept loop.
  3531. ASSERT_FALSE(is_loopback_port_accepting(port));
  3532. // Nothing is left to accept on, so listen_after_bind() must report failure
  3533. // instead of returning success without ever serving.
  3534. EXPECT_FALSE(svr.listen_after_bind());
  3535. // The failed listen marks the server decommissioned, so a waiter returns
  3536. // instead of spinning forever.
  3537. svr.wait_until_ready();
  3538. }
  3539. #ifdef CPPHTTPLIB_SSL_ENABLED
  3540. TEST(BindServerTest, BindAndListenSeparatelySSL) {
  3541. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3542. CLIENT_CA_CERT_DIR);
  3543. int port = svr.bind_to_any_port("0.0.0.0");
  3544. ASSERT_TRUE(svr.is_valid());
  3545. ASSERT_TRUE(port > 0);
  3546. svr.stop();
  3547. }
  3548. // SSLServer::is_valid() overrides the base version, so it has to chain to it
  3549. // or a rejected CustomRoute() registration would not stop the server binding.
  3550. TEST(BindServerTest, SSLServerIsInvalidAfterRejectedCustomRoute) {
  3551. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  3552. CLIENT_CA_CERT_DIR);
  3553. ASSERT_TRUE(svr.is_valid());
  3554. svr.CustomRoute("GET", "/x", [](const Request &, Response &) {});
  3555. EXPECT_FALSE(svr.is_valid());
  3556. EXPECT_TRUE(svr.bind_to_any_port("0.0.0.0") < 0);
  3557. }
  3558. TEST(BindServerTest, BindAndListenSeparatelySSLEncryptedKey) {
  3559. SSLServer svr(SERVER_ENCRYPTED_CERT_FILE, SERVER_ENCRYPTED_PRIVATE_KEY_FILE,
  3560. nullptr, nullptr, SERVER_ENCRYPTED_PRIVATE_KEY_PASS);
  3561. int port = svr.bind_to_any_port("0.0.0.0");
  3562. ASSERT_TRUE(svr.is_valid());
  3563. ASSERT_TRUE(port > 0);
  3564. svr.stop();
  3565. }
  3566. TEST(BindServerTest, UpdateCertsPem) {
  3567. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3568. int port = svr.bind_to_any_port("0.0.0.0");
  3569. ASSERT_TRUE(svr.is_valid());
  3570. ASSERT_TRUE(port > 0);
  3571. // Read PEM files
  3572. std::string cert_pem, key_pem, ca_pem;
  3573. read_file(SERVER_CERT_FILE, cert_pem);
  3574. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3575. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3576. // Update server certificates using PEM API
  3577. ASSERT_TRUE(
  3578. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3579. ASSERT_TRUE(svr.is_valid());
  3580. svr.stop();
  3581. }
  3582. TEST(SSLClientServerTest, UpdateCertsPemWithClientAuth) {
  3583. // Start server with client CA (enables client auth)
  3584. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  3585. ASSERT_TRUE(svr.is_valid());
  3586. bool handler_called = false;
  3587. svr.Get("/test", [&](const Request &req, Response &res) {
  3588. handler_called = true;
  3589. // Verify client certificate is present
  3590. auto cert = req.peer_cert();
  3591. EXPECT_TRUE(static_cast<bool>(cert));
  3592. res.set_content("ok", "text/plain");
  3593. });
  3594. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  3595. auto se = detail::scope_exit([&] {
  3596. svr.stop();
  3597. t.join();
  3598. ASSERT_FALSE(svr.is_running());
  3599. });
  3600. svr.wait_until_ready();
  3601. // Read PEM files
  3602. std::string cert_pem, key_pem, ca_pem;
  3603. read_file(SERVER_CERT_FILE, cert_pem);
  3604. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  3605. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  3606. // Update server certificates and client CA using PEM API while server running
  3607. ASSERT_TRUE(
  3608. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str()));
  3609. // Connect with client certificate
  3610. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  3611. cli.enable_server_certificate_verification(false);
  3612. cli.set_connection_timeout(30);
  3613. auto res = cli.Get("/test");
  3614. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3615. ASSERT_EQ(StatusCode::OK_200, res->status);
  3616. ASSERT_TRUE(handler_called);
  3617. EXPECT_EQ("ok", res->body);
  3618. }
  3619. #endif
  3620. TEST(ErrorHandlerTest, ContentLength) {
  3621. Server svr;
  3622. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3623. res.status = StatusCode::OK_200;
  3624. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3625. "text/html"); // <= Content-Length still 13
  3626. });
  3627. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3628. res.set_content("Hello World!\n", "text/plain");
  3629. res.status = 524;
  3630. });
  3631. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3632. auto se = detail::scope_exit([&] {
  3633. svr.stop();
  3634. thread.join();
  3635. ASSERT_FALSE(svr.is_running());
  3636. });
  3637. svr.wait_until_ready();
  3638. {
  3639. Client cli(HOST, PORT);
  3640. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3641. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3642. EXPECT_EQ(StatusCode::OK_200, res->status);
  3643. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3644. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3645. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3646. }
  3647. }
  3648. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3649. TEST(ExceptionTest, WithoutExceptionHandler) {
  3650. Server svr;
  3651. svr.Get("/exception", [&](const Request & /*req*/, Response & /*res*/) {
  3652. throw std::runtime_error("exception...");
  3653. });
  3654. svr.Get("/unknown", [&](const Request & /*req*/, Response & /*res*/) {
  3655. throw std::runtime_error("exception\r\n...");
  3656. });
  3657. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  3658. auto se = detail::scope_exit([&] {
  3659. svr.stop();
  3660. listen_thread.join();
  3661. ASSERT_FALSE(svr.is_running());
  3662. });
  3663. svr.wait_until_ready();
  3664. Client cli("localhost", PORT);
  3665. {
  3666. auto res = cli.Get("/exception");
  3667. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3668. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3669. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3670. }
  3671. {
  3672. auto res = cli.Get("/unknown");
  3673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3674. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3675. EXPECT_FALSE(res->has_header("EXCEPTION_WHAT"));
  3676. }
  3677. }
  3678. TEST(ExceptionTest, WithExceptionHandler) {
  3679. Server svr;
  3680. svr.set_exception_handler([](const Request & /*req*/, Response &res,
  3681. std::exception_ptr ep) {
  3682. EXPECT_FALSE(ep == nullptr);
  3683. try {
  3684. std::rethrow_exception(ep);
  3685. } catch (std::exception &e) {
  3686. EXPECT_EQ("abc", std::string(e.what()));
  3687. } catch (...) {}
  3688. res.status = StatusCode::InternalServerError_500;
  3689. res.set_content("abcdefghijklmnopqrstuvwxyz",
  3690. "text/html"); // <= Content-Length still 13 at this point
  3691. });
  3692. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3693. res.set_content("Hello World!\n", "text/plain");
  3694. throw std::runtime_error("abc");
  3695. });
  3696. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3697. auto se = detail::scope_exit([&] {
  3698. svr.stop();
  3699. thread.join();
  3700. ASSERT_FALSE(svr.is_running());
  3701. });
  3702. svr.wait_until_ready();
  3703. for (size_t i = 0; i < 10; i++) {
  3704. Client cli(HOST, PORT);
  3705. for (size_t j = 0; j < 100; j++) {
  3706. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3707. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3708. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3709. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3710. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3711. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3712. }
  3713. cli.set_keep_alive(true);
  3714. for (size_t j = 0; j < 100; j++) {
  3715. auto res = cli.Get("/hi", Headers{{"Accept-Encoding", ""}});
  3716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3717. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3718. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3719. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  3720. EXPECT_EQ("abcdefghijklmnopqrstuvwxyz", res->body);
  3721. }
  3722. }
  3723. }
  3724. TEST(ExceptionTest, AndErrorHandler) {
  3725. Server svr;
  3726. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  3727. if (res.body.empty()) { res.set_content("NOT_FOUND", "text/html"); }
  3728. });
  3729. svr.set_exception_handler(
  3730. [](const Request & /*req*/, Response &res, std::exception_ptr ep) {
  3731. EXPECT_FALSE(ep == nullptr);
  3732. try {
  3733. std::rethrow_exception(ep);
  3734. } catch (std::exception &e) {
  3735. res.set_content(e.what(), "text/html");
  3736. } catch (...) {}
  3737. res.status = StatusCode::InternalServerError_500;
  3738. });
  3739. svr.Get("/exception", [](const Request & /*req*/, Response & /*res*/) {
  3740. throw std::runtime_error("EXCEPTION");
  3741. });
  3742. svr.Get("/error", [](const Request & /*req*/, Response &res) {
  3743. res.set_content("ERROR", "text/html");
  3744. res.status = StatusCode::InternalServerError_500;
  3745. });
  3746. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  3747. auto se = detail::scope_exit([&] {
  3748. svr.stop();
  3749. thread.join();
  3750. ASSERT_FALSE(svr.is_running());
  3751. });
  3752. svr.wait_until_ready();
  3753. Client cli(HOST, PORT);
  3754. {
  3755. auto res = cli.Get("/exception");
  3756. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3757. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  3758. EXPECT_EQ("EXCEPTION", res->body);
  3759. }
  3760. {
  3761. auto res = cli.Get("/error");
  3762. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3763. EXPECT_EQ(StatusCode::InternalServerError_500, res->status);
  3764. EXPECT_EQ("ERROR", res->body);
  3765. }
  3766. {
  3767. auto res = cli.Get("/invalid");
  3768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3769. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  3770. EXPECT_EQ("NOT_FOUND", res->body);
  3771. }
  3772. }
  3773. #endif
  3774. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  3775. // process_request() wraps only routing() in a try/catch, so an exception from
  3776. // any other user callback used to unwind into the task queue - which does not
  3777. // catch - and terminate the process. Each test below runs the server on a
  3778. // single worker thread: a guard that catches the exception but still loses the
  3779. // thread would otherwise be hidden by a spare worker serving the follow-up
  3780. // request. Note that a regression here aborts the whole test binary rather
  3781. // than failing one test.
  3782. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheServer) {
  3783. Server svr;
  3784. svr.new_task_queue = [] { return new ThreadPool(1); };
  3785. std::atomic<int> reported{0};
  3786. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3787. if (err == Error::UserCallbackException) { reported++; }
  3788. });
  3789. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3790. res.set_content_provider(
  3791. 1024, "text/plain",
  3792. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3793. sink.write("hello", 5);
  3794. throw std::runtime_error("from the content provider");
  3795. });
  3796. });
  3797. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3798. res.set_content("ok", "text/plain");
  3799. });
  3800. auto port = svr.bind_to_any_port(HOST);
  3801. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3802. auto se = detail::scope_exit([&] {
  3803. svr.stop();
  3804. listen_thread.join();
  3805. ASSERT_FALSE(svr.is_running());
  3806. });
  3807. svr.wait_until_ready();
  3808. {
  3809. Client cli(HOST, port);
  3810. cli.set_read_timeout(5, 0);
  3811. EXPECT_FALSE(cli.Get("/throw"));
  3812. }
  3813. EXPECT_TRUE(svr.is_running());
  3814. EXPECT_EQ(1, reported.load());
  3815. // A request on a fresh connection is still served.
  3816. {
  3817. Client cli(HOST, port);
  3818. auto res = cli.Get("/ok");
  3819. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3820. EXPECT_EQ(StatusCode::OK_200, res->status);
  3821. EXPECT_EQ("ok", res->body);
  3822. }
  3823. }
  3824. TEST(ServerExceptionTest, ThrowingPostRoutingHandlerDoesNotKillTheServer) {
  3825. Server svr;
  3826. svr.new_task_queue = [] { return new ThreadPool(1); };
  3827. std::atomic<bool> should_throw{true};
  3828. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  3829. res.set_content("hi", "text/plain");
  3830. });
  3831. svr.set_post_routing_handler(
  3832. [&](const Request & /*req*/, Response & /*res*/) {
  3833. if (should_throw) {
  3834. throw std::runtime_error("from the post-routing handler");
  3835. }
  3836. });
  3837. auto port = svr.bind_to_any_port(HOST);
  3838. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3839. auto se = detail::scope_exit([&] {
  3840. svr.stop();
  3841. listen_thread.join();
  3842. ASSERT_FALSE(svr.is_running());
  3843. });
  3844. svr.wait_until_ready();
  3845. {
  3846. Client cli(HOST, port);
  3847. cli.set_read_timeout(5, 0);
  3848. EXPECT_FALSE(cli.Get("/hi"));
  3849. }
  3850. EXPECT_TRUE(svr.is_running());
  3851. should_throw = false;
  3852. {
  3853. Client cli(HOST, port);
  3854. auto res = cli.Get("/hi");
  3855. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3856. EXPECT_EQ(StatusCode::OK_200, res->status);
  3857. EXPECT_EQ("hi", res->body);
  3858. }
  3859. }
  3860. TEST(ServerExceptionTest, ThrowingErrorLoggerDoesNotReopenTheGuard) {
  3861. // The guard reports the caught exception through the error logger, which is
  3862. // a user callback too. A logger that throws has to be contained as well, or
  3863. // the process would terminate from inside the catch.
  3864. Server svr;
  3865. svr.new_task_queue = [] { return new ThreadPool(1); };
  3866. std::atomic<int> reported{0};
  3867. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3868. if (err == Error::UserCallbackException) {
  3869. reported++;
  3870. throw std::runtime_error("from the error logger");
  3871. }
  3872. });
  3873. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3874. res.set_content_provider(
  3875. 1024, "text/plain",
  3876. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3877. sink.write("hello", 5);
  3878. throw std::runtime_error("from the content provider");
  3879. });
  3880. });
  3881. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3882. res.set_content("ok", "text/plain");
  3883. });
  3884. auto port = svr.bind_to_any_port(HOST);
  3885. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3886. auto se = detail::scope_exit([&] {
  3887. svr.stop();
  3888. listen_thread.join();
  3889. ASSERT_FALSE(svr.is_running());
  3890. });
  3891. svr.wait_until_ready();
  3892. {
  3893. Client cli(HOST, port);
  3894. cli.set_read_timeout(5, 0);
  3895. EXPECT_FALSE(cli.Get("/throw"));
  3896. }
  3897. EXPECT_TRUE(svr.is_running());
  3898. EXPECT_EQ(1, reported.load());
  3899. {
  3900. Client cli(HOST, port);
  3901. auto res = cli.Get("/ok");
  3902. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3903. EXPECT_EQ(StatusCode::OK_200, res->status);
  3904. EXPECT_EQ("ok", res->body);
  3905. }
  3906. }
  3907. TEST(ServerExceptionTest, ThrowingWebSocketHandlerDoesNotKillTheServer) {
  3908. // A WebSocket handler runs on the upgrade path after the 101 has been sent,
  3909. // so the exception unwinds through the ws::WebSocket object on its way to
  3910. // the guard. None of the HTTP cases above cross that.
  3911. Server svr;
  3912. svr.new_task_queue = [] { return new ThreadPool(1); };
  3913. std::atomic<int> reported{0};
  3914. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3915. if (err == Error::UserCallbackException) { reported++; }
  3916. });
  3917. svr.WebSocket("/ws", [](const Request & /*req*/, ws::WebSocket & /*ws*/) {
  3918. throw std::runtime_error("from the WebSocket handler");
  3919. });
  3920. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3921. res.set_content("ok", "text/plain");
  3922. });
  3923. auto port = svr.bind_to_any_port(HOST);
  3924. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3925. auto se = detail::scope_exit([&] {
  3926. svr.stop();
  3927. listen_thread.join();
  3928. ASSERT_FALSE(svr.is_running());
  3929. });
  3930. svr.wait_until_ready();
  3931. {
  3932. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  3933. "/ws");
  3934. auto res = client.connect();
  3935. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3936. // The server dropped the connection instead of dying.
  3937. std::string msg;
  3938. EXPECT_FALSE(client.read(msg));
  3939. client.close();
  3940. }
  3941. EXPECT_TRUE(svr.is_running());
  3942. EXPECT_EQ(1, reported.load());
  3943. {
  3944. Client cli(HOST, port);
  3945. auto res = cli.Get("/ok");
  3946. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3947. EXPECT_EQ(StatusCode::OK_200, res->status);
  3948. EXPECT_EQ("ok", res->body);
  3949. }
  3950. }
  3951. #ifdef CPPHTTPLIB_SSL_ENABLED
  3952. TEST(ServerExceptionTest, ThrowingContentProviderDoesNotKillTheSSLServer) {
  3953. // SSLServer::process_and_close_socket() is a separate overload with its own
  3954. // guard, so it is exercised on its own.
  3955. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  3956. ASSERT_TRUE(svr.is_valid());
  3957. svr.new_task_queue = [] { return new ThreadPool(1); };
  3958. std::atomic<int> reported{0};
  3959. svr.set_error_logger([&](const Error &err, const Request * /*req*/) {
  3960. if (err == Error::UserCallbackException) { reported++; }
  3961. });
  3962. svr.Get("/throw", [](const Request & /*req*/, Response &res) {
  3963. res.set_content_provider(
  3964. 1024, "text/plain",
  3965. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  3966. sink.write("hello", 5);
  3967. throw std::runtime_error("from the content provider");
  3968. });
  3969. });
  3970. svr.Get("/ok", [](const Request & /*req*/, Response &res) {
  3971. res.set_content("ok", "text/plain");
  3972. });
  3973. auto port = svr.bind_to_any_port(HOST);
  3974. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  3975. auto se = detail::scope_exit([&] {
  3976. svr.stop();
  3977. listen_thread.join();
  3978. ASSERT_FALSE(svr.is_running());
  3979. });
  3980. svr.wait_until_ready();
  3981. {
  3982. SSLClient cli(HOST, port);
  3983. cli.enable_server_certificate_verification(false);
  3984. cli.set_read_timeout(5, 0);
  3985. EXPECT_FALSE(cli.Get("/throw"));
  3986. }
  3987. EXPECT_TRUE(svr.is_running());
  3988. EXPECT_EQ(1, reported.load());
  3989. {
  3990. SSLClient cli(HOST, port);
  3991. cli.enable_server_certificate_verification(false);
  3992. auto res = cli.Get("/ok");
  3993. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  3994. EXPECT_EQ(StatusCode::OK_200, res->status);
  3995. EXPECT_EQ("ok", res->body);
  3996. }
  3997. }
  3998. #endif
  3999. #endif
  4000. TEST(NoContentTest, ContentLength) {
  4001. Server svr;
  4002. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4003. res.status = StatusCode::NoContent_204;
  4004. });
  4005. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4006. auto se = detail::scope_exit([&] {
  4007. svr.stop();
  4008. thread.join();
  4009. ASSERT_FALSE(svr.is_running());
  4010. });
  4011. svr.wait_until_ready();
  4012. {
  4013. Client cli(HOST, PORT);
  4014. auto res = cli.Get("/hi");
  4015. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4016. EXPECT_EQ(StatusCode::NoContent_204, res->status);
  4017. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  4018. }
  4019. }
  4020. TEST(RoutingHandlerTest, PreAndPostRoutingHandlers) {
  4021. #ifdef CPPHTTPLIB_SSL_ENABLED
  4022. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  4023. ASSERT_TRUE(svr.is_valid());
  4024. #else
  4025. Server svr;
  4026. #endif
  4027. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  4028. if (req.path == "/routing_handler") {
  4029. res.set_header("PRE_ROUTING", "on");
  4030. res.set_content("Routing Handler", "text/plain");
  4031. return httplib::Server::HandlerResponse::Handled;
  4032. }
  4033. return httplib::Server::HandlerResponse::Unhandled;
  4034. });
  4035. svr.set_error_handler([](const Request & /*req*/, Response &res) {
  4036. res.set_content("Error", "text/html");
  4037. });
  4038. svr.set_post_routing_handler([](const Request &req, Response &res) {
  4039. if (req.path == "/routing_handler") {
  4040. res.set_header("POST_ROUTING", "on");
  4041. }
  4042. });
  4043. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4044. res.set_content("Hello World!\n", "text/plain");
  4045. });
  4046. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4047. auto se = detail::scope_exit([&] {
  4048. svr.stop();
  4049. thread.join();
  4050. ASSERT_FALSE(svr.is_running());
  4051. });
  4052. svr.wait_until_ready();
  4053. {
  4054. #ifdef CPPHTTPLIB_SSL_ENABLED
  4055. SSLClient cli(HOST, PORT);
  4056. cli.enable_server_certificate_verification(false);
  4057. #else
  4058. Client cli(HOST, PORT);
  4059. #endif
  4060. auto res = cli.Get("/routing_handler");
  4061. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4062. EXPECT_EQ(StatusCode::OK_200, res->status);
  4063. EXPECT_EQ("Routing Handler", res->body);
  4064. EXPECT_EQ(1U, res->get_header_value_count("PRE_ROUTING"));
  4065. EXPECT_EQ("on", res->get_header_value("PRE_ROUTING"));
  4066. EXPECT_EQ(1U, res->get_header_value_count("POST_ROUTING"));
  4067. EXPECT_EQ("on", res->get_header_value("POST_ROUTING"));
  4068. }
  4069. {
  4070. #ifdef CPPHTTPLIB_SSL_ENABLED
  4071. SSLClient cli(HOST, PORT);
  4072. cli.enable_server_certificate_verification(false);
  4073. #else
  4074. Client cli(HOST, PORT);
  4075. #endif
  4076. auto res = cli.Get("/hi");
  4077. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4078. EXPECT_EQ(StatusCode::OK_200, res->status);
  4079. EXPECT_EQ("Hello World!\n", res->body);
  4080. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4081. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4082. }
  4083. {
  4084. #ifdef CPPHTTPLIB_SSL_ENABLED
  4085. SSLClient cli(HOST, PORT);
  4086. cli.enable_server_certificate_verification(false);
  4087. #else
  4088. Client cli(HOST, PORT);
  4089. #endif
  4090. auto res = cli.Get("/aaa");
  4091. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4092. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4093. EXPECT_EQ("Error", res->body);
  4094. EXPECT_EQ(0U, res->get_header_value_count("PRE_ROUTING"));
  4095. EXPECT_EQ(0U, res->get_header_value_count("POST_ROUTING"));
  4096. }
  4097. }
  4098. TEST(RequestHandlerTest, PreRequestHandler) {
  4099. auto route_path = "/user/:user";
  4100. Server svr;
  4101. svr.Get("/hi", [](const Request &, Response &res) {
  4102. res.set_content("hi", "text/plain");
  4103. });
  4104. svr.Get(route_path, [](const Request &req, Response &res) {
  4105. res.set_content(req.path_params.at("user"), "text/plain");
  4106. });
  4107. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  4108. if (req.matched_route == route_path) {
  4109. auto user = req.path_params.at("user");
  4110. if (user != "john") {
  4111. res.status = StatusCode::Forbidden_403;
  4112. res.set_content("error", "text/html");
  4113. return Server::HandlerResponse::Handled;
  4114. }
  4115. }
  4116. return Server::HandlerResponse::Unhandled;
  4117. });
  4118. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4119. auto se = detail::scope_exit([&] {
  4120. svr.stop();
  4121. thread.join();
  4122. ASSERT_FALSE(svr.is_running());
  4123. });
  4124. svr.wait_until_ready();
  4125. Client cli(HOST, PORT);
  4126. {
  4127. auto res = cli.Get("/hi");
  4128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4129. EXPECT_EQ(StatusCode::OK_200, res->status);
  4130. EXPECT_EQ("hi", res->body);
  4131. }
  4132. {
  4133. auto res = cli.Get("/user/john");
  4134. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4135. EXPECT_EQ(StatusCode::OK_200, res->status);
  4136. EXPECT_EQ("john", res->body);
  4137. }
  4138. {
  4139. auto res = cli.Get("/user/invalid-user");
  4140. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4141. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4142. EXPECT_EQ("error", res->body);
  4143. }
  4144. }
  4145. // The pre-request handler must run before the request body is read, so a
  4146. // rejected request never forces the server to buffer a (potentially large)
  4147. // body. Here the posted body is larger than the payload limit: if the body
  4148. // were read first the server would answer 413, but because the pre-request
  4149. // handler runs first it answers 403 and the body is never read.
  4150. TEST(RequestHandlerTest, PreRequestHandlerRunsBeforeBodyIsRead) {
  4151. Server svr;
  4152. svr.set_payload_max_length(8);
  4153. auto handler_ran = false;
  4154. svr.Post("/reject", [&](const Request &req, Response &res) {
  4155. handler_ran = true;
  4156. res.set_content(req.body, "text/plain");
  4157. });
  4158. svr.Post("/accept", [](const Request &req, Response &res) {
  4159. res.set_content(req.body, "text/plain");
  4160. });
  4161. svr.set_pre_request_handler([](const Request &req, Response &res) {
  4162. if (req.matched_route == "/reject") {
  4163. res.status = StatusCode::Forbidden_403;
  4164. res.set_content("denied", "text/plain");
  4165. return Server::HandlerResponse::Handled;
  4166. }
  4167. return Server::HandlerResponse::Unhandled;
  4168. });
  4169. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4170. auto se = detail::scope_exit([&] {
  4171. svr.stop();
  4172. thread.join();
  4173. ASSERT_FALSE(svr.is_running());
  4174. });
  4175. svr.wait_until_ready();
  4176. Client cli(HOST, PORT);
  4177. // Body (10 bytes) exceeds the 8-byte limit, yet the pre-request handler
  4178. // rejects with 403 before the body is read, so 413 is never reached.
  4179. {
  4180. auto res = cli.Post("/reject", "0123456789", "text/plain");
  4181. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4182. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  4183. EXPECT_EQ("denied", res->body);
  4184. EXPECT_FALSE(handler_ran);
  4185. }
  4186. // An approved route still reads the body and enforces the payload limit.
  4187. {
  4188. auto res = cli.Post("/accept", "0123456789", "text/plain");
  4189. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4190. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  4191. }
  4192. }
  4193. TEST(UserDataTest, BasicOperations) {
  4194. httplib::UserData ud;
  4195. // Initially empty
  4196. EXPECT_FALSE(ud.has("key"));
  4197. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4198. // set and get
  4199. ud.set("key", 42);
  4200. EXPECT_TRUE(ud.has("key"));
  4201. auto *p = ud.get<int>("key");
  4202. ASSERT_NE(nullptr, p);
  4203. EXPECT_EQ(42, *p);
  4204. // Type mismatch → nullptr
  4205. EXPECT_EQ(nullptr, ud.get<std::string>("key"));
  4206. // Overwrite with different type
  4207. ud.set("key", std::string("hello"));
  4208. EXPECT_EQ(nullptr, ud.get<int>("key"));
  4209. auto *s = ud.get<std::string>("key");
  4210. ASSERT_NE(nullptr, s);
  4211. EXPECT_EQ("hello", *s);
  4212. // erase
  4213. ud.erase("key");
  4214. EXPECT_FALSE(ud.has("key"));
  4215. // clear
  4216. ud.set("a", 1);
  4217. ud.set("b", 2);
  4218. ud.clear();
  4219. EXPECT_FALSE(ud.has("a"));
  4220. EXPECT_FALSE(ud.has("b"));
  4221. }
  4222. TEST(RequestHandlerTest, ResponseUserDataInPreRouting) {
  4223. struct AuthCtx {
  4224. std::string user_id;
  4225. };
  4226. Server svr;
  4227. svr.set_pre_routing_handler([](const Request & /*req*/, Response &res) {
  4228. res.user_data.set("auth", AuthCtx{"alice"});
  4229. return Server::HandlerResponse::Unhandled;
  4230. });
  4231. svr.Get("/me", [](const Request & /*req*/, Response &res) {
  4232. auto *ctx = res.user_data.get<AuthCtx>("auth");
  4233. ASSERT_NE(nullptr, ctx);
  4234. res.set_content("Hello " + ctx->user_id, "text/plain");
  4235. });
  4236. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4237. auto se = detail::scope_exit([&] {
  4238. svr.stop();
  4239. thread.join();
  4240. ASSERT_FALSE(svr.is_running());
  4241. });
  4242. svr.wait_until_ready();
  4243. Client cli(HOST, PORT);
  4244. auto res = cli.Get("/me");
  4245. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4246. EXPECT_EQ(StatusCode::OK_200, res->status);
  4247. EXPECT_EQ("Hello alice", res->body);
  4248. }
  4249. TEST(RequestHandlerTest, ResponseUserDataInPreRequest) {
  4250. struct RoleCtx {
  4251. std::string role;
  4252. };
  4253. Server svr;
  4254. svr.set_pre_request_handler([](const Request & /*req*/, Response &res) {
  4255. res.user_data.set("role", RoleCtx{"admin"});
  4256. return Server::HandlerResponse::Unhandled;
  4257. });
  4258. svr.Get("/role", [](const Request & /*req*/, Response &res) {
  4259. auto *ctx = res.user_data.get<RoleCtx>("role");
  4260. ASSERT_NE(nullptr, ctx);
  4261. res.set_content(ctx->role, "text/plain");
  4262. });
  4263. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4264. auto se = detail::scope_exit([&] {
  4265. svr.stop();
  4266. thread.join();
  4267. ASSERT_FALSE(svr.is_running());
  4268. });
  4269. svr.wait_until_ready();
  4270. Client cli(HOST, PORT);
  4271. auto res = cli.Get("/role");
  4272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  4273. EXPECT_EQ(StatusCode::OK_200, res->status);
  4274. EXPECT_EQ("admin", res->body);
  4275. }
  4276. TEST(InvalidFormatTest, StatusCode) {
  4277. Server svr;
  4278. svr.Get("/hi", [](const Request & /*req*/, Response &res) {
  4279. res.set_content("Hello World!\n", "text/plain");
  4280. res.status = 9999; // Status should be a three-digit code...
  4281. });
  4282. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4283. auto se = detail::scope_exit([&] {
  4284. svr.stop();
  4285. thread.join();
  4286. ASSERT_FALSE(svr.is_running());
  4287. });
  4288. svr.wait_until_ready();
  4289. {
  4290. Client cli(HOST, PORT);
  4291. auto res = cli.Get("/hi");
  4292. ASSERT_FALSE(res);
  4293. }
  4294. }
  4295. TEST(URLFragmentTest, WithFragment) {
  4296. Server svr;
  4297. svr.Get("/hi", [](const Request &req, Response & /*res*/) {
  4298. EXPECT_TRUE(req.target == "/hi");
  4299. });
  4300. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4301. auto se = detail::scope_exit([&] {
  4302. svr.stop();
  4303. thread.join();
  4304. ASSERT_FALSE(svr.is_running());
  4305. });
  4306. svr.wait_until_ready();
  4307. {
  4308. Client cli(HOST, PORT);
  4309. auto res = cli.Get("/hi#key1=val1=key2=val2");
  4310. EXPECT_TRUE(res);
  4311. EXPECT_EQ(StatusCode::OK_200, res->status);
  4312. res = cli.Get("/hi%23key1=val1=key2=val2");
  4313. EXPECT_TRUE(res);
  4314. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  4315. }
  4316. }
  4317. TEST(HeaderWriter, SetHeaderWriter) {
  4318. Server svr;
  4319. svr.set_header_writer([](Stream &strm, Headers &hdrs) {
  4320. hdrs.emplace("CustomServerHeader", "CustomServerValue");
  4321. return detail::write_headers(strm, hdrs);
  4322. });
  4323. svr.Get("/hi", [](const Request &req, Response &res) {
  4324. auto it = req.headers.find("CustomClientHeader");
  4325. EXPECT_TRUE(it != req.headers.end());
  4326. EXPECT_EQ(it->second, "CustomClientValue");
  4327. res.set_content("Hello World!\n", "text/plain");
  4328. });
  4329. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  4330. auto se = detail::scope_exit([&] {
  4331. svr.stop();
  4332. thread.join();
  4333. ASSERT_FALSE(svr.is_running());
  4334. });
  4335. svr.wait_until_ready();
  4336. {
  4337. Client cli(HOST, PORT);
  4338. cli.set_header_writer([](Stream &strm, Headers &hdrs) {
  4339. hdrs.emplace("CustomClientHeader", "CustomClientValue");
  4340. return detail::write_headers(strm, hdrs);
  4341. });
  4342. auto res = cli.Get("/hi");
  4343. EXPECT_TRUE(res);
  4344. EXPECT_EQ(StatusCode::OK_200, res->status);
  4345. auto it = res->headers.find("CustomServerHeader");
  4346. EXPECT_TRUE(it != res->headers.end());
  4347. EXPECT_EQ(it->second, "CustomServerValue");
  4348. }
  4349. }
  4350. class ServerTest : public ::testing::Test {
  4351. protected:
  4352. ServerTest()
  4353. : cli_(HOST, PORT)
  4354. #ifdef CPPHTTPLIB_SSL_ENABLED
  4355. ,
  4356. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  4357. #endif
  4358. {
  4359. #ifdef CPPHTTPLIB_SSL_ENABLED
  4360. cli_.enable_server_certificate_verification(false);
  4361. #endif
  4362. // Allow LARGE_DATA (100MB) responses
  4363. cli_.set_payload_max_length(200 * 1024 * 1024);
  4364. }
  4365. virtual void SetUp() {
  4366. // Allow LARGE_DATA (100MB) tests to pass with new 100MB default limit
  4367. svr_.set_payload_max_length(200 * 1024 * 1024);
  4368. svr_.set_mount_point("/", "./www");
  4369. svr_.set_mount_point("/mount", "./www2");
  4370. svr_.set_file_extension_and_mimetype_mapping("abcde", "text/abcde");
  4371. svr_.Get("/hi",
  4372. [&](const Request & /*req*/, Response &res) {
  4373. res.set_content("Hello World!", "text/plain");
  4374. })
  4375. .Get("/file_content",
  4376. [&](const Request & /*req*/, Response &res) {
  4377. res.set_file_content("./www/dir/test.html");
  4378. })
  4379. .Get("/file_content_with_content_type",
  4380. [&](const Request & /*req*/, Response &res) {
  4381. res.set_file_content("./www/file", "text/plain");
  4382. })
  4383. .Get("/invalid_file_content",
  4384. [&](const Request & /*req*/, Response &res) {
  4385. res.set_file_content("./www/dir/invalid_file_path");
  4386. })
  4387. .Get("/http_response_splitting",
  4388. [&](const Request & /*req*/, Response &res) {
  4389. res.set_header("a", "1\r\nSet-Cookie: a=1");
  4390. EXPECT_EQ(0U, res.headers.size());
  4391. EXPECT_FALSE(res.has_header("a"));
  4392. res.set_header("a", "1\nSet-Cookie: a=1");
  4393. EXPECT_EQ(0U, res.headers.size());
  4394. EXPECT_FALSE(res.has_header("a"));
  4395. res.set_header("a", "1\rSet-Cookie: a=1");
  4396. EXPECT_EQ(0U, res.headers.size());
  4397. EXPECT_FALSE(res.has_header("a"));
  4398. res.set_header("a\r\nb", "0");
  4399. EXPECT_EQ(0U, res.headers.size());
  4400. EXPECT_FALSE(res.has_header("a"));
  4401. res.set_header("a\rb", "0");
  4402. EXPECT_EQ(0U, res.headers.size());
  4403. EXPECT_FALSE(res.has_header("a"));
  4404. res.set_header("a\nb", "0");
  4405. EXPECT_EQ(0U, res.headers.size());
  4406. EXPECT_FALSE(res.has_header("a"));
  4407. res.set_redirect("1\r\nSet-Cookie: a=1");
  4408. EXPECT_EQ(0U, res.headers.size());
  4409. EXPECT_FALSE(res.has_header("Location"));
  4410. })
  4411. .Get("/slow",
  4412. [&](const Request & /*req*/, Response &res) {
  4413. std::this_thread::sleep_for(std::chrono::seconds(4));
  4414. res.set_content("slow", "text/plain");
  4415. })
  4416. #if 0
  4417. .Post("/slowpost",
  4418. [&](const Request & /*req*/, Response &res) {
  4419. std::this_thread::sleep_for(std::chrono::seconds(2));
  4420. res.set_content("slow", "text/plain");
  4421. })
  4422. #endif
  4423. .Get("/remote_addr",
  4424. [&](const Request &req, Response &res) {
  4425. ASSERT_FALSE(req.has_header("REMOTE_ADDR"));
  4426. ASSERT_FALSE(req.has_header("REMOTE_PORT"));
  4427. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4428. ASSERT_ANY_THROW(req.get_header_value("REMOTE_ADDR"));
  4429. ASSERT_ANY_THROW(req.get_header_value("REMOTE_PORT"));
  4430. #endif
  4431. res.set_content(req.remote_addr, "text/plain");
  4432. })
  4433. .Get("/local_addr",
  4434. [&](const Request &req, Response &res) {
  4435. ASSERT_FALSE(req.has_header("LOCAL_ADDR"));
  4436. ASSERT_FALSE(req.has_header("LOCAL_PORT"));
  4437. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  4438. ASSERT_ANY_THROW(req.get_header_value("LOCAL_ADDR"));
  4439. ASSERT_ANY_THROW(req.get_header_value("LOCAL_PORT"));
  4440. #endif
  4441. auto local_addr = req.local_addr;
  4442. auto local_port = std::to_string(req.local_port);
  4443. res.set_content(local_addr.append(":").append(local_port),
  4444. "text/plain");
  4445. })
  4446. .Get("/endwith%",
  4447. [&](const Request & /*req*/, Response &res) {
  4448. res.set_content("Hello World!", "text/plain");
  4449. })
  4450. .Get("/a\\+\\+b",
  4451. [&](const Request &req, Response &res) {
  4452. ASSERT_TRUE(req.has_param("a +b"));
  4453. auto val = req.get_param_value("a +b");
  4454. res.set_content(val, "text/plain");
  4455. })
  4456. .Get("/", [&](const Request & /*req*/,
  4457. Response &res) { res.set_redirect("/hi"); })
  4458. .Post("/1",
  4459. [](const Request & /*req*/, Response &res) {
  4460. res.set_redirect("/2", StatusCode::SeeOther_303);
  4461. })
  4462. .Get("/2",
  4463. [](const Request & /*req*/, Response &res) {
  4464. res.set_content("redirected.", "text/plain");
  4465. res.status = StatusCode::OK_200;
  4466. })
  4467. .Post("/person",
  4468. [&](const Request &req, Response &res) {
  4469. if (req.has_param("name") && req.has_param("note")) {
  4470. persons_[req.get_param_value("name")] =
  4471. req.get_param_value("note");
  4472. } else {
  4473. res.status = StatusCode::BadRequest_400;
  4474. }
  4475. })
  4476. .Put("/person",
  4477. [&](const Request &req, Response &res) {
  4478. if (req.has_param("name") && req.has_param("note")) {
  4479. persons_[req.get_param_value("name")] =
  4480. req.get_param_value("note");
  4481. } else {
  4482. res.status = StatusCode::BadRequest_400;
  4483. }
  4484. })
  4485. .Get("/person/(.*)",
  4486. [&](const Request &req, Response &res) {
  4487. string name = req.matches[1];
  4488. if (persons_.find(name) != persons_.end()) {
  4489. auto note = persons_[name];
  4490. res.set_content(note, "text/plain");
  4491. } else {
  4492. res.status = StatusCode::NotFound_404;
  4493. }
  4494. })
  4495. .Delete("/person",
  4496. [&](const Request &req, Response &res) {
  4497. if (req.has_param("name")) {
  4498. string name = req.get_param_value("name");
  4499. if (persons_.find(name) != persons_.end()) {
  4500. persons_.erase(name);
  4501. res.set_content("DELETED", "text/plain");
  4502. } else {
  4503. res.status = StatusCode::NotFound_404;
  4504. }
  4505. } else {
  4506. res.status = StatusCode::BadRequest_400;
  4507. }
  4508. })
  4509. .Post("/x-www-form-urlencoded-json",
  4510. [&](const Request &req, Response &res) {
  4511. auto json = req.get_param_value("json");
  4512. ASSERT_EQ(JSON_DATA, json);
  4513. res.set_content(json, "appliation/json");
  4514. res.status = StatusCode::OK_200;
  4515. })
  4516. .Get("/streamed-chunked",
  4517. [&](const Request & /*req*/, Response &res) {
  4518. res.set_chunked_content_provider(
  4519. "text/plain", [](size_t /*offset*/, DataSink &sink) {
  4520. sink.os << "123";
  4521. sink.os << "456";
  4522. sink.os << "789";
  4523. sink.done();
  4524. return true;
  4525. });
  4526. })
  4527. .Get("/streamed-chunked-with-prohibited-trailer",
  4528. [&](const Request & /*req*/, Response &res) {
  4529. auto i = new int(0);
  4530. // Declare both a prohibited trailer (Content-Length) and an
  4531. // allowed one
  4532. res.set_header("Trailer", "Content-Length, X-Allowed");
  4533. res.set_chunked_content_provider(
  4534. "text/plain",
  4535. [i](size_t /*offset*/, DataSink &sink) {
  4536. switch (*i) {
  4537. case 0: sink.os << "123"; break;
  4538. case 1: sink.os << "456"; break;
  4539. case 2: sink.os << "789"; break;
  4540. case 3: {
  4541. sink.done_with_trailer(
  4542. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  4543. } break;
  4544. }
  4545. (*i)++;
  4546. return true;
  4547. },
  4548. [i](bool success) {
  4549. EXPECT_TRUE(success);
  4550. delete i;
  4551. });
  4552. })
  4553. .Get("/streamed-chunked2",
  4554. [&](const Request & /*req*/, Response &res) {
  4555. auto i = new int(0);
  4556. res.set_chunked_content_provider(
  4557. "text/plain",
  4558. [i](size_t /*offset*/, DataSink &sink) {
  4559. switch (*i) {
  4560. case 0: sink.os << "123"; break;
  4561. case 1: sink.os << "456"; break;
  4562. case 2: sink.os << "789"; break;
  4563. case 3: sink.done(); break;
  4564. }
  4565. (*i)++;
  4566. return true;
  4567. },
  4568. [i](bool success) {
  4569. EXPECT_TRUE(success);
  4570. delete i;
  4571. });
  4572. })
  4573. .Get("/streamed-chunked-with-trailer",
  4574. [&](const Request & /*req*/, Response &res) {
  4575. auto i = new int(0);
  4576. res.set_header("Trailer", "Dummy1, Dummy2");
  4577. res.set_chunked_content_provider(
  4578. "text/plain",
  4579. [i](size_t /*offset*/, DataSink &sink) {
  4580. switch (*i) {
  4581. case 0: sink.os << "123"; break;
  4582. case 1: sink.os << "456"; break;
  4583. case 2: sink.os << "789"; break;
  4584. case 3: {
  4585. sink.done_with_trailer(
  4586. {{"Dummy1", "DummyVal1"}, {"Dummy2", "DummyVal2"}});
  4587. } break;
  4588. }
  4589. (*i)++;
  4590. return true;
  4591. },
  4592. [i](bool success) {
  4593. EXPECT_TRUE(success);
  4594. delete i;
  4595. });
  4596. })
  4597. .Get("/streamed",
  4598. [&](const Request & /*req*/, Response &res) {
  4599. res.set_content_provider(
  4600. 6, "text/plain",
  4601. [](size_t offset, size_t /*length*/, DataSink &sink) {
  4602. sink.os << (offset < 3 ? "a" : "b");
  4603. return true;
  4604. });
  4605. })
  4606. .Get("/streamed-without-length",
  4607. [&](const Request & /*req*/, Response &res) {
  4608. auto data = new std::string("abcdefg");
  4609. res.set_content_provider(
  4610. "text/plain",
  4611. [data](size_t offset, DataSink &sink) {
  4612. if (offset < data->size()) {
  4613. sink.os << data->substr(offset);
  4614. }
  4615. sink.done();
  4616. return true;
  4617. },
  4618. [data](bool success) {
  4619. EXPECT_TRUE(success);
  4620. delete data;
  4621. });
  4622. })
  4623. .Get("/streamed-with-range",
  4624. [&](const Request &req, Response &res) {
  4625. auto data = new std::string("abcdefg");
  4626. // An explicit status keeps the server from picking the 206 it
  4627. // would otherwise choose for a ranged request, so the response
  4628. // is not a partial representation.
  4629. auto status = req.get_param_value("status");
  4630. if (status == "200") {
  4631. res.status = StatusCode::OK_200;
  4632. } else if (status == "403") {
  4633. res.status = StatusCode::Forbidden_403;
  4634. }
  4635. res.set_content_provider(
  4636. data->size(), "text/plain",
  4637. [data](size_t offset, size_t length, DataSink &sink) {
  4638. size_t DATA_CHUNK_SIZE = 4;
  4639. const auto &d = *data;
  4640. auto out_len =
  4641. std::min(static_cast<size_t>(length), DATA_CHUNK_SIZE);
  4642. auto ret =
  4643. sink.write(&d[static_cast<size_t>(offset)], out_len);
  4644. EXPECT_TRUE(ret);
  4645. return true;
  4646. },
  4647. [data, &req](bool success) {
  4648. EXPECT_EQ(success, !req.has_param("error"));
  4649. delete data;
  4650. });
  4651. })
  4652. .Get("/streamed-cancel",
  4653. [&](const Request & /*req*/, Response &res) {
  4654. res.set_content_provider(
  4655. size_t(-1), "text/plain",
  4656. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  4657. sink.os << "data_chunk";
  4658. return true;
  4659. });
  4660. })
  4661. .Get("/regex-with-delimiter",
  4662. [&](const Request &req, Response & /*res*/) {
  4663. ASSERT_TRUE(req.has_param("key"));
  4664. EXPECT_EQ("^(?.*(value))", req.get_param_value("key"));
  4665. })
  4666. .Get("/with-range",
  4667. [&](const Request & /*req*/, Response &res) {
  4668. res.set_content("abcdefg", "text/plain");
  4669. })
  4670. .Get("/test-start-time",
  4671. [&](const Request &req, Response & /*res*/) {
  4672. EXPECT_NE(req.start_time_,
  4673. std::chrono::steady_clock::time_point::min());
  4674. })
  4675. .Get("/with-range-customized-response",
  4676. [&](const Request & /*req*/, Response &res) {
  4677. res.status = StatusCode::BadRequest_400;
  4678. res.set_content(JSON_DATA, "application/json");
  4679. })
  4680. .Post("/chunked",
  4681. [&](const Request &req, Response & /*res*/) {
  4682. EXPECT_EQ(req.body, "dechunked post body");
  4683. })
  4684. .Post("/large-chunked",
  4685. [&](const Request &req, Response & /*res*/) {
  4686. std::string expected(6 * 30 * 1024u, 'a');
  4687. EXPECT_EQ(req.body, expected);
  4688. })
  4689. .Post("/multipart",
  4690. [&](const Request &req, Response & /*res*/) {
  4691. EXPECT_EQ(4u, req.form.get_field_count("text1") +
  4692. req.form.get_field_count("text2") +
  4693. req.form.get_field_count("file3") +
  4694. req.form.get_field_count("file4"));
  4695. EXPECT_EQ(2u, req.form.get_file_count("file1") +
  4696. req.form.get_file_count("file2"));
  4697. ASSERT_TRUE(!req.form.has_file("???"));
  4698. ASSERT_TRUE(!req.form.has_field("???"));
  4699. ASSERT_TRUE(req.body.empty());
  4700. {
  4701. const auto &text = req.form.get_field("text1");
  4702. EXPECT_EQ("text default", text);
  4703. }
  4704. {
  4705. const auto &text = req.form.get_field("text2");
  4706. EXPECT_EQ("aωb", text);
  4707. }
  4708. {
  4709. const auto &file = req.form.get_file("file1");
  4710. EXPECT_EQ("hello.txt", file.filename);
  4711. EXPECT_EQ("text/plain", file.content_type);
  4712. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4713. }
  4714. {
  4715. const auto &file = req.form.get_file("file2");
  4716. EXPECT_EQ("world.json", file.filename);
  4717. EXPECT_EQ("application/json", file.content_type);
  4718. EXPECT_EQ("{\n \"world\", true\n}\n", file.content);
  4719. }
  4720. {
  4721. const auto &text = req.form.get_field("file3");
  4722. EXPECT_EQ(0u, text.size());
  4723. }
  4724. {
  4725. const auto &text = req.form.get_field("file4");
  4726. EXPECT_EQ(0u, text.size());
  4727. }
  4728. })
  4729. .Post("/multipart/multi_file_values",
  4730. [&](const Request &req, Response & /*res*/) {
  4731. EXPECT_EQ(3u, req.form.get_field_count("text") +
  4732. req.form.get_field_count("multi_text1"));
  4733. EXPECT_EQ(2u, req.form.get_file_count("multi_file1"));
  4734. ASSERT_TRUE(!req.form.has_file("???"));
  4735. ASSERT_TRUE(!req.form.has_field("???"));
  4736. ASSERT_TRUE(req.body.empty());
  4737. {
  4738. const auto &text = req.form.get_field("text");
  4739. EXPECT_EQ("default text", text);
  4740. }
  4741. {
  4742. const auto &text1_values = req.form.get_fields("multi_text1");
  4743. EXPECT_EQ(2u, text1_values.size());
  4744. EXPECT_EQ("aaaaa", text1_values[0]);
  4745. EXPECT_EQ("bbbbb", text1_values[1]);
  4746. }
  4747. {
  4748. const auto &file1_values = req.form.get_files("multi_file1");
  4749. EXPECT_EQ(2u, file1_values.size());
  4750. auto file1 = file1_values[0];
  4751. EXPECT_EQ(file1.filename, "hello.txt");
  4752. EXPECT_EQ(file1.content_type, "text/plain");
  4753. EXPECT_EQ("h\ne\n\nl\nl\no\n", file1.content);
  4754. auto file2 = file1_values[1];
  4755. EXPECT_EQ(file2.filename, "world.json");
  4756. EXPECT_EQ(file2.content_type, "application/json");
  4757. EXPECT_EQ("{\n \"world\", true\n}\n", file2.content);
  4758. }
  4759. })
  4760. .Post("/empty",
  4761. [&](const Request &req, Response &res) {
  4762. EXPECT_EQ(req.body, "");
  4763. EXPECT_EQ("text/plain", req.get_header_value("Content-Type"));
  4764. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4765. res.set_content("empty", "text/plain");
  4766. })
  4767. .Post("/empty-no-content-type",
  4768. [&](const Request &req, Response &res) {
  4769. EXPECT_EQ(req.body, "");
  4770. EXPECT_FALSE(req.has_header("Content-Type"));
  4771. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4772. res.set_content("empty-no-content-type", "text/plain");
  4773. })
  4774. .Post("/path-only",
  4775. [&](const Request &req, Response &res) {
  4776. EXPECT_EQ(req.body, "");
  4777. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4778. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4779. res.set_content("path-only", "text/plain");
  4780. })
  4781. .Post("/path-headers-only",
  4782. [&](const Request &req, Response &res) {
  4783. EXPECT_EQ(req.body, "");
  4784. EXPECT_EQ("", req.get_header_value("Content-Type"));
  4785. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4786. EXPECT_EQ("world", req.get_header_value("hello"));
  4787. EXPECT_EQ("world2", req.get_header_value("hello2"));
  4788. res.set_content("path-headers-only", "text/plain");
  4789. })
  4790. .Post("/post-large",
  4791. [&](const Request &req, Response &res) {
  4792. EXPECT_EQ(req.body, LARGE_DATA);
  4793. res.set_content(req.body, "text/plain");
  4794. })
  4795. .Post("/post-loopback",
  4796. [&](const Request &, Response &res,
  4797. ContentReader const &content_reader) {
  4798. std::string body;
  4799. content_reader([&](const char *data, size_t data_length) {
  4800. body.append(data, data_length);
  4801. return true;
  4802. });
  4803. res.set_content(body, "text/plain");
  4804. })
  4805. .Put("/put-loopback",
  4806. [&](const Request &, Response &res,
  4807. ContentReader const &content_reader) {
  4808. std::string body;
  4809. content_reader([&](const char *data, size_t data_length) {
  4810. body.append(data, data_length);
  4811. return true;
  4812. });
  4813. res.set_content(body, "text/plain");
  4814. })
  4815. .Patch("/patch-loopback",
  4816. [&](const Request &, Response &res,
  4817. ContentReader const &content_reader) {
  4818. std::string body;
  4819. content_reader([&](const char *data, size_t data_length) {
  4820. body.append(data, data_length);
  4821. return true;
  4822. });
  4823. res.set_content(body, "text/plain");
  4824. })
  4825. .Put("/empty-no-content-type",
  4826. [&](const Request &req, Response &res) {
  4827. EXPECT_EQ(req.body, "");
  4828. EXPECT_FALSE(req.has_header("Content-Type"));
  4829. EXPECT_EQ("0", req.get_header_value("Content-Length"));
  4830. res.set_content("empty-no-content-type", "text/plain");
  4831. })
  4832. .Put("/put",
  4833. [&](const Request &req, Response &res) {
  4834. EXPECT_EQ(req.body, "PUT");
  4835. res.set_content(req.body, "text/plain");
  4836. })
  4837. .Put("/put-large",
  4838. [&](const Request &req, Response &res) {
  4839. EXPECT_EQ(req.body, LARGE_DATA);
  4840. res.set_content(req.body, "text/plain");
  4841. })
  4842. .Patch("/patch",
  4843. [&](const Request &req, Response &res) {
  4844. EXPECT_EQ(req.body, "PATCH");
  4845. res.set_content(req.body, "text/plain");
  4846. })
  4847. .Delete("/delete",
  4848. [&](const Request & /*req*/, Response &res) {
  4849. res.set_content("DELETE", "text/plain");
  4850. })
  4851. .Delete("/delete-body",
  4852. [&](const Request &req, Response &res) {
  4853. EXPECT_EQ(req.body, "content");
  4854. res.set_content(req.body, "text/plain");
  4855. })
  4856. .Options(R"(\*)",
  4857. [&](const Request & /*req*/, Response &res) {
  4858. res.set_header("Allow", "GET, POST, HEAD, OPTIONS");
  4859. })
  4860. .CustomRoute("PROPFIND", "/dav/:id",
  4861. [&](const Request &req, Response &res) {
  4862. res.set_header("x-body-size",
  4863. std::to_string(req.body.size()));
  4864. res.set_header("x-matched-route", req.matched_route);
  4865. res.set_header("x-dav-id", req.path_params.at("id"));
  4866. res.status = StatusCode::MultiStatus_207;
  4867. res.set_content(req.body, "application/xml");
  4868. })
  4869. .CustomRoute("PROPFIND", R"(/dav-re/(\d+))",
  4870. [&](const Request &req, Response &res) {
  4871. res.set_header("x-dav-match", req.matches[1]);
  4872. res.status = StatusCode::MultiStatus_207;
  4873. })
  4874. .CustomRoute("MKCOL", "/dav-mkcol",
  4875. [&](const Request &req, Response &res) {
  4876. EXPECT_TRUE(req.body.empty());
  4877. res.status = StatusCode::Created_201;
  4878. })
  4879. .CustomRoute(
  4880. "REPORT", "/dav-report",
  4881. [&](const Request & /*req*/, Response &res,
  4882. const ContentReader &content_reader) {
  4883. std::string body;
  4884. content_reader([&](const char *data, size_t data_length) {
  4885. body.append(data, data_length);
  4886. return true;
  4887. });
  4888. res.set_header("x-body-size", std::to_string(body.size()));
  4889. res.status = StatusCode::MultiStatus_207;
  4890. res.set_content(body, "application/xml");
  4891. })
  4892. .Get("/request-target",
  4893. [&](const Request &req, Response & /*res*/) {
  4894. EXPECT_EQ("/request-target?aaa=bbb&ccc=ddd", req.target);
  4895. EXPECT_EQ("bbb", req.get_param_value("aaa"));
  4896. EXPECT_EQ("ddd", req.get_param_value("ccc"));
  4897. })
  4898. .Get("/long-query-value",
  4899. [&](const Request &req, Response & /*res*/) {
  4900. EXPECT_EQ(LONG_QUERY_URL, req.target);
  4901. EXPECT_EQ(LONG_QUERY_VALUE, req.get_param_value("key"));
  4902. })
  4903. .Get("/too-long-query-value",
  4904. [&](const Request &req, Response & /*res*/) {
  4905. EXPECT_EQ(TOO_LONG_QUERY_URL, req.target);
  4906. EXPECT_EQ(TOO_LONG_QUERY_VALUE, req.get_param_value("key"));
  4907. })
  4908. .Get("/array-param",
  4909. [&](const Request &req, Response & /*res*/) {
  4910. EXPECT_EQ(3u, req.get_param_value_count("array"));
  4911. EXPECT_EQ("value1", req.get_param_value("array", 0));
  4912. EXPECT_EQ("value2", req.get_param_value("array", 1));
  4913. EXPECT_EQ("value3", req.get_param_value("array", 2));
  4914. })
  4915. .Get("/array-param-values",
  4916. [&](const Request &req, Response & /*res*/) {
  4917. auto values = req.get_param_values("array");
  4918. EXPECT_EQ(3u, values.size());
  4919. EXPECT_EQ("value1", values[0]);
  4920. EXPECT_EQ("value2", values[1]);
  4921. EXPECT_EQ("value3", values[2]);
  4922. auto empty = req.get_param_values("nonexistent");
  4923. EXPECT_TRUE(empty.empty());
  4924. })
  4925. .Post("/validate-no-multiple-headers",
  4926. [&](const Request &req, Response & /*res*/) {
  4927. EXPECT_EQ(1u, req.get_header_value_count("Content-Length"));
  4928. EXPECT_EQ("5", req.get_header_value("Content-Length"));
  4929. })
  4930. .Post("/content_receiver",
  4931. [&](const Request &req, Response &res,
  4932. const ContentReader &content_reader) {
  4933. if (req.is_multipart_form_data()) {
  4934. std::vector<FormData> items;
  4935. content_reader(
  4936. [&](const FormData &file) {
  4937. items.push_back(file);
  4938. return true;
  4939. },
  4940. [&](const char *data, size_t data_length) {
  4941. items.back().content.append(data, data_length);
  4942. return true;
  4943. });
  4944. EXPECT_EQ(5u, items.size());
  4945. {
  4946. const auto &file = get_file_value(items, "text1");
  4947. EXPECT_TRUE(file.filename.empty());
  4948. EXPECT_EQ("text default", file.content);
  4949. }
  4950. {
  4951. const auto &file = get_file_value(items, "text2");
  4952. EXPECT_TRUE(file.filename.empty());
  4953. EXPECT_EQ("aωb", file.content);
  4954. }
  4955. {
  4956. const auto &file = get_file_value(items, "file1");
  4957. EXPECT_EQ("hello.txt", file.filename);
  4958. EXPECT_EQ("text/plain", file.content_type);
  4959. EXPECT_EQ("h\ne\n\nl\nl\no\n", file.content);
  4960. }
  4961. {
  4962. const auto &file = get_file_value(items, "file2");
  4963. EXPECT_EQ("world.json", file.filename);
  4964. EXPECT_EQ("application/json", file.content_type);
  4965. EXPECT_EQ(R"({\n "world": true\n}\n)", file.content);
  4966. }
  4967. {
  4968. const auto &file = get_file_value(items, "file3");
  4969. EXPECT_TRUE(file.filename.empty());
  4970. EXPECT_EQ("application/octet-stream", file.content_type);
  4971. EXPECT_EQ(0u, file.content.size());
  4972. }
  4973. } else {
  4974. std::string body;
  4975. content_reader([&](const char *data, size_t data_length) {
  4976. EXPECT_EQ(7U, data_length);
  4977. body.append(data, data_length);
  4978. return true;
  4979. });
  4980. EXPECT_EQ(body, "content");
  4981. res.set_content(body, "text/plain");
  4982. }
  4983. })
  4984. .Put("/content_receiver",
  4985. [&](const Request & /*req*/, Response &res,
  4986. const ContentReader &content_reader) {
  4987. std::string body;
  4988. content_reader([&](const char *data, size_t data_length) {
  4989. body.append(data, data_length);
  4990. return true;
  4991. });
  4992. EXPECT_EQ(body, "content");
  4993. res.set_content(body, "text/plain");
  4994. })
  4995. .Patch("/content_receiver",
  4996. [&](const Request & /*req*/, Response &res,
  4997. const ContentReader &content_reader) {
  4998. std::string body;
  4999. content_reader([&](const char *data, size_t data_length) {
  5000. body.append(data, data_length);
  5001. return true;
  5002. });
  5003. EXPECT_EQ(body, "content");
  5004. res.set_content(body, "text/plain");
  5005. })
  5006. .Post("/query-string-and-body",
  5007. [&](const Request &req, Response & /*res*/) {
  5008. ASSERT_TRUE(req.has_param("key"));
  5009. EXPECT_EQ(req.get_param_value("key"), "value");
  5010. EXPECT_EQ(req.body, "content");
  5011. })
  5012. .Get("/last-request",
  5013. [&](const Request &req, Response & /*res*/) {
  5014. EXPECT_EQ("close", req.get_header_value("Connection"));
  5015. })
  5016. .Get(R"(/redirect/(\d+))",
  5017. [&](const Request &req, Response &res) {
  5018. auto num = std::stoi(req.matches[1]) + 1;
  5019. std::string url = "/redirect/" + std::to_string(num);
  5020. res.set_redirect(url);
  5021. })
  5022. .Post("/binary",
  5023. [&](const Request &req, Response &res) {
  5024. EXPECT_EQ(4U, req.body.size());
  5025. EXPECT_EQ("application/octet-stream",
  5026. req.get_header_value("Content-Type"));
  5027. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5028. res.set_content(req.body, "application/octet-stream");
  5029. })
  5030. .Put("/binary",
  5031. [&](const Request &req, Response &res) {
  5032. EXPECT_EQ(4U, req.body.size());
  5033. EXPECT_EQ("application/octet-stream",
  5034. req.get_header_value("Content-Type"));
  5035. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5036. res.set_content(req.body, "application/octet-stream");
  5037. })
  5038. .Patch("/binary",
  5039. [&](const Request &req, Response &res) {
  5040. EXPECT_EQ(4U, req.body.size());
  5041. EXPECT_EQ("application/octet-stream",
  5042. req.get_header_value("Content-Type"));
  5043. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5044. res.set_content(req.body, "application/octet-stream");
  5045. })
  5046. .Delete("/binary",
  5047. [&](const Request &req, Response &res) {
  5048. EXPECT_EQ(4U, req.body.size());
  5049. EXPECT_EQ("application/octet-stream",
  5050. req.get_header_value("Content-Type"));
  5051. EXPECT_EQ("4", req.get_header_value("Content-Length"));
  5052. res.set_content(req.body, "application/octet-stream");
  5053. })
  5054. .Get("/issue1772",
  5055. [&](const Request & /*req*/, Response &res) {
  5056. res.status = 401;
  5057. res.set_header("WWW-Authenticate", "Basic realm=123456");
  5058. })
  5059. .Delete("/issue609",
  5060. [](const httplib::Request &, httplib::Response &res,
  5061. const httplib::ContentReader &) {
  5062. res.set_content("ok", "text/plain");
  5063. })
  5064. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) || defined(CPPHTTPLIB_BROTLI_SUPPORT) || \
  5065. defined(CPPHTTPLIB_ZSTD_SUPPORT)
  5066. .Get("/compress",
  5067. [&](const Request & /*req*/, Response &res) {
  5068. res.set_content(
  5069. "12345678901234567890123456789012345678901234567890123456789"
  5070. "01234567890123456789012345678901234567890",
  5071. "text/plain");
  5072. })
  5073. .Get("/compress-with-charset",
  5074. [&](const Request & /*req*/, Response &res) {
  5075. res.set_content(
  5076. "12345678901234567890123456789012345678901234567890123456789"
  5077. "01234567890123456789012345678901234567890",
  5078. "application/json; charset=utf-8");
  5079. })
  5080. .Get("/nocompress",
  5081. [&](const Request & /*req*/, Response &res) {
  5082. res.set_content(
  5083. "12345678901234567890123456789012345678901234567890123456789"
  5084. "01234567890123456789012345678901234567890",
  5085. "application/octet-stream");
  5086. })
  5087. .Post("/compress-multipart",
  5088. [&](const Request &req, Response & /*res*/) {
  5089. EXPECT_EQ(2u, req.form.fields.size());
  5090. ASSERT_TRUE(!req.form.has_field("???"));
  5091. {
  5092. const auto &text = req.form.get_field("key1");
  5093. EXPECT_EQ("test", text);
  5094. }
  5095. {
  5096. const auto &text = req.form.get_field("key2");
  5097. EXPECT_EQ("--abcdefg123", text);
  5098. }
  5099. })
  5100. #endif
  5101. ;
  5102. persons_["john"] = "programmer";
  5103. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  5104. svr_.wait_until_ready();
  5105. }
  5106. virtual void TearDown() {
  5107. svr_.stop();
  5108. if (!request_threads_.empty()) {
  5109. std::this_thread::sleep_for(std::chrono::seconds(1));
  5110. for (auto &t : request_threads_) {
  5111. t.join();
  5112. }
  5113. }
  5114. t_.join();
  5115. }
  5116. map<string, string> persons_;
  5117. #ifdef CPPHTTPLIB_SSL_ENABLED
  5118. SSLClient cli_;
  5119. SSLServer svr_;
  5120. #else
  5121. Client cli_;
  5122. Server svr_;
  5123. #endif
  5124. thread t_;
  5125. std::vector<thread> request_threads_;
  5126. };
  5127. TEST_F(ServerTest, GetMethod200) {
  5128. auto res = cli_.Get("/hi");
  5129. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5130. EXPECT_EQ("HTTP/1.1", res->version);
  5131. EXPECT_EQ(StatusCode::OK_200, res->status);
  5132. EXPECT_EQ("OK", res->reason);
  5133. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5134. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5135. EXPECT_EQ("Hello World!", res->body);
  5136. }
  5137. TEST_F(ServerTest, GetEmptyFile) {
  5138. auto res = cli_.Get("/empty_file");
  5139. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5140. EXPECT_EQ(StatusCode::OK_200, res->status);
  5141. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  5142. EXPECT_EQ(0, std::stoi(res->get_header_value("Content-Length")));
  5143. EXPECT_EQ("", res->body);
  5144. }
  5145. TEST_F(ServerTest, GetFileContent) {
  5146. auto res = cli_.Get("/file_content");
  5147. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5148. EXPECT_EQ(StatusCode::OK_200, res->status);
  5149. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5150. EXPECT_EQ(9, std::stoi(res->get_header_value("Content-Length")));
  5151. EXPECT_EQ("test.html", res->body);
  5152. }
  5153. TEST_F(ServerTest, GetFileContentWithRange) {
  5154. auto res = cli_.Get("/file_content", Headers{{make_range_header({{1, 3}})}});
  5155. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5156. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5157. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5158. EXPECT_EQ("bytes 1-3/9", res->get_header_value("Content-Range"));
  5159. EXPECT_EQ(3, std::stoi(res->get_header_value("Content-Length")));
  5160. EXPECT_EQ("est", res->body);
  5161. }
  5162. TEST_F(ServerTest, GetFileContentWithContentType) {
  5163. auto res = cli_.Get("/file_content_with_content_type");
  5164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5165. EXPECT_EQ(StatusCode::OK_200, res->status);
  5166. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5167. EXPECT_EQ(5, std::stoi(res->get_header_value("Content-Length")));
  5168. EXPECT_EQ("file\n", res->body);
  5169. }
  5170. TEST_F(ServerTest, GetInvalidFileContent) {
  5171. auto res = cli_.Get("/invalid_file_content");
  5172. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5173. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5174. }
  5175. TEST_F(ServerTest, GetMethod200withPercentEncoding) {
  5176. auto res = cli_.Get("/%68%69"); // auto res = cli_.Get("/hi");
  5177. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5178. EXPECT_EQ("HTTP/1.1", res->version);
  5179. EXPECT_EQ(StatusCode::OK_200, res->status);
  5180. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5181. EXPECT_EQ(1U, res->get_header_value_count("Content-Type"));
  5182. EXPECT_EQ("Hello World!", res->body);
  5183. }
  5184. TEST_F(ServerTest, GetMethod302) {
  5185. auto res = cli_.Get("/");
  5186. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5187. EXPECT_EQ(StatusCode::Found_302, res->status);
  5188. EXPECT_EQ("/hi", res->get_header_value("Location"));
  5189. }
  5190. TEST_F(ServerTest, GetMethod302Redirect) {
  5191. cli_.set_follow_location(true);
  5192. auto res = cli_.Get("/");
  5193. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5194. EXPECT_EQ(StatusCode::OK_200, res->status);
  5195. EXPECT_EQ("Hello World!", res->body);
  5196. EXPECT_EQ("/hi", res->location);
  5197. }
  5198. TEST_F(ServerTest, GetMethod404) {
  5199. auto res = cli_.Get("/invalid");
  5200. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5201. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5202. }
  5203. TEST_F(ServerTest, HeadMethod200) {
  5204. auto res = cli_.Head("/hi");
  5205. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5206. EXPECT_EQ(StatusCode::OK_200, res->status);
  5207. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5208. EXPECT_TRUE(res->body.empty());
  5209. }
  5210. TEST_F(ServerTest, HeadMethod200Static) {
  5211. auto res = cli_.Head("/mount/dir/index.html");
  5212. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5213. EXPECT_EQ(StatusCode::OK_200, res->status);
  5214. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5215. EXPECT_EQ(104, std::stoi(res->get_header_value("Content-Length")));
  5216. EXPECT_TRUE(res->body.empty());
  5217. }
  5218. TEST_F(ServerTest, HeadMethod404) {
  5219. auto res = cli_.Head("/invalid");
  5220. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5221. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5222. EXPECT_TRUE(res->body.empty());
  5223. }
  5224. TEST_F(ServerTest, GetMethodPersonJohn) {
  5225. auto res = cli_.Get("/person/john");
  5226. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5227. EXPECT_EQ(StatusCode::OK_200, res->status);
  5228. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5229. EXPECT_EQ("programmer", res->body);
  5230. }
  5231. TEST_F(ServerTest, PostMethod1) {
  5232. auto res = cli_.Get("/person/john1");
  5233. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5234. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5235. res = cli_.Post("/person", "name=john1&note=coder",
  5236. "application/x-www-form-urlencoded");
  5237. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5238. ASSERT_EQ(StatusCode::OK_200, res->status);
  5239. res = cli_.Get("/person/john1");
  5240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5241. ASSERT_EQ(StatusCode::OK_200, res->status);
  5242. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5243. ASSERT_EQ("coder", res->body);
  5244. }
  5245. TEST_F(ServerTest, PostMethod2) {
  5246. auto res = cli_.Get("/person/john2");
  5247. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5248. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5249. Params params;
  5250. params.emplace("name", "john2");
  5251. params.emplace("note", "coder");
  5252. res = cli_.Post("/person", params);
  5253. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5254. ASSERT_EQ(StatusCode::OK_200, res->status);
  5255. res = cli_.Get("/person/john2");
  5256. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5257. ASSERT_EQ(StatusCode::OK_200, res->status);
  5258. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5259. ASSERT_EQ("coder", res->body);
  5260. }
  5261. TEST_F(ServerTest, PutMethod3) {
  5262. auto res = cli_.Get("/person/john3");
  5263. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5264. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5265. Params params;
  5266. params.emplace("name", "john3");
  5267. params.emplace("note", "coder");
  5268. res = cli_.Put("/person", params);
  5269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5270. ASSERT_EQ(StatusCode::OK_200, res->status);
  5271. res = cli_.Get("/person/john3");
  5272. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5273. ASSERT_EQ(StatusCode::OK_200, res->status);
  5274. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5275. ASSERT_EQ("coder", res->body);
  5276. }
  5277. TEST_F(ServerTest, DeleteMethod1) {
  5278. auto res = cli_.Get("/person/john4");
  5279. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5280. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5281. Params params;
  5282. params.emplace("name", "john4");
  5283. params.emplace("note", "coder");
  5284. res = cli_.Post("/person", params);
  5285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5286. ASSERT_EQ(StatusCode::OK_200, res->status);
  5287. res = cli_.Get("/person/john4");
  5288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5289. ASSERT_EQ(StatusCode::OK_200, res->status);
  5290. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5291. ASSERT_EQ("coder", res->body);
  5292. Params delete_params;
  5293. delete_params.emplace("name", "john4");
  5294. res = cli_.Delete("/person", delete_params);
  5295. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5296. ASSERT_EQ(StatusCode::OK_200, res->status);
  5297. ASSERT_EQ("DELETED", res->body);
  5298. res = cli_.Get("/person/john4");
  5299. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5300. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5301. }
  5302. TEST_F(ServerTest, DeleteMethod2) {
  5303. auto res = cli_.Get("/person/john5");
  5304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5305. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5306. Params params;
  5307. params.emplace("name", "john5");
  5308. params.emplace("note", "developer");
  5309. res = cli_.Post("/person", params);
  5310. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5311. ASSERT_EQ(StatusCode::OK_200, res->status);
  5312. res = cli_.Get("/person/john5");
  5313. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5314. ASSERT_EQ(StatusCode::OK_200, res->status);
  5315. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5316. ASSERT_EQ("developer", res->body);
  5317. Params delete_params;
  5318. delete_params.emplace("name", "john5");
  5319. Headers headers;
  5320. headers.emplace("Custom-Header", "test-value");
  5321. res = cli_.Delete("/person", headers, delete_params);
  5322. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5323. ASSERT_EQ(StatusCode::OK_200, res->status);
  5324. ASSERT_EQ("DELETED", res->body);
  5325. res = cli_.Get("/person/john5");
  5326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5327. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5328. }
  5329. TEST_F(ServerTest, DeleteMethod3) {
  5330. auto res = cli_.Get("/person/john6");
  5331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5332. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5333. Params params;
  5334. params.emplace("name", "john6");
  5335. params.emplace("note", "tester");
  5336. res = cli_.Post("/person", params);
  5337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5338. ASSERT_EQ(StatusCode::OK_200, res->status);
  5339. res = cli_.Get("/person/john6");
  5340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5341. ASSERT_EQ(StatusCode::OK_200, res->status);
  5342. ASSERT_EQ("text/plain", res->get_header_value("Content-Type"));
  5343. ASSERT_EQ("tester", res->body);
  5344. Params delete_params;
  5345. delete_params.emplace("name", "john6");
  5346. Headers headers;
  5347. headers.emplace("Custom-Header", "test-value");
  5348. res = cli_.Delete("/person", headers, delete_params, nullptr);
  5349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5350. ASSERT_EQ(StatusCode::OK_200, res->status);
  5351. ASSERT_EQ("DELETED", res->body);
  5352. res = cli_.Get("/person/john6");
  5353. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5354. ASSERT_EQ(StatusCode::NotFound_404, res->status);
  5355. }
  5356. TEST_F(ServerTest, PostWwwFormUrlEncodedJson) {
  5357. Params params;
  5358. params.emplace("json", JSON_DATA);
  5359. auto res = cli_.Post("/x-www-form-urlencoded-json", params);
  5360. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5361. ASSERT_EQ(StatusCode::OK_200, res->status);
  5362. ASSERT_EQ(JSON_DATA, res->body);
  5363. }
  5364. TEST_F(ServerTest, PostEmptyContent) {
  5365. auto res = cli_.Post("/empty", "", "text/plain");
  5366. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5367. ASSERT_EQ(StatusCode::OK_200, res->status);
  5368. ASSERT_EQ("empty", res->body);
  5369. }
  5370. TEST_F(ServerTest, PostEmptyContentWithNoContentType) {
  5371. auto res = cli_.Post("/empty-no-content-type");
  5372. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5373. ASSERT_EQ(StatusCode::OK_200, res->status);
  5374. ASSERT_EQ("empty-no-content-type", res->body);
  5375. }
  5376. TEST_F(ServerTest, PostPathOnly) {
  5377. auto res = cli_.Post("/path-only");
  5378. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5379. ASSERT_EQ(StatusCode::OK_200, res->status);
  5380. ASSERT_EQ("path-only", res->body);
  5381. }
  5382. TEST_F(ServerTest, PostPathAndHeadersOnly) {
  5383. auto res = cli_.Post("/path-headers-only",
  5384. Headers({{"hello", "world"}, {"hello2", "world2"}}));
  5385. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5386. ASSERT_EQ(StatusCode::OK_200, res->status);
  5387. ASSERT_EQ("path-headers-only", res->body);
  5388. }
  5389. TEST_F(ServerTest, PostLarge) {
  5390. auto res = cli_.Post("/post-large", LARGE_DATA, "text/plain");
  5391. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5392. ASSERT_EQ(StatusCode::OK_200, res->status);
  5393. EXPECT_EQ(LARGE_DATA, res->body);
  5394. }
  5395. TEST_F(ServerTest, PutEmptyContentWithNoContentType) {
  5396. auto res = cli_.Put("/empty-no-content-type");
  5397. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5398. ASSERT_EQ(StatusCode::OK_200, res->status);
  5399. ASSERT_EQ("empty-no-content-type", res->body);
  5400. }
  5401. TEST_F(ServerTest, GetMethodDir) {
  5402. auto res = cli_.Get("/dir/");
  5403. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5404. EXPECT_EQ(StatusCode::OK_200, res->status);
  5405. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5406. auto body = R"(<html>
  5407. <head>
  5408. </head>
  5409. <body>
  5410. <a href="/dir/test.html">Test</a>
  5411. <a href="/hi">hi</a>
  5412. </body>
  5413. </html>
  5414. )";
  5415. EXPECT_EQ(body, res->body);
  5416. }
  5417. TEST_F(ServerTest, GetMethodDirTest) {
  5418. auto res = cli_.Get("/dir/test.html");
  5419. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5420. EXPECT_EQ(StatusCode::OK_200, res->status);
  5421. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5422. EXPECT_EQ("test.html", res->body);
  5423. }
  5424. TEST_F(ServerTest, GetMethodDirTestWithDoubleDots) {
  5425. auto res = cli_.Get("/dir/../dir/test.html");
  5426. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5427. EXPECT_EQ(StatusCode::OK_200, res->status);
  5428. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5429. EXPECT_EQ("test.html", res->body);
  5430. }
  5431. TEST_F(ServerTest, GetMethodInvalidPath) {
  5432. auto res = cli_.Get("/dir/../test.html");
  5433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5435. }
  5436. TEST_F(ServerTest, GetMethodOutOfBaseDir) {
  5437. auto res = cli_.Get("/../www/dir/test.html");
  5438. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5439. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5440. }
  5441. TEST_F(ServerTest, GetMethodOutOfBaseDir2) {
  5442. auto res = cli_.Get("/dir/../../www/dir/test.html");
  5443. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5444. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5445. }
  5446. TEST_F(ServerTest, GetMethodDirMountTest) {
  5447. auto res = cli_.Get("/mount/dir/test.html");
  5448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5449. EXPECT_EQ(StatusCode::OK_200, res->status);
  5450. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5451. EXPECT_EQ("test.html", res->body);
  5452. }
  5453. TEST_F(ServerTest, GetMethodDirMountTestWithDoubleDots) {
  5454. auto res = cli_.Get("/mount/dir/../dir/test.html");
  5455. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5456. EXPECT_EQ(StatusCode::OK_200, res->status);
  5457. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  5458. EXPECT_EQ("test.html", res->body);
  5459. }
  5460. TEST_F(ServerTest, GetMethodInvalidMountPath) {
  5461. auto res = cli_.Get("/mount/dir/../test.html");
  5462. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5463. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5464. }
  5465. TEST_F(ServerTest, GetMethodEmbeddedNUL) {
  5466. auto res = cli_.Get("/mount/dir/test.html%00.js");
  5467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5468. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5469. }
  5470. TEST_F(ServerTest, GetMethodOutOfBaseDirMount) {
  5471. auto res = cli_.Get("/mount/../www2/dir/test.html");
  5472. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5474. }
  5475. TEST_F(ServerTest, GetMethodOutOfBaseDirMount2) {
  5476. auto res = cli_.Get("/mount/dir/../../www2/dir/test.html");
  5477. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5478. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5479. }
  5480. TEST_F(ServerTest, GetMethodOutOfBaseDirMountWithBackslash) {
  5481. auto res = cli_.Get("/mount/%2e%2e%5c/www2/dir/test.html");
  5482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5484. }
  5485. TEST_F(ServerTest, PostMethod303) {
  5486. auto res = cli_.Post("/1", "body", "text/plain");
  5487. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5488. EXPECT_EQ(StatusCode::SeeOther_303, res->status);
  5489. EXPECT_EQ("/2", res->get_header_value("Location"));
  5490. }
  5491. TEST_F(ServerTest, PostMethod303Redirect) {
  5492. cli_.set_follow_location(true);
  5493. auto res = cli_.Post("/1", "body", "text/plain");
  5494. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5495. EXPECT_EQ(StatusCode::OK_200, res->status);
  5496. EXPECT_EQ("redirected.", res->body);
  5497. EXPECT_EQ("/2", res->location);
  5498. }
  5499. TEST_F(ServerTest, UserDefinedMIMETypeMapping) {
  5500. auto res = cli_.Get("/dir/test.abcde");
  5501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5502. EXPECT_EQ(StatusCode::OK_200, res->status);
  5503. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5504. EXPECT_EQ("abcde", res->body);
  5505. }
  5506. TEST_F(ServerTest, StaticFileRange) {
  5507. auto res =
  5508. cli_.Get("/dir/test.abcde", Headers{{make_range_header({{2, 3}})}});
  5509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5510. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5511. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5512. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5513. EXPECT_EQ(true, res->has_header("Content-Range"));
  5514. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5515. EXPECT_EQ(std::string("cd"), res->body);
  5516. }
  5517. TEST_F(ServerTest, StaticFileRanges) {
  5518. auto res = cli_.Get("/dir/test.abcde",
  5519. Headers{{make_range_header({{1, 2}, {4, -1}})}});
  5520. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5521. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5522. EXPECT_TRUE(
  5523. res->get_header_value("Content-Type")
  5524. .find(
  5525. "multipart/byteranges; boundary=--cpp-httplib-multipart-data-") ==
  5526. 0);
  5527. EXPECT_EQ("266", res->get_header_value("Content-Length"));
  5528. }
  5529. TEST_F(ServerTest, StaticFileRangeHead) {
  5530. auto res = cli_.Head("/dir/test.abcde", {{make_range_header({{2, 3}})}});
  5531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5532. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5533. EXPECT_EQ("text/abcde", res->get_header_value("Content-Type"));
  5534. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5535. EXPECT_EQ(true, res->has_header("Content-Range"));
  5536. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  5537. }
  5538. TEST_F(ServerTest, StaticFileRangeBigFile) {
  5539. auto res = cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{-1, 5}})}});
  5540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5541. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5542. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5543. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  5544. EXPECT_EQ(true, res->has_header("Content-Range"));
  5545. EXPECT_EQ("bytes 1048571-1048575/1048576",
  5546. res->get_header_value("Content-Range"));
  5547. EXPECT_EQ("LAST\n", res->body);
  5548. }
  5549. TEST_F(ServerTest, StaticFileRangeBigFile2) {
  5550. auto res =
  5551. cli_.Get("/dir/1MB.txt", Headers{{make_range_header({{1, 4097}})}});
  5552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5553. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5554. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5555. EXPECT_EQ("4097", res->get_header_value("Content-Length"));
  5556. EXPECT_EQ(true, res->has_header("Content-Range"));
  5557. EXPECT_EQ("bytes 1-4097/1048576", res->get_header_value("Content-Range"));
  5558. }
  5559. TEST_F(ServerTest, StaticFileBigFile) {
  5560. auto res = cli_.Get("/dir/1MB.txt");
  5561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5562. EXPECT_EQ(StatusCode::OK_200, res->status);
  5563. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  5564. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  5565. }
  5566. TEST_F(ServerTest, InvalidBaseDirMount) {
  5567. EXPECT_EQ(false, svr_.set_mount_point("invalid_mount_point", "./www3"));
  5568. }
  5569. TEST_F(ServerTest, Binary) {
  5570. std::vector<char> binary{0x00, 0x01, 0x02, 0x03};
  5571. auto res = cli_.Post("/binary", binary.data(), binary.size(),
  5572. "application/octet-stream");
  5573. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5574. ASSERT_EQ(StatusCode::OK_200, res->status);
  5575. ASSERT_EQ(4U, res->body.size());
  5576. res = cli_.Put("/binary", binary.data(), binary.size(),
  5577. "application/octet-stream");
  5578. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5579. ASSERT_EQ(StatusCode::OK_200, res->status);
  5580. ASSERT_EQ(4U, res->body.size());
  5581. res = cli_.Patch("/binary", binary.data(), binary.size(),
  5582. "application/octet-stream");
  5583. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5584. ASSERT_EQ(StatusCode::OK_200, res->status);
  5585. ASSERT_EQ(4U, res->body.size());
  5586. res = cli_.Delete("/binary", binary.data(), binary.size(),
  5587. "application/octet-stream");
  5588. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5589. ASSERT_EQ(StatusCode::OK_200, res->status);
  5590. ASSERT_EQ(4U, res->body.size());
  5591. }
  5592. TEST_F(ServerTest, BinaryString) {
  5593. auto binary = std::string("\x00\x01\x02\x03", 4);
  5594. auto res = cli_.Post("/binary", binary, "application/octet-stream");
  5595. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5596. ASSERT_EQ(StatusCode::OK_200, res->status);
  5597. ASSERT_EQ(4U, res->body.size());
  5598. res = cli_.Put("/binary", binary, "application/octet-stream");
  5599. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5600. ASSERT_EQ(StatusCode::OK_200, res->status);
  5601. ASSERT_EQ(4U, res->body.size());
  5602. res = cli_.Patch("/binary", binary, "application/octet-stream");
  5603. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5604. ASSERT_EQ(StatusCode::OK_200, res->status);
  5605. ASSERT_EQ(4U, res->body.size());
  5606. res = cli_.Delete("/binary", binary, "application/octet-stream");
  5607. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5608. ASSERT_EQ(StatusCode::OK_200, res->status);
  5609. ASSERT_EQ(4U, res->body.size());
  5610. }
  5611. TEST_F(ServerTest, EmptyRequest) {
  5612. auto res = cli_.Get("");
  5613. ASSERT_TRUE(!res);
  5614. EXPECT_EQ(Error::Connection, res.error());
  5615. }
  5616. TEST_F(ServerTest, LongRequest) {
  5617. std::string request;
  5618. for (size_t i = 0; i < 545; i++) {
  5619. request += "/TooLongRequest";
  5620. }
  5621. request += "OK";
  5622. auto res = cli_.Get(request.c_str());
  5623. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5624. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5625. }
  5626. TEST_F(ServerTest, TooLongRequest) {
  5627. std::string request;
  5628. for (size_t i = 0; i < 546; i++) {
  5629. request += "/TooLongRequest";
  5630. }
  5631. request += "_NG";
  5632. auto start = std::chrono::high_resolution_clock::now();
  5633. cli_.set_keep_alive(true);
  5634. auto res = cli_.Get(request.c_str());
  5635. auto end = std::chrono::high_resolution_clock::now();
  5636. auto elapsed =
  5637. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5638. .count();
  5639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5640. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5641. EXPECT_LE(elapsed, 1000);
  5642. EXPECT_EQ("close", res->get_header_value("Connection"));
  5643. EXPECT_FALSE(cli_.is_socket_open());
  5644. }
  5645. TEST_F(ServerTest, AlmostTooLongRequest) {
  5646. // test for #2046 - URI length check shouldn't include other content on req
  5647. // line URI is max URI length, minus 14 other chars in req line (GET, space,
  5648. // leading /, space, HTTP/1.1)
  5649. std::string request =
  5650. "/" + string(CPPHTTPLIB_REQUEST_URI_MAX_LENGTH - 14, 'A');
  5651. auto res = cli_.Get(request.c_str());
  5652. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5653. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5654. }
  5655. TEST_F(ServerTest, LongHeader) {
  5656. Request req;
  5657. req.method = "GET";
  5658. req.path = "/hi";
  5659. std::string host_and_port;
  5660. host_and_port += HOST;
  5661. host_and_port += ":";
  5662. host_and_port += std::to_string(PORT);
  5663. req.headers.emplace("Host", host_and_port.c_str());
  5664. req.headers.emplace("Accept", "*/*");
  5665. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5666. req.headers.emplace(
  5667. "Header-Name",
  5668. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5669. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5670. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5671. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5672. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5673. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5674. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5675. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5676. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5677. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5678. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5679. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5680. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5681. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5682. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5683. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5684. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5685. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5686. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5687. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5688. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5689. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5690. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5691. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5692. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5693. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5694. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5695. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5696. "@@@@@@@@@@@@@@@@");
  5697. auto res = std::make_shared<Response>();
  5698. auto error = Error::Success;
  5699. auto ret = cli_.send(req, *res, error);
  5700. ASSERT_TRUE(ret);
  5701. EXPECT_EQ(StatusCode::OK_200, res->status);
  5702. }
  5703. TEST_F(ServerTest, LongQueryValue) {
  5704. auto start = std::chrono::high_resolution_clock::now();
  5705. cli_.set_keep_alive(true);
  5706. auto res = cli_.Get(LONG_QUERY_URL.c_str());
  5707. auto end = std::chrono::high_resolution_clock::now();
  5708. auto elapsed =
  5709. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  5710. .count();
  5711. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5712. EXPECT_EQ(StatusCode::UriTooLong_414, res->status);
  5713. EXPECT_LE(elapsed, 1000);
  5714. EXPECT_EQ("close", res->get_header_value("Connection"));
  5715. EXPECT_FALSE(cli_.is_socket_open());
  5716. }
  5717. TEST_F(ServerTest, TooLongQueryValue) {
  5718. auto res = cli_.Get(TOO_LONG_QUERY_URL.c_str());
  5719. ASSERT_FALSE(res);
  5720. EXPECT_EQ(Error::Read, res.error());
  5721. }
  5722. TEST_F(ServerTest, TooLongHeader) {
  5723. Request req;
  5724. req.method = "GET";
  5725. req.path = "/hi";
  5726. std::string host_and_port;
  5727. host_and_port += HOST;
  5728. host_and_port += ":";
  5729. host_and_port += std::to_string(PORT);
  5730. req.headers.emplace("Host", host_and_port.c_str());
  5731. req.headers.emplace("Accept", "*/*");
  5732. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5733. req.headers.emplace(
  5734. "Header-Name",
  5735. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5736. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5737. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5738. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5739. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5740. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5741. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5742. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5743. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5744. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5745. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5746. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5747. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5748. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5749. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5750. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5751. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5752. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5753. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5754. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5755. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5756. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5757. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5758. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5759. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5760. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5761. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5762. "@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@"
  5763. "@@@@@@@@@@@@@@@@@");
  5764. auto res = std::make_shared<Response>();
  5765. auto error = Error::Success;
  5766. auto ret = cli_.send(req, *res, error);
  5767. ASSERT_TRUE(ret);
  5768. EXPECT_EQ(StatusCode::OK_200, res->status);
  5769. }
  5770. TEST_F(ServerTest, HeaderCountAtLimit) {
  5771. // Test with headers just under the 100 limit
  5772. httplib::Headers headers;
  5773. // Add 95 custom headers (the client will add Host, User-Agent, Accept, etc.)
  5774. // This should keep us just under the 100 header limit
  5775. for (int i = 0; i < 95; i++) {
  5776. std::string name = "X-Test-Header-" + std::to_string(i);
  5777. std::string value = "value" + std::to_string(i);
  5778. headers.emplace(name, value);
  5779. }
  5780. // This should work fine as we're under the limit
  5781. auto res = cli_.Get("/hi", headers);
  5782. EXPECT_TRUE(res);
  5783. if (res) { EXPECT_EQ(StatusCode::OK_200, res->status); }
  5784. }
  5785. TEST_F(ServerTest, HeaderCountExceedsLimit) {
  5786. // Test with many headers to exceed the 100 limit
  5787. httplib::Headers headers;
  5788. // Add 150 headers to definitely exceed the 100 limit
  5789. for (int i = 0; i < 150; i++) {
  5790. std::string name = "X-Test-Header-" + std::to_string(i);
  5791. std::string value = "value" + std::to_string(i);
  5792. headers.emplace(name, value);
  5793. }
  5794. // This should fail due to exceeding header count limit
  5795. cli_.set_keep_alive(true);
  5796. auto res = cli_.Get("/hi", headers);
  5797. // The server should respond with 400 Bad Request
  5798. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5799. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5800. EXPECT_EQ("close", res->get_header_value("Connection"));
  5801. EXPECT_FALSE(cli_.is_socket_open());
  5802. }
  5803. TEST_F(ServerTest, PercentEncoding) {
  5804. auto res = cli_.Get("/e%6edwith%");
  5805. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5806. EXPECT_EQ(StatusCode::OK_200, res->status);
  5807. }
  5808. TEST_F(ServerTest, PercentEncodingUnicode) {
  5809. auto res = cli_.Get("/e%u006edwith%");
  5810. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5811. EXPECT_EQ(StatusCode::OK_200, res->status);
  5812. }
  5813. TEST_F(ServerTest, InvalidPercentEncoding) {
  5814. auto res = cli_.Get("/%endwith%");
  5815. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5816. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5817. }
  5818. TEST_F(ServerTest, InvalidPercentEncodingUnicode) {
  5819. auto res = cli_.Get("/%uendwith%");
  5820. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5821. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5822. }
  5823. TEST_F(ServerTest, EndWithPercentCharacterInQuery) {
  5824. auto res = cli_.Get("/hello?aaa=bbb%");
  5825. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5826. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  5827. }
  5828. TEST_F(ServerTest, PlusSignEncoding) {
  5829. auto res = cli_.Get("/a+%2Bb?a %2bb=a %2Bb");
  5830. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5831. EXPECT_EQ(StatusCode::OK_200, res->status);
  5832. EXPECT_EQ("a +b", res->body);
  5833. }
  5834. TEST_F(ServerTest, HeaderCountSecurityTest) {
  5835. // This test simulates a potential DoS attack using many headers
  5836. // to verify our security fix prevents memory exhaustion
  5837. httplib::Headers attack_headers;
  5838. // Attempt to add many headers like an attacker would (200 headers to far
  5839. // exceed limit)
  5840. for (int i = 0; i < 200; i++) {
  5841. std::string name = "X-Attack-Header-" + std::to_string(i);
  5842. std::string value = "attack_payload_" + std::to_string(i);
  5843. attack_headers.emplace(name, value);
  5844. }
  5845. // Try to POST with excessive headers
  5846. cli_.set_keep_alive(true);
  5847. auto res = cli_.Post("/", attack_headers, "test_data", "text/plain");
  5848. // Should either fail or return 400 Bad Request due to security limit
  5849. if (res) {
  5850. // If we get a response, it should be 400 Bad Request
  5851. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  5852. EXPECT_EQ("close", res->get_header_value("Connection"));
  5853. }
  5854. EXPECT_FALSE(cli_.is_socket_open());
  5855. }
  5856. TEST_F(ServerTest, MultipartFormData) {
  5857. UploadFormDataItems items = {
  5858. {"text1", "text default", "", ""},
  5859. {"text2", "aωb", "", ""},
  5860. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5861. {"file2", "{\n \"world\", true\n}\n", "world.json", "application/json"},
  5862. {"file3", "", "", "application/octet-stream"},
  5863. {"file4", "", "", " application/json tmp-string "}};
  5864. auto res = cli_.Post("/multipart", items);
  5865. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5866. EXPECT_EQ(StatusCode::OK_200, res->status);
  5867. }
  5868. TEST_F(ServerTest, MultipartFormDataMultiFileValues) {
  5869. UploadFormDataItems items = {
  5870. {"text", "default text", "", ""},
  5871. {"multi_text1", "aaaaa", "", ""},
  5872. {"multi_text1", "bbbbb", "", ""},
  5873. {"multi_file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  5874. {"multi_file1", "{\n \"world\", true\n}\n", "world.json",
  5875. "application/json"},
  5876. };
  5877. auto res = cli_.Post("/multipart/multi_file_values", items);
  5878. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5879. EXPECT_EQ(StatusCode::OK_200, res->status);
  5880. }
  5881. TEST_F(ServerTest, CaseInsensitiveHeaderName) {
  5882. auto res = cli_.Get("/hi");
  5883. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5884. EXPECT_EQ(StatusCode::OK_200, res->status);
  5885. EXPECT_EQ("text/plain", res->get_header_value("content-type"));
  5886. EXPECT_EQ("Hello World!", res->body);
  5887. }
  5888. TEST_F(ServerTest, CaseInsensitiveTransferEncoding) {
  5889. Request req;
  5890. req.method = "POST";
  5891. req.path = "/chunked";
  5892. std::string host_and_port;
  5893. host_and_port += HOST;
  5894. host_and_port += ":";
  5895. host_and_port += std::to_string(PORT);
  5896. req.headers.emplace("Host", host_and_port.c_str());
  5897. req.headers.emplace("Accept", "*/*");
  5898. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  5899. req.headers.emplace("Content-Type", "text/plain");
  5900. req.headers.emplace("Content-Length", "0");
  5901. req.headers.emplace(
  5902. "Transfer-Encoding",
  5903. "Chunked"); // Note, "Chunked" rather than typical "chunked".
  5904. // Client does not chunk, so make a chunked body manually.
  5905. req.body = "4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n";
  5906. auto res = std::make_shared<Response>();
  5907. auto error = Error::Success;
  5908. auto ret = cli_.send(req, *res, error);
  5909. ASSERT_TRUE(ret);
  5910. EXPECT_EQ(StatusCode::OK_200, res->status);
  5911. }
  5912. template <typename ClientT>
  5913. static void expect_chunked_body_status(ClientT &cli, const char *body,
  5914. int expected_status) {
  5915. Request req;
  5916. req.method = "POST";
  5917. req.path = "/chunked";
  5918. std::string host_and_port;
  5919. host_and_port += HOST;
  5920. host_and_port += ":";
  5921. host_and_port += std::to_string(PORT);
  5922. req.headers.emplace("Host", host_and_port.c_str());
  5923. req.headers.emplace("Content-Length", "0");
  5924. req.headers.emplace("Transfer-Encoding", "chunked");
  5925. req.body = body;
  5926. auto res = std::make_shared<Response>();
  5927. auto error = Error::Success;
  5928. ASSERT_TRUE(cli.send(req, *res, error));
  5929. EXPECT_EQ(expected_status, res->status);
  5930. }
  5931. // GHSA-h6wq-j5mv-f3q8: the server must reject malformed chunk-size lines
  5932. // rather than treat them as valid lengths.
  5933. template <typename ClientT>
  5934. static void expect_chunked_body_rejected(ClientT &cli, const char *body) {
  5935. expect_chunked_body_status(cli, body, StatusCode::BadRequest_400);
  5936. }
  5937. TEST_F(ServerTest, RejectsNegativeChunkSize) {
  5938. expect_chunked_body_rejected(cli_, "-2\r\nAAAA\r\n0\r\n\r\n");
  5939. }
  5940. TEST_F(ServerTest, RejectsChunkSizeWithLeadingPlus) {
  5941. expect_chunked_body_rejected(
  5942. cli_, "+4\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5943. }
  5944. // RFC 9112 §7.1.1: a chunk-ext is made of tokens and quoted-strings, so the
  5945. // chunk-size line carries no CR, LF or other control character ahead of its
  5946. // terminator. Such a line must be refused rather than read as extension text.
  5947. TEST_F(ServerTest, RejectsBareLFInChunkExtension) {
  5948. expect_chunked_body_rejected(
  5949. cli_, "4;\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5950. }
  5951. TEST_F(ServerTest, RejectsBareLFAfterChunkSize) {
  5952. expect_chunked_body_rejected(
  5953. cli_, "4\nxx\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5954. }
  5955. TEST_F(ServerTest, RejectsBareCRInChunkExtension) {
  5956. expect_chunked_body_rejected(
  5957. cli_, "4;a\rb\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5958. }
  5959. TEST_F(ServerTest, RejectsControlCharacterInChunkExtension) {
  5960. // The literal stays split: a hex escape consumes every hex digit that
  5961. // follows, so "\x01b" would be the single byte \x1b, not \x01 then 'b'.
  5962. expect_chunked_body_rejected(
  5963. cli_, "4;a\x01"
  5964. "b\r\ndech\r\nf\r\nunked post body\r\n0\r\n\r\n");
  5965. }
  5966. TEST_F(ServerTest, AcceptsChunkExtension) {
  5967. expect_chunked_body_status(cli_,
  5968. "4;name=value\r\ndech\r\n"
  5969. "f ; note=\"a;b c\"\r\nunked post body\r\n"
  5970. "0;last\r\n\r\n",
  5971. StatusCode::OK_200);
  5972. }
  5973. TEST_F(ServerTest, GetStreamed2) {
  5974. auto res = cli_.Get("/streamed", Headers{{make_range_header({{2, 3}})}});
  5975. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5976. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  5977. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  5978. EXPECT_EQ(true, res->has_header("Content-Range"));
  5979. EXPECT_EQ("bytes 2-3/6", res->get_header_value("Content-Range"));
  5980. EXPECT_EQ(std::string("ab"), res->body);
  5981. }
  5982. TEST_F(ServerTest, GetStreamed) {
  5983. auto res = cli_.Get("/streamed");
  5984. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5985. EXPECT_EQ(StatusCode::OK_200, res->status);
  5986. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  5987. EXPECT_EQ(std::string("aaabbb"), res->body);
  5988. }
  5989. TEST_F(ServerTest, GetStreamedWithoutLengthWithRange) {
  5990. auto res = cli_.Get("/streamed-without-length",
  5991. Headers{make_range_header({{0, -1}})});
  5992. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  5993. EXPECT_EQ(StatusCode::OK_200, res->status);
  5994. EXPECT_EQ(false, res->has_header("Content-Length"));
  5995. EXPECT_EQ(false, res->has_header("Content-Range"));
  5996. EXPECT_EQ(std::string("abcdefg"), res->body);
  5997. }
  5998. TEST_F(ServerTest, GetStreamedWithRange1) {
  5999. auto res =
  6000. cli_.Get("/streamed-with-range", Headers{{make_range_header({{3, 5}})}});
  6001. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6002. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6003. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6004. EXPECT_EQ(true, res->has_header("Content-Range"));
  6005. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6006. EXPECT_EQ(std::string("def"), res->body);
  6007. }
  6008. TEST_F(ServerTest, GetStreamedWithRange2) {
  6009. auto res =
  6010. cli_.Get("/streamed-with-range", Headers{{make_range_header({{1, -1}})}});
  6011. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6012. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6013. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6014. EXPECT_EQ(true, res->has_header("Content-Range"));
  6015. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6016. EXPECT_EQ(std::string("bcdefg"), res->body);
  6017. }
  6018. TEST_F(ServerTest, GetStreamedWithRangeSuffix1) {
  6019. auto res = cli_.Get("/streamed-with-range", Headers{{"Range", "bytes=-3"}});
  6020. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6021. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6022. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6023. EXPECT_EQ(true, res->has_header("Content-Range"));
  6024. EXPECT_EQ("bytes 4-6/7", res->get_header_value("Content-Range"));
  6025. EXPECT_EQ(std::string("efg"), res->body);
  6026. }
  6027. TEST_F(ServerTest, GetStreamedWithRangeSuffix2) {
  6028. auto res =
  6029. cli_.Get("/streamed-with-range?error", Headers{{"Range", "bytes=-9999"}});
  6030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6031. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6032. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6033. EXPECT_EQ(false, res->has_header("Content-Range"));
  6034. EXPECT_EQ(0U, res->body.size());
  6035. }
  6036. TEST_F(ServerTest, GetStreamedWithRangeAndNonPartialStatus) {
  6037. // Only a 206 is served as a partial representation. Under any other status
  6038. // `apply_ranges()` reported the full content length, so the body must match
  6039. // that header, and the content provider must never be asked for an offset
  6040. // outside the representation.
  6041. auto check = [&](int status, const char *range) {
  6042. auto path =
  6043. std::string("/streamed-with-range?status=") + std::to_string(status);
  6044. auto ctx = path + " Range: " + range;
  6045. auto res = cli_.Get(path, Headers{{"Range", range}});
  6046. ASSERT_TRUE(res) << ctx << " Error: " << to_string(res.error());
  6047. EXPECT_EQ(status, res->status) << ctx;
  6048. EXPECT_EQ("7", res->get_header_value("Content-Length")) << ctx;
  6049. EXPECT_EQ("text/plain", res->get_header_value("Content-Type")) << ctx;
  6050. EXPECT_FALSE(res->has_header("Content-Range")) << ctx;
  6051. EXPECT_EQ(std::string("abcdefg"), res->body) << ctx;
  6052. };
  6053. // Non-2xx: `detail::range_error()` never validated these ranges at all.
  6054. check(403, "bytes=3-5");
  6055. // The offset is far past the representation.
  6056. check(403, "bytes=100000-100200");
  6057. // `first_pos` is still -1 here, and the bounds asserts in
  6058. // `get_range_offset_and_length()` are compiled out under NDEBUG.
  6059. check(403, "bytes=-3");
  6060. // `apply_ranges()` makes no boundary for a non-206 response, so the
  6061. // multipart branch would have written one that is empty.
  6062. check(403, "bytes=1-2, 4-5");
  6063. // 2xx but not 206: the ranges were validated, yet the Content-Length still
  6064. // covers the whole representation.
  6065. check(200, "bytes=3-5");
  6066. check(200, "bytes=1-2, 4-5");
  6067. }
  6068. TEST_F(ServerTest, GetStreamedWithRangeError) {
  6069. auto res =
  6070. cli_.Get("/streamed-with-range",
  6071. Headers{{"Range", "bytes=92233720368547758079223372036854775806-"
  6072. "92233720368547758079223372036854775807"}});
  6073. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6074. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6075. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6076. EXPECT_EQ(false, res->has_header("Content-Range"));
  6077. EXPECT_EQ(0U, res->body.size());
  6078. }
  6079. TEST_F(ServerTest, GetRangeWithMaxLongLength) {
  6080. auto res = cli_.Get(
  6081. "/with-range",
  6082. Headers{{"Range",
  6083. "bytes=0-" + std::to_string(std::numeric_limits<long>::max())},
  6084. {"Accept-Encoding", ""}});
  6085. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6086. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6087. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6088. EXPECT_EQ(true, res->has_header("Content-Range"));
  6089. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6090. EXPECT_EQ(std::string("abcdefg"), res->body);
  6091. }
  6092. TEST_F(ServerTest, GetRangeWithZeroToInfinite) {
  6093. auto res = cli_.Get("/with-range", Headers{
  6094. {"Range", "bytes=0-"},
  6095. {"Accept-Encoding", ""},
  6096. });
  6097. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6098. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6099. EXPECT_EQ("7", res->get_header_value("Content-Length"));
  6100. EXPECT_EQ(true, res->has_header("Content-Range"));
  6101. EXPECT_EQ("bytes 0-6/7", res->get_header_value("Content-Range"));
  6102. EXPECT_EQ(std::string("abcdefg"), res->body);
  6103. }
  6104. TEST_F(ServerTest, GetStreamedWithRangeMultipart) {
  6105. auto res = cli_.Get("/streamed-with-range",
  6106. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6107. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6108. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6109. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6110. EXPECT_EQ(false, res->has_header("Content-Range"));
  6111. EXPECT_EQ(267U, res->body.size());
  6112. // Check that both range contents are present
  6113. EXPECT_TRUE(res->body.find("bc\r\n") != std::string::npos);
  6114. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6115. // Check that Content-Range headers are present for both ranges
  6116. EXPECT_TRUE(res->body.find("Content-Range: bytes 1-2/7") !=
  6117. std::string::npos);
  6118. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6119. std::string::npos);
  6120. }
  6121. TEST_F(ServerTest, GetStreamedWithTooManyRanges) {
  6122. Ranges ranges;
  6123. for (size_t i = 0; i < CPPHTTPLIB_RANGE_MAX_COUNT + 1; i++) {
  6124. ranges.emplace_back(0, -1);
  6125. }
  6126. auto res = cli_.Get("/streamed-with-range?error",
  6127. Headers{{make_range_header(ranges)}});
  6128. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6129. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6130. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6131. EXPECT_EQ(false, res->has_header("Content-Range"));
  6132. EXPECT_EQ(0U, res->body.size());
  6133. }
  6134. TEST_F(ServerTest, GetStreamedWithOverwrapping) {
  6135. auto res = cli_.Get("/streamed-with-range",
  6136. Headers{{make_range_header({{1, 4}, {2, 5}})}});
  6137. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6138. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6139. EXPECT_EQ(5U, res->body.size());
  6140. // Check that overlapping ranges are coalesced into a single range
  6141. EXPECT_EQ("bcdef", res->body);
  6142. EXPECT_EQ("bytes 1-5/7", res->get_header_value("Content-Range"));
  6143. // Should be single range, not multipart
  6144. EXPECT_TRUE(res->has_header("Content-Range"));
  6145. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6146. }
  6147. TEST_F(ServerTest, GetStreamedWithNonAscendingRanges) {
  6148. auto res = cli_.Get("/streamed-with-range",
  6149. Headers{{make_range_header({{4, 5}, {0, 2}})}});
  6150. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6151. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6152. EXPECT_EQ(268U, res->body.size());
  6153. // Check that both range contents are present
  6154. EXPECT_TRUE(res->body.find("ef\r\n") != std::string::npos);
  6155. EXPECT_TRUE(res->body.find("abc\r\n") != std::string::npos);
  6156. // Check that Content-Range headers are present for both ranges
  6157. EXPECT_TRUE(res->body.find("Content-Range: bytes 4-5/7") !=
  6158. std::string::npos);
  6159. EXPECT_TRUE(res->body.find("Content-Range: bytes 0-2/7") !=
  6160. std::string::npos);
  6161. }
  6162. TEST_F(ServerTest, GetStreamedWithDuplicateRanges) {
  6163. auto res = cli_.Get("/streamed-with-range",
  6164. Headers{{make_range_header({{0, 2}, {0, 2}})}});
  6165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6166. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6167. EXPECT_EQ(269U, res->body.size());
  6168. // Check that both duplicate range contents are present
  6169. size_t first_abc = res->body.find("abc\r\n");
  6170. EXPECT_TRUE(first_abc != std::string::npos);
  6171. size_t second_abc = res->body.find("abc\r\n", first_abc + 1);
  6172. EXPECT_TRUE(second_abc != std::string::npos);
  6173. // Check that Content-Range headers are present for both ranges
  6174. size_t first_range = res->body.find("Content-Range: bytes 0-2/7");
  6175. EXPECT_TRUE(first_range != std::string::npos);
  6176. size_t second_range =
  6177. res->body.find("Content-Range: bytes 0-2/7", first_range + 1);
  6178. EXPECT_TRUE(second_range != std::string::npos);
  6179. }
  6180. TEST_F(ServerTest, GetStreamedWithRangesMoreThanTwoOverwrapping) {
  6181. auto res =
  6182. cli_.Get("/streamed-with-range?error",
  6183. Headers{{make_range_header({{0, 1}, {1, 2}, {2, 3}, {3, 4}})}});
  6184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6185. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6186. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  6187. EXPECT_EQ(false, res->has_header("Content-Range"));
  6188. EXPECT_EQ(0U, res->body.size());
  6189. }
  6190. TEST_F(ServerTest, GetStreamedEndless) {
  6191. uint64_t offset = 0;
  6192. auto res = cli_.Get("/streamed-cancel",
  6193. [&](const char * /*data*/, uint64_t data_length) {
  6194. if (offset < 100) {
  6195. offset += data_length;
  6196. return true;
  6197. }
  6198. return false;
  6199. });
  6200. ASSERT_TRUE(!res);
  6201. EXPECT_EQ(Error::Canceled, res.error());
  6202. }
  6203. TEST_F(ServerTest, ClientStop) {
  6204. std::atomic_size_t count{4};
  6205. std::vector<std::thread> threads;
  6206. for (auto i = count.load(); i != 0; --i) {
  6207. threads.emplace_back([&]() {
  6208. auto res = cli_.Get("/streamed-cancel",
  6209. [&](const char *, uint64_t) { return true; });
  6210. --count;
  6211. ASSERT_TRUE(!res);
  6212. EXPECT_TRUE(res.error() == Error::Canceled ||
  6213. res.error() == Error::Read || res.error() == Error::Write);
  6214. });
  6215. }
  6216. std::this_thread::sleep_for(std::chrono::seconds(2));
  6217. while (count != 0) {
  6218. cli_.stop();
  6219. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  6220. }
  6221. for (auto &t : threads) {
  6222. t.join();
  6223. }
  6224. }
  6225. TEST_F(ServerTest, GetWithRange1) {
  6226. auto res = cli_.Get("/with-range", Headers{
  6227. make_range_header({{3, 5}}),
  6228. {"Accept-Encoding", ""},
  6229. });
  6230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6231. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6232. EXPECT_EQ("3", res->get_header_value("Content-Length"));
  6233. EXPECT_EQ(true, res->has_header("Content-Range"));
  6234. EXPECT_EQ("bytes 3-5/7", res->get_header_value("Content-Range"));
  6235. EXPECT_EQ(std::string("def"), res->body);
  6236. }
  6237. TEST_F(ServerTest, GetWithRange2) {
  6238. auto res = cli_.Get("/with-range", Headers{
  6239. make_range_header({{1, -1}}),
  6240. {"Accept-Encoding", ""},
  6241. });
  6242. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6243. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6244. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6245. EXPECT_EQ(true, res->has_header("Content-Range"));
  6246. EXPECT_EQ("bytes 1-6/7", res->get_header_value("Content-Range"));
  6247. EXPECT_EQ(std::string("bcdefg"), res->body);
  6248. }
  6249. TEST_F(ServerTest, GetWithRange3) {
  6250. auto res = cli_.Get("/with-range", Headers{
  6251. make_range_header({{0, 0}}),
  6252. {"Accept-Encoding", ""},
  6253. });
  6254. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6255. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6256. EXPECT_EQ("1", res->get_header_value("Content-Length"));
  6257. EXPECT_EQ(true, res->has_header("Content-Range"));
  6258. EXPECT_EQ("bytes 0-0/7", res->get_header_value("Content-Range"));
  6259. EXPECT_EQ(std::string("a"), res->body);
  6260. }
  6261. TEST_F(ServerTest, GetWithRange4) {
  6262. auto res = cli_.Get("/with-range", Headers{
  6263. make_range_header({{-1, 2}}),
  6264. {"Accept-Encoding", ""},
  6265. });
  6266. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6267. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6268. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  6269. EXPECT_EQ(true, res->has_header("Content-Range"));
  6270. EXPECT_EQ("bytes 5-6/7", res->get_header_value("Content-Range"));
  6271. EXPECT_EQ(std::string("fg"), res->body);
  6272. }
  6273. TEST_F(ServerTest, GetWithRange5) {
  6274. auto res = cli_.Get("/with-range", Headers{
  6275. make_range_header({{0, 5}}),
  6276. {"Accept-Encoding", ""},
  6277. });
  6278. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6279. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6280. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  6281. EXPECT_EQ(true, res->has_header("Content-Range"));
  6282. EXPECT_EQ("bytes 0-5/7", res->get_header_value("Content-Range"));
  6283. EXPECT_EQ(std::string("abcdef"), res->body);
  6284. }
  6285. TEST_F(ServerTest, GetWithRangeOffsetGreaterThanContent) {
  6286. auto res =
  6287. cli_.Get("/with-range", Headers{{make_range_header({{10000, 20000}})}});
  6288. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6289. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6290. }
  6291. TEST_F(ServerTest, GetWithRangeMultipart) {
  6292. auto res =
  6293. cli_.Get("/with-range", Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6295. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  6296. EXPECT_EQ("267", res->get_header_value("Content-Length"));
  6297. EXPECT_EQ(false, res->has_header("Content-Range"));
  6298. EXPECT_EQ(267U, res->body.size());
  6299. }
  6300. TEST_F(ServerTest, GetWithRangeMultipartOffsetGreaterThanContent) {
  6301. auto res = cli_.Get("/with-range",
  6302. Headers{{make_range_header({{-1, 2}, {10000, 30000}})}});
  6303. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6304. EXPECT_EQ(StatusCode::RangeNotSatisfiable_416, res->status);
  6305. }
  6306. TEST_F(ServerTest, GetWithRangeCustomizedResponse) {
  6307. auto res = cli_.Get("/with-range-customized-response",
  6308. Headers{{make_range_header({{1, 2}})}});
  6309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6310. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6311. EXPECT_EQ(true, res->has_header("Content-Length"));
  6312. EXPECT_EQ(false, res->has_header("Content-Range"));
  6313. EXPECT_EQ(JSON_DATA, res->body);
  6314. }
  6315. TEST_F(ServerTest, GetWithRangeMultipartCustomizedResponseMultipleRange) {
  6316. auto res = cli_.Get("/with-range-customized-response",
  6317. Headers{{make_range_header({{1, 2}, {4, 5}})}});
  6318. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6319. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  6320. EXPECT_EQ(true, res->has_header("Content-Length"));
  6321. EXPECT_EQ(false, res->has_header("Content-Range"));
  6322. EXPECT_EQ(JSON_DATA, res->body);
  6323. }
  6324. TEST_F(ServerTest, Issue1772) {
  6325. auto res = cli_.Get("/issue1772", Headers{{make_range_header({{1000, -1}})}});
  6326. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6327. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  6328. }
  6329. TEST_F(ServerTest, Issue609) {
  6330. auto res = cli_.Delete("/issue609");
  6331. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6332. EXPECT_EQ(StatusCode::OK_200, res->status);
  6333. EXPECT_EQ(std::string("ok"), res->body);
  6334. }
  6335. TEST_F(ServerTest, GetStreamedChunked) {
  6336. auto res = cli_.Get("/streamed-chunked");
  6337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6338. EXPECT_EQ(StatusCode::OK_200, res->status);
  6339. EXPECT_EQ(std::string("123456789"), res->body);
  6340. }
  6341. TEST_F(ServerTest, GetStreamedChunked2) {
  6342. auto res = cli_.Get("/streamed-chunked2");
  6343. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6344. EXPECT_EQ(StatusCode::OK_200, res->status);
  6345. EXPECT_EQ(std::string("123456789"), res->body);
  6346. }
  6347. TEST_F(ServerTest, GetStreamedChunkedWithTrailer) {
  6348. auto res = cli_.Get("/streamed-chunked-with-trailer");
  6349. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6350. EXPECT_EQ(StatusCode::OK_200, res->status);
  6351. EXPECT_EQ(std::string("123456789"), res->body);
  6352. EXPECT_TRUE(res->has_header("Trailer"));
  6353. EXPECT_EQ(1U, res->get_header_value_count("Trailer"));
  6354. EXPECT_EQ(std::string("Dummy1, Dummy2"), res->get_header_value("Trailer"));
  6355. // Trailers are now stored separately from headers (security fix)
  6356. EXPECT_EQ(2U, res->trailers.size());
  6357. EXPECT_TRUE(res->has_trailer("Dummy1"));
  6358. EXPECT_TRUE(res->has_trailer("Dummy2"));
  6359. EXPECT_FALSE(res->has_trailer("Dummy3"));
  6360. EXPECT_EQ(std::string("DummyVal1"), res->get_trailer_value("Dummy1"));
  6361. EXPECT_EQ(std::string("DummyVal2"), res->get_trailer_value("Dummy2"));
  6362. // Verify trailers are NOT in headers (security verification)
  6363. EXPECT_EQ(std::string(""), res->get_header_value("Dummy1"));
  6364. EXPECT_EQ(std::string(""), res->get_header_value("Dummy2"));
  6365. }
  6366. TEST_F(ServerTest, LargeChunkedPost) {
  6367. Request req;
  6368. req.method = "POST";
  6369. req.path = "/large-chunked";
  6370. std::string host_and_port;
  6371. host_and_port += HOST;
  6372. host_and_port += ":";
  6373. host_and_port += std::to_string(PORT);
  6374. req.headers.emplace("Host", host_and_port.c_str());
  6375. req.headers.emplace("Accept", "*/*");
  6376. req.headers.emplace("User-Agent", "cpp-httplib/0.1");
  6377. req.headers.emplace("Content-Type", "text/plain");
  6378. req.headers.emplace("Content-Length", "0");
  6379. req.headers.emplace("Transfer-Encoding", "chunked");
  6380. std::string long_string(30 * 1024u, 'a');
  6381. std::string chunk = "7800\r\n" + long_string + "\r\n";
  6382. // Attempt to make a large enough post to exceed OS buffers, to test that
  6383. // the server handles short reads if the full chunk data isn't available.
  6384. req.body = chunk + chunk + chunk + chunk + chunk + chunk + "0\r\n\r\n";
  6385. auto res = std::make_shared<Response>();
  6386. auto error = Error::Success;
  6387. auto ret = cli_.send(req, *res, error);
  6388. ASSERT_TRUE(ret);
  6389. EXPECT_EQ(StatusCode::OK_200, res->status);
  6390. }
  6391. TEST_F(ServerTest, GetMethodRemoteAddr) {
  6392. auto res = cli_.Get("/remote_addr");
  6393. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6394. EXPECT_EQ(StatusCode::OK_200, res->status);
  6395. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6396. EXPECT_TRUE(res->body == "::1" || res->body == "127.0.0.1");
  6397. }
  6398. TEST_F(ServerTest, GetMethodLocalAddr) {
  6399. auto res = cli_.Get("/local_addr");
  6400. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6401. EXPECT_EQ(StatusCode::OK_200, res->status);
  6402. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  6403. EXPECT_TRUE(res->body == std::string("::1:").append(to_string(PORT)) ||
  6404. res->body == std::string("127.0.0.1:").append(to_string(PORT)));
  6405. }
  6406. TEST_F(ServerTest, HTTPResponseSplitting) {
  6407. auto res = cli_.Get("/http_response_splitting");
  6408. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6409. EXPECT_EQ(StatusCode::OK_200, res->status);
  6410. }
  6411. TEST_F(ServerTest, SlowRequest) {
  6412. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6413. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6414. request_threads_.emplace_back([this]() { auto res = cli_.Get("/slow"); });
  6415. }
  6416. #if 0
  6417. TEST_F(ServerTest, SlowPost) {
  6418. char buffer[64 * 1024];
  6419. memset(buffer, 0x42, sizeof(buffer));
  6420. auto res = cli_.Post(
  6421. "/slowpost", 64 * 1024 * 1024,
  6422. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6423. auto ret = sink.write(buffer, sizeof(buffer));
  6424. EXPECT_TRUE(ret);
  6425. return true;
  6426. },
  6427. "text/plain");
  6428. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6429. EXPECT_EQ(StatusCode::OK_200, res->status);
  6430. }
  6431. TEST_F(ServerTest, SlowPostFail) {
  6432. char buffer[64 * 1024];
  6433. memset(buffer, 0x42, sizeof(buffer));
  6434. cli_.set_write_timeout(std::chrono::seconds(0));
  6435. auto res = cli_.Post(
  6436. "/slowpost", 64 * 1024 * 1024,
  6437. [&](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6438. sink.write(buffer, sizeof(buffer));
  6439. return true;
  6440. },
  6441. "text/plain");
  6442. ASSERT_TRUE(!res);
  6443. EXPECT_EQ(Error::Write, res.error());
  6444. }
  6445. #endif
  6446. TEST_F(ServerTest, Put) {
  6447. auto res = cli_.Put("/put", "PUT", "text/plain");
  6448. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6449. EXPECT_EQ(StatusCode::OK_200, res->status);
  6450. EXPECT_EQ("PUT", res->body);
  6451. }
  6452. TEST_F(ServerTest, PutWithContentProvider) {
  6453. auto res = cli_.Put(
  6454. "/put", 3,
  6455. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6456. sink.os << "PUT";
  6457. return true;
  6458. },
  6459. "text/plain");
  6460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6461. EXPECT_EQ(StatusCode::OK_200, res->status);
  6462. EXPECT_EQ("PUT", res->body);
  6463. }
  6464. TEST_F(ServerTest, PostWithContentProviderAbort) {
  6465. auto res = cli_.Post(
  6466. "/post", 42,
  6467. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6468. return false;
  6469. },
  6470. "text/plain");
  6471. ASSERT_TRUE(!res);
  6472. EXPECT_EQ(Error::Canceled, res.error());
  6473. }
  6474. TEST_F(ServerTest, PutWithContentProviderWithoutLength) {
  6475. auto res = cli_.Put(
  6476. "/put",
  6477. [](size_t /*offset*/, DataSink &sink) {
  6478. sink.os << "PUT";
  6479. sink.done();
  6480. return true;
  6481. },
  6482. "text/plain");
  6483. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6484. EXPECT_EQ(StatusCode::OK_200, res->status);
  6485. EXPECT_EQ("PUT", res->body);
  6486. }
  6487. TEST_F(ServerTest, PostWithContentProviderWithoutLengthAbort) {
  6488. auto res = cli_.Post(
  6489. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6490. "text/plain");
  6491. ASSERT_TRUE(!res);
  6492. EXPECT_EQ(Error::Canceled, res.error());
  6493. }
  6494. TEST_F(ServerTest, PostLoopBack) {
  6495. std::string body;
  6496. auto res = cli_.Post(
  6497. "/post-loopback", 9,
  6498. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6499. EXPECT_EQ(9u, length);
  6500. sink.write("123", 3);
  6501. sink.write("456", 3);
  6502. sink.write("789", 3);
  6503. return true;
  6504. },
  6505. "text/plain",
  6506. [&body](const char *data, size_t data_length) {
  6507. body.append(data, data_length);
  6508. return true;
  6509. });
  6510. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6511. EXPECT_EQ(StatusCode::OK_200, res->status);
  6512. EXPECT_EQ("123456789", body);
  6513. }
  6514. TEST_F(ServerTest, PutLoopBack) {
  6515. std::string body;
  6516. auto res = cli_.Put(
  6517. "/put-loopback", 9,
  6518. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6519. EXPECT_EQ(9u, length);
  6520. sink.write("123", 3);
  6521. sink.write("456", 3);
  6522. sink.write("789", 3);
  6523. return true;
  6524. },
  6525. "text/plain",
  6526. [&body](const char *data, size_t data_length) {
  6527. body.append(data, data_length);
  6528. return true;
  6529. });
  6530. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6531. EXPECT_EQ(StatusCode::OK_200, res->status);
  6532. EXPECT_EQ("123456789", body);
  6533. }
  6534. TEST_F(ServerTest, PatchLoopBack) {
  6535. std::string body;
  6536. auto res = cli_.Patch(
  6537. "/patch-loopback", 9,
  6538. [](size_t /*offset*/, size_t length, DataSink &sink) {
  6539. EXPECT_EQ(9u, length);
  6540. sink.write("123", 3);
  6541. sink.write("456", 3);
  6542. sink.write("789", 3);
  6543. return true;
  6544. },
  6545. "text/plain",
  6546. [&body](const char *data, size_t data_length) {
  6547. body.append(data, data_length);
  6548. return true;
  6549. });
  6550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6551. EXPECT_EQ(StatusCode::OK_200, res->status);
  6552. EXPECT_EQ("123456789", body);
  6553. }
  6554. TEST_F(ServerTest, PostLoopBackWithoutRequestContentLength) {
  6555. std::string body;
  6556. auto res = cli_.Post(
  6557. "/post-loopback",
  6558. [](size_t /*offset*/, DataSink &sink) {
  6559. sink.write("123", 3);
  6560. sink.write("456", 3);
  6561. sink.write("789", 3);
  6562. sink.done();
  6563. return true;
  6564. },
  6565. "text/plain",
  6566. [&body](const char *data, size_t data_length) {
  6567. body.append(data, data_length);
  6568. return true;
  6569. });
  6570. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6571. EXPECT_EQ(StatusCode::OK_200, res->status);
  6572. EXPECT_EQ("123456789", body);
  6573. }
  6574. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  6575. TEST_F(ServerTest, PutWithContentProviderWithGzip) {
  6576. cli_.set_compress(true);
  6577. auto res = cli_.Put(
  6578. "/put", 3,
  6579. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6580. sink.os << "PUT";
  6581. return true;
  6582. },
  6583. "text/plain");
  6584. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6585. EXPECT_EQ(StatusCode::OK_200, res->status);
  6586. EXPECT_EQ("PUT", res->body);
  6587. }
  6588. TEST_F(ServerTest, PostWithContentProviderWithGzipAbort) {
  6589. cli_.set_compress(true);
  6590. auto res = cli_.Post(
  6591. "/post", 42,
  6592. [](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  6593. return false;
  6594. },
  6595. "text/plain");
  6596. ASSERT_TRUE(!res);
  6597. EXPECT_EQ(Error::Canceled, res.error());
  6598. }
  6599. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithGzip) {
  6600. cli_.set_compress(true);
  6601. auto res = cli_.Put(
  6602. "/put",
  6603. [](size_t /*offset*/, DataSink &sink) {
  6604. sink.os << "PUT";
  6605. sink.done();
  6606. return true;
  6607. },
  6608. "text/plain");
  6609. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6610. EXPECT_EQ(StatusCode::OK_200, res->status);
  6611. EXPECT_EQ("PUT", res->body);
  6612. }
  6613. TEST_F(ServerTest, PostWithContentProviderWithoutLengthWithGzipAbort) {
  6614. cli_.set_compress(true);
  6615. auto res = cli_.Post(
  6616. "/post", [](size_t /*offset*/, DataSink & /*sink*/) { return false; },
  6617. "text/plain");
  6618. ASSERT_TRUE(!res);
  6619. EXPECT_EQ(Error::Canceled, res.error());
  6620. }
  6621. TEST_F(ServerTest, PutLargeFileWithGzip) {
  6622. cli_.set_compress(true);
  6623. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6624. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6625. EXPECT_EQ(StatusCode::OK_200, res->status);
  6626. EXPECT_EQ(LARGE_DATA, res->body);
  6627. }
  6628. TEST_F(ServerTest, PutLargeFileWithGzip2) {
  6629. #ifdef CPPHTTPLIB_SSL_ENABLED
  6630. std::string s = std::string("https://") + HOST + ":" + std::to_string(PORT);
  6631. Client cli(s.c_str());
  6632. cli.enable_server_certificate_verification(false);
  6633. #else
  6634. std::string s = std::string("http://") + HOST + ":" + std::to_string(PORT);
  6635. Client cli(s.c_str());
  6636. #endif
  6637. cli.set_compress(true);
  6638. auto res = cli.Put("/put-large", LARGE_DATA, "text/plain");
  6639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6640. EXPECT_EQ(StatusCode::OK_200, res->status);
  6641. EXPECT_EQ(LARGE_DATA, res->body);
  6642. // The compressed size should be less than a 10th of the original. May vary
  6643. // depending on the zlib library.
  6644. EXPECT_LT(res.get_request_header_value_u64("Content-Length"),
  6645. static_cast<uint64_t>(10 * 1024 * 1024));
  6646. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6647. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6648. #elif defined(CPPHTTPLIB_ZLIB_SUPPORT)
  6649. EXPECT_EQ("gzip", res.get_request_header_value("Content-Encoding"));
  6650. #elif defined(CPPHTTPLIB_ZSTD_SUPPORT)
  6651. EXPECT_EQ("zstd", res.get_request_header_value("Content-Encoding"));
  6652. #endif
  6653. }
  6654. TEST_F(ServerTest, PutContentWithDeflate) {
  6655. cli_.set_compress(false);
  6656. Headers headers;
  6657. headers.emplace("Content-Encoding", "deflate");
  6658. // PUT in deflate format:
  6659. auto res = cli_.Put("/put", headers,
  6660. "\170\234\013\010\015\001\0\001\361\0\372", "text/plain");
  6661. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6662. EXPECT_EQ(StatusCode::OK_200, res->status);
  6663. EXPECT_EQ("PUT", res->body);
  6664. }
  6665. TEST_F(ServerTest, GetStreamedChunkedWithGzip) {
  6666. Headers headers;
  6667. headers.emplace("Accept-Encoding", "gzip, deflate");
  6668. auto res = cli_.Get("/streamed-chunked", headers);
  6669. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6670. EXPECT_EQ(StatusCode::OK_200, res->status);
  6671. EXPECT_EQ(std::string("123456789"), res->body);
  6672. }
  6673. TEST_F(ServerTest, GetStreamedChunkedWithGzip2) {
  6674. Headers headers;
  6675. headers.emplace("Accept-Encoding", "gzip, deflate");
  6676. auto res = cli_.Get("/streamed-chunked2", headers);
  6677. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6678. EXPECT_EQ(StatusCode::OK_200, res->status);
  6679. EXPECT_EQ(std::string("123456789"), res->body);
  6680. }
  6681. TEST_F(ServerTest, SplitDelimiterInPathRegex) {
  6682. auto res = cli_.Get("/regex-with-delimiter?key=^(?.*(value))");
  6683. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6684. EXPECT_EQ(StatusCode::OK_200, res->status);
  6685. }
  6686. TEST(GzipDecompressor, ChunkedDecompression) {
  6687. std::string data;
  6688. for (size_t i = 0; i < 32 * 1024; ++i) {
  6689. data.push_back(static_cast<char>('a' + i % 26));
  6690. }
  6691. std::string compressed_data;
  6692. {
  6693. httplib::detail::gzip_compressor compressor;
  6694. bool result = compressor.compress(
  6695. data.data(), data.size(),
  6696. /*last=*/true,
  6697. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  6698. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  6699. compressed_data_size);
  6700. return true;
  6701. });
  6702. ASSERT_TRUE(result);
  6703. }
  6704. std::string decompressed_data;
  6705. {
  6706. httplib::detail::gzip_decompressor decompressor;
  6707. // Chunk size is chosen specifically to have a decompressed chunk size equal
  6708. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  6709. size_t chunk_size = 130;
  6710. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  6711. chunk_begin += chunk_size) {
  6712. size_t current_chunk_size =
  6713. std::min(compressed_data.size() - chunk_begin, chunk_size);
  6714. bool result = decompressor.decompress(
  6715. compressed_data.data() + chunk_begin, current_chunk_size,
  6716. [&](const char *decompressed_data_chunk,
  6717. size_t decompressed_data_chunk_size) {
  6718. decompressed_data.insert(decompressed_data.size(),
  6719. decompressed_data_chunk,
  6720. decompressed_data_chunk_size);
  6721. return true;
  6722. });
  6723. ASSERT_TRUE(result);
  6724. }
  6725. }
  6726. ASSERT_EQ(data, decompressed_data);
  6727. }
  6728. TEST(GzipDecompressor, DeflateDecompression) {
  6729. std::string original_text = "Raw deflate without gzip";
  6730. unsigned char data[32] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6731. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6732. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6733. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E};
  6734. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6735. std::string decompressed_data;
  6736. {
  6737. httplib::detail::gzip_decompressor decompressor;
  6738. bool result = decompressor.decompress(
  6739. compressed_data.data(), compressed_data.size(),
  6740. [&](const char *decompressed_data_chunk,
  6741. size_t decompressed_data_chunk_size) {
  6742. decompressed_data.insert(decompressed_data.size(),
  6743. decompressed_data_chunk,
  6744. decompressed_data_chunk_size);
  6745. return true;
  6746. });
  6747. ASSERT_TRUE(result);
  6748. }
  6749. ASSERT_EQ(original_text, decompressed_data);
  6750. }
  6751. TEST(GzipDecompressor, DeflateDecompressionTrailingBytes) {
  6752. std::string original_text = "Raw deflate without gzip";
  6753. unsigned char data[40] = {0x78, 0x9C, 0x0B, 0x4A, 0x2C, 0x57, 0x48, 0x49,
  6754. 0x4D, 0xCB, 0x49, 0x2C, 0x49, 0x55, 0x28, 0xCF,
  6755. 0x2C, 0xC9, 0xC8, 0x2F, 0x2D, 0x51, 0x48, 0xAF,
  6756. 0xCA, 0x2C, 0x00, 0x00, 0x6F, 0x98, 0x09, 0x2E,
  6757. 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00};
  6758. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  6759. std::string decompressed_data;
  6760. {
  6761. httplib::detail::gzip_decompressor decompressor;
  6762. bool result = decompressor.decompress(
  6763. compressed_data.data(), compressed_data.size(),
  6764. [&](const char *decompressed_data_chunk,
  6765. size_t decompressed_data_chunk_size) {
  6766. decompressed_data.insert(decompressed_data.size(),
  6767. decompressed_data_chunk,
  6768. decompressed_data_chunk_size);
  6769. return true;
  6770. });
  6771. ASSERT_TRUE(result);
  6772. }
  6773. ASSERT_EQ(original_text, decompressed_data);
  6774. }
  6775. #endif
  6776. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  6777. TEST_F(ServerTest, GetStreamedChunkedWithBrotli) {
  6778. Headers headers;
  6779. headers.emplace("Accept-Encoding", "br");
  6780. auto res = cli_.Get("/streamed-chunked", headers);
  6781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6782. EXPECT_EQ(StatusCode::OK_200, res->status);
  6783. EXPECT_EQ(std::string("123456789"), res->body);
  6784. }
  6785. TEST_F(ServerTest, GetStreamedChunkedWithBrotli2) {
  6786. Headers headers;
  6787. headers.emplace("Accept-Encoding", "br");
  6788. auto res = cli_.Get("/streamed-chunked2", headers);
  6789. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6790. EXPECT_EQ(StatusCode::OK_200, res->status);
  6791. EXPECT_EQ(std::string("123456789"), res->body);
  6792. }
  6793. TEST_F(ServerTest, PutWithContentProviderWithBrotli) {
  6794. cli_.set_compress(true);
  6795. auto res = cli_.Put(
  6796. "/put", 3,
  6797. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  6798. sink.os << "PUT";
  6799. return true;
  6800. },
  6801. "text/plain");
  6802. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6803. EXPECT_EQ(StatusCode::OK_200, res->status);
  6804. EXPECT_EQ("PUT", res->body);
  6805. }
  6806. TEST_F(ServerTest, PutWithContentProviderWithoutLengthWithBrotli) {
  6807. cli_.set_compress(true);
  6808. auto res = cli_.Put(
  6809. "/put",
  6810. [](size_t /*offset*/, DataSink &sink) {
  6811. sink.os << "PUT";
  6812. sink.done();
  6813. return true;
  6814. },
  6815. "text/plain");
  6816. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6817. EXPECT_EQ(StatusCode::OK_200, res->status);
  6818. EXPECT_EQ("PUT", res->body);
  6819. }
  6820. TEST_F(ServerTest, PutLargeFileWithBrotli) {
  6821. cli_.set_compress(true);
  6822. auto res = cli_.Put("/put-large", LARGE_DATA, "text/plain");
  6823. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6824. EXPECT_EQ(StatusCode::OK_200, res->status);
  6825. EXPECT_EQ(LARGE_DATA, res->body);
  6826. EXPECT_EQ("br", res.get_request_header_value("Content-Encoding"));
  6827. }
  6828. #endif
  6829. TEST_F(ServerTest, Patch) {
  6830. auto res = cli_.Patch("/patch", "PATCH", "text/plain");
  6831. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6832. EXPECT_EQ(StatusCode::OK_200, res->status);
  6833. EXPECT_EQ("PATCH", res->body);
  6834. }
  6835. TEST_F(ServerTest, Delete) {
  6836. auto res = cli_.Delete("/delete");
  6837. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6838. EXPECT_EQ(StatusCode::OK_200, res->status);
  6839. EXPECT_EQ("DELETE", res->body);
  6840. }
  6841. TEST_F(ServerTest, DeleteContentReceiver) {
  6842. auto res = cli_.Delete("/delete-body", "content", "text/plain");
  6843. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6844. EXPECT_EQ(StatusCode::OK_200, res->status);
  6845. EXPECT_EQ("content", res->body);
  6846. }
  6847. TEST_F(ServerTest, Options) {
  6848. auto res = cli_.Options("*");
  6849. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6850. EXPECT_EQ(StatusCode::OK_200, res->status);
  6851. EXPECT_EQ("GET, POST, HEAD, OPTIONS", res->get_header_value("Allow"));
  6852. EXPECT_TRUE(res->body.empty());
  6853. }
  6854. TEST_F(ServerTest, URL) {
  6855. auto res = cli_.Get("/request-target?aaa=bbb&ccc=ddd");
  6856. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6857. EXPECT_EQ(StatusCode::OK_200, res->status);
  6858. }
  6859. TEST_F(ServerTest, ArrayParam) {
  6860. auto res = cli_.Get("/array-param?array=value1&array=value2&array=value3");
  6861. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6862. EXPECT_EQ(StatusCode::OK_200, res->status);
  6863. }
  6864. TEST_F(ServerTest, ArrayParamValues) {
  6865. auto res =
  6866. cli_.Get("/array-param-values?array=value1&array=value2&array=value3");
  6867. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6868. EXPECT_EQ(StatusCode::OK_200, res->status);
  6869. }
  6870. TEST_F(ServerTest, NoMultipleHeaders) {
  6871. Headers headers = {{"Content-Length", "5"}};
  6872. auto res = cli_.Post("/validate-no-multiple-headers", headers, "hello",
  6873. "text/plain");
  6874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6875. EXPECT_EQ(StatusCode::OK_200, res->status);
  6876. }
  6877. TEST_F(ServerTest, PostContentReceiver) {
  6878. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  6879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6880. ASSERT_EQ(StatusCode::OK_200, res->status);
  6881. ASSERT_EQ("content", res->body);
  6882. }
  6883. TEST_F(ServerTest, PostMultipartFileContentReceiver) {
  6884. UploadFormDataItems items = {
  6885. {"text1", "text default", "", ""},
  6886. {"text2", "aωb", "", ""},
  6887. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6888. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6889. {"file3", "", "", "application/octet-stream"},
  6890. };
  6891. auto res = cli_.Post("/content_receiver", items);
  6892. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6893. EXPECT_EQ(StatusCode::OK_200, res->status);
  6894. }
  6895. TEST_F(ServerTest, PostMultipartPlusBoundary) {
  6896. UploadFormDataItems items = {
  6897. {"text1", "text default", "", ""},
  6898. {"text2", "aωb", "", ""},
  6899. {"file1", "h\ne\n\nl\nl\no\n", "hello.txt", "text/plain"},
  6900. {"file2", R"({\n "world": true\n}\n)", "world.json", "application/json"},
  6901. {"file3", "", "", "application/octet-stream"},
  6902. };
  6903. auto boundary = std::string("+++++");
  6904. std::string body;
  6905. for (const auto &item : items) {
  6906. body += "--" + boundary + "\r\n";
  6907. body += "Content-Disposition: form-data; name=\"" + item.name + "\"";
  6908. if (!item.filename.empty()) {
  6909. body += "; filename=\"" + item.filename + "\"";
  6910. }
  6911. body += "\r\n";
  6912. if (!item.content_type.empty()) {
  6913. body += "Content-Type: " + item.content_type + "\r\n";
  6914. }
  6915. body += "\r\n";
  6916. body += item.content + "\r\n";
  6917. }
  6918. body += "--" + boundary + "--\r\n";
  6919. std::string content_type = "multipart/form-data; boundary=" + boundary;
  6920. auto res = cli_.Post("/content_receiver", body, content_type.c_str());
  6921. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6922. EXPECT_EQ(StatusCode::OK_200, res->status);
  6923. }
  6924. TEST(MultipartFormDataTest, FieldEscaping) {
  6925. Server svr;
  6926. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6927. const ContentReader &content_reader) {
  6928. ASSERT_TRUE(req.is_multipart_form_data());
  6929. std::vector<FormData> received;
  6930. content_reader(
  6931. [&](const FormData &file) {
  6932. received.push_back(file);
  6933. return true;
  6934. },
  6935. [&](const char *data, size_t data_length) {
  6936. received.back().content.append(data, data_length);
  6937. return true;
  6938. });
  6939. // '"', CR and LF in names and filenames are escaped following the
  6940. // WHATWG HTML standard, so each part still parses as a single part
  6941. // with no injected headers. Content types get CR/LF escaped too,
  6942. // while '"' (legal there, e.g. quoted charset) is preserved.
  6943. ASSERT_EQ(4U, received.size());
  6944. EXPECT_EQ("na%22me", received[0].name);
  6945. EXPECT_EQ("quoted name", received[0].content);
  6946. EXPECT_EQ("file", received[1].name);
  6947. EXPECT_EQ("evil%0D%0AContent-Type: text/evil%0D%0A%0D%0A.pdf",
  6948. received[1].filename);
  6949. EXPECT_EQ("application/octet-stream", received[1].content_type);
  6950. EXPECT_EQ("injected", received[1].content);
  6951. EXPECT_EQ("my%0Dna%0Ame", received[2].name);
  6952. EXPECT_EQ("my%22file.txt", received[2].filename);
  6953. EXPECT_EQ("cr lf name", received[2].content);
  6954. EXPECT_EQ("typed", received[3].name);
  6955. EXPECT_EQ("text/plain; charset=\"utf-8\"%0D%0AX-Evil: 1",
  6956. received[3].content_type);
  6957. EXPECT_EQ("typed content", received[3].content);
  6958. });
  6959. auto port = svr.bind_to_any_port("localhost");
  6960. auto t = std::thread([&]() { svr.listen_after_bind(); });
  6961. auto se = detail::scope_exit([&] {
  6962. svr.stop();
  6963. t.join();
  6964. ASSERT_FALSE(svr.is_running());
  6965. });
  6966. svr.wait_until_ready();
  6967. Client cli("localhost", port);
  6968. UploadFormDataItems items = {
  6969. {"na\"me", "quoted name", "", ""},
  6970. {"file", "injected", "evil\r\nContent-Type: text/evil\r\n\r\n.pdf",
  6971. "application/octet-stream"},
  6972. {"my\rna\nme", "cr lf name", "my\"file.txt", "text/plain"},
  6973. {"typed", "typed content", "",
  6974. "text/plain; charset=\"utf-8\"\r\nX-Evil: 1"},
  6975. };
  6976. auto res = cli.Post("/post", items);
  6977. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  6978. EXPECT_EQ(StatusCode::OK_200, res->status);
  6979. }
  6980. TEST(MultipartFormDataTest, PublicWriterAPI) {
  6981. const UploadFormDataItems items = {
  6982. {"name1", "Content 1", "", ""},
  6983. {"name2", "Content 2", "file2.txt", "text/plain"},
  6984. };
  6985. Server svr;
  6986. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  6987. const ContentReader &content_reader) {
  6988. ASSERT_TRUE(req.is_multipart_form_data());
  6989. std::vector<FormData> received;
  6990. content_reader(
  6991. [&](const FormData &file) {
  6992. received.push_back(file);
  6993. return true;
  6994. },
  6995. [&](const char *data, size_t data_length) {
  6996. received.back().content.append(data, data_length);
  6997. return true;
  6998. });
  6999. ASSERT_EQ(2U, received.size());
  7000. EXPECT_EQ("name1", received[0].name);
  7001. EXPECT_EQ("Content 1", received[0].content);
  7002. EXPECT_EQ("name2", received[1].name);
  7003. EXPECT_EQ("Content 2", received[1].content);
  7004. EXPECT_EQ("file2.txt", received[1].filename);
  7005. EXPECT_EQ("text/plain", received[1].content_type);
  7006. });
  7007. auto port = svr.bind_to_any_port("localhost");
  7008. auto t = std::thread([&]() { svr.listen_after_bind(); });
  7009. auto se = detail::scope_exit([&] {
  7010. svr.stop();
  7011. t.join();
  7012. ASSERT_FALSE(svr.is_running());
  7013. });
  7014. svr.wait_until_ready();
  7015. Client cli("localhost", port);
  7016. // Whole-body serialization with a generated boundary
  7017. {
  7018. MultipartFormDataWriter writer;
  7019. EXPECT_TRUE(is_valid_multipart_boundary(writer.boundary()));
  7020. EXPECT_EQ("multipart/form-data; boundary=" + writer.boundary(),
  7021. writer.content_type());
  7022. auto body = writer.serialize(items);
  7023. EXPECT_EQ(body.size(), writer.content_length(items));
  7024. auto res = cli.Post("/post", body, writer.content_type());
  7025. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7026. EXPECT_EQ(StatusCode::OK_200, res->status);
  7027. }
  7028. // Per-part framing with a custom boundary via a content provider
  7029. {
  7030. EXPECT_FALSE(is_valid_multipart_boundary("bad boundary"));
  7031. ASSERT_TRUE(is_valid_multipart_boundary("custom-boundary_123"));
  7032. MultipartFormDataWriter writer("custom-boundary_123");
  7033. EXPECT_EQ("custom-boundary_123", writer.boundary());
  7034. std::string body;
  7035. for (const auto &item : items) {
  7036. body += writer.item_begin(item);
  7037. body += item.content;
  7038. body += MultipartFormDataWriter::item_end();
  7039. }
  7040. body += writer.finish();
  7041. EXPECT_EQ(body.size(), writer.content_length(items));
  7042. auto res = cli.Post(
  7043. "/post", body.size(),
  7044. [&](size_t offset, size_t length, DataSink &sink) {
  7045. sink.write(body.data() + offset, length);
  7046. return true;
  7047. },
  7048. writer.content_type());
  7049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7050. EXPECT_EQ(StatusCode::OK_200, res->status);
  7051. }
  7052. }
  7053. TEST_F(ServerTest, PostContentReceiverGzip) {
  7054. cli_.set_compress(true);
  7055. auto res = cli_.Post("/content_receiver", "content", "text/plain");
  7056. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7057. ASSERT_EQ(StatusCode::OK_200, res->status);
  7058. ASSERT_EQ("content", res->body);
  7059. }
  7060. TEST_F(ServerTest, PutContentReceiver) {
  7061. auto res = cli_.Put("/content_receiver", "content", "text/plain");
  7062. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7063. ASSERT_EQ(StatusCode::OK_200, res->status);
  7064. ASSERT_EQ("content", res->body);
  7065. }
  7066. TEST_F(ServerTest, PatchContentReceiver) {
  7067. auto res = cli_.Patch("/content_receiver", "content", "text/plain");
  7068. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7069. ASSERT_EQ(StatusCode::OK_200, res->status);
  7070. ASSERT_EQ("content", res->body);
  7071. }
  7072. template <typename ClientType>
  7073. void TestWithHeadersAndContentReceiver(
  7074. ClientType &cli,
  7075. std::function<Result(ClientType &, const std::string &, const Headers &,
  7076. const std::string &, const std::string &,
  7077. ContentReceiver, DownloadProgress)>
  7078. request_func) {
  7079. Headers headers;
  7080. headers.emplace("X-Custom-Header", "test-value");
  7081. std::string received_body;
  7082. auto res = request_func(
  7083. cli, "/content_receiver", headers, "content", "application/json",
  7084. [&](const char *data, size_t data_length) {
  7085. received_body.append(data, data_length);
  7086. return true;
  7087. },
  7088. nullptr);
  7089. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7090. EXPECT_EQ(StatusCode::OK_200, res->status);
  7091. EXPECT_EQ("content", received_body);
  7092. }
  7093. TEST_F(ServerTest, PostWithHeadersAndContentReceiver) {
  7094. #ifdef CPPHTTPLIB_SSL_ENABLED
  7095. using ClientT = SSLClient;
  7096. #else
  7097. using ClientT = Client;
  7098. #endif
  7099. TestWithHeadersAndContentReceiver<ClientT>(
  7100. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7101. const std::string &body, const std::string &content_type,
  7102. ContentReceiver receiver, DownloadProgress progress) {
  7103. return cli.Post(path, headers, body, content_type, receiver, progress);
  7104. });
  7105. }
  7106. TEST_F(ServerTest, PutWithHeadersAndContentReceiver) {
  7107. #ifdef CPPHTTPLIB_SSL_ENABLED
  7108. using ClientT = SSLClient;
  7109. #else
  7110. using ClientT = Client;
  7111. #endif
  7112. TestWithHeadersAndContentReceiver<ClientT>(
  7113. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7114. const std::string &body, const std::string &content_type,
  7115. ContentReceiver receiver, DownloadProgress progress) {
  7116. return cli.Put(path, headers, body, content_type, receiver, progress);
  7117. });
  7118. }
  7119. TEST_F(ServerTest, PatchWithHeadersAndContentReceiver) {
  7120. #ifdef CPPHTTPLIB_SSL_ENABLED
  7121. using ClientT = SSLClient;
  7122. #else
  7123. using ClientT = Client;
  7124. #endif
  7125. TestWithHeadersAndContentReceiver<ClientT>(
  7126. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7127. const std::string &body, const std::string &content_type,
  7128. ContentReceiver receiver, DownloadProgress progress) {
  7129. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7130. });
  7131. }
  7132. template <typename ClientType>
  7133. void TestWithHeadersAndContentReceiverWithProgress(
  7134. ClientType &cli,
  7135. std::function<Result(ClientType &, const std::string &, const Headers &,
  7136. const std::string &, const std::string &,
  7137. ContentReceiver, DownloadProgress)>
  7138. request_func) {
  7139. Headers headers;
  7140. headers.emplace("X-Test-Header", "progress-test");
  7141. std::string received_body;
  7142. auto progress_called = false;
  7143. auto res = request_func(
  7144. cli, "/content_receiver", headers, "content", "text/plain",
  7145. [&](const char *data, size_t data_length) {
  7146. received_body.append(data, data_length);
  7147. return true;
  7148. },
  7149. [&](uint64_t /*current*/, uint64_t /*total*/) {
  7150. progress_called = true;
  7151. return true;
  7152. });
  7153. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7154. EXPECT_EQ(StatusCode::OK_200, res->status);
  7155. EXPECT_EQ("content", received_body);
  7156. EXPECT_TRUE(progress_called);
  7157. }
  7158. TEST_F(ServerTest, PostWithHeadersAndContentReceiverWithProgress) {
  7159. #ifdef CPPHTTPLIB_SSL_ENABLED
  7160. using ClientT = SSLClient;
  7161. #else
  7162. using ClientT = Client;
  7163. #endif
  7164. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7165. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7166. const std::string &body, const std::string &content_type,
  7167. ContentReceiver receiver, DownloadProgress progress) {
  7168. return cli.Post(path, headers, body, content_type, receiver, progress);
  7169. });
  7170. }
  7171. TEST_F(ServerTest, PutWithHeadersAndContentReceiverWithProgress) {
  7172. #ifdef CPPHTTPLIB_SSL_ENABLED
  7173. using ClientT = SSLClient;
  7174. #else
  7175. using ClientT = Client;
  7176. #endif
  7177. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7178. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7179. const std::string &body, const std::string &content_type,
  7180. ContentReceiver receiver, DownloadProgress progress) {
  7181. return cli.Put(path, headers, body, content_type, receiver, progress);
  7182. });
  7183. }
  7184. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverWithProgress) {
  7185. #ifdef CPPHTTPLIB_SSL_ENABLED
  7186. using ClientT = SSLClient;
  7187. #else
  7188. using ClientT = Client;
  7189. #endif
  7190. TestWithHeadersAndContentReceiverWithProgress<ClientT>(
  7191. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7192. const std::string &body, const std::string &content_type,
  7193. ContentReceiver receiver, DownloadProgress progress) {
  7194. return cli.Patch(path, headers, body, content_type, receiver, progress);
  7195. });
  7196. }
  7197. template <typename ClientType>
  7198. void TestWithHeadersAndContentReceiverError(
  7199. ClientType &cli, std::function<Result(ClientType &, const std::string &,
  7200. const Headers &, const std::string &,
  7201. const std::string &, ContentReceiver)>
  7202. request_func) {
  7203. Headers headers;
  7204. headers.emplace("X-Error-Test", "true");
  7205. std::string received_body;
  7206. auto receiver_failed = false;
  7207. auto res =
  7208. request_func(cli, "/content_receiver", headers, "content", "text/plain",
  7209. [&](const char *data, size_t data_length) {
  7210. received_body.append(data, data_length);
  7211. receiver_failed = true;
  7212. return false;
  7213. });
  7214. ASSERT_FALSE(res);
  7215. EXPECT_TRUE(receiver_failed);
  7216. }
  7217. TEST_F(ServerTest, PostWithHeadersAndContentReceiverError) {
  7218. #ifdef CPPHTTPLIB_SSL_ENABLED
  7219. using ClientT = SSLClient;
  7220. #else
  7221. using ClientT = Client;
  7222. #endif
  7223. TestWithHeadersAndContentReceiverError<ClientT>(
  7224. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7225. const std::string &body, const std::string &content_type,
  7226. ContentReceiver receiver) {
  7227. return cli.Post(path, headers, body, content_type, receiver);
  7228. });
  7229. }
  7230. TEST_F(ServerTest, PuttWithHeadersAndContentReceiverError) {
  7231. #ifdef CPPHTTPLIB_SSL_ENABLED
  7232. using ClientT = SSLClient;
  7233. #else
  7234. using ClientT = Client;
  7235. #endif
  7236. TestWithHeadersAndContentReceiverError<ClientT>(
  7237. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7238. const std::string &body, const std::string &content_type,
  7239. ContentReceiver receiver) {
  7240. return cli.Put(path, headers, body, content_type, receiver);
  7241. });
  7242. }
  7243. TEST_F(ServerTest, PatchWithHeadersAndContentReceiverError) {
  7244. #ifdef CPPHTTPLIB_SSL_ENABLED
  7245. using ClientT = SSLClient;
  7246. #else
  7247. using ClientT = Client;
  7248. #endif
  7249. TestWithHeadersAndContentReceiverError<ClientT>(
  7250. cli_, [](ClientT &cli, const std::string &path, const Headers &headers,
  7251. const std::string &body, const std::string &content_type,
  7252. ContentReceiver receiver) {
  7253. return cli.Patch(path, headers, body, content_type, receiver);
  7254. });
  7255. }
  7256. TEST_F(ServerTest, PostQueryStringAndBody) {
  7257. auto res =
  7258. cli_.Post("/query-string-and-body?key=value", "content", "text/plain");
  7259. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7260. ASSERT_EQ(StatusCode::OK_200, res->status);
  7261. }
  7262. TEST_F(ServerTest, HTTP2Magic) {
  7263. Request req;
  7264. req.method = "PRI";
  7265. req.path = "*";
  7266. req.body = "SM";
  7267. auto res = std::make_shared<Response>();
  7268. auto error = Error::Success;
  7269. auto ret = cli_.send(req, *res, error);
  7270. ASSERT_TRUE(ret);
  7271. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7272. }
  7273. TEST_F(ServerTest, KeepAlive) {
  7274. auto res = cli_.Get("/hi");
  7275. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7276. EXPECT_EQ(StatusCode::OK_200, res->status);
  7277. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7278. EXPECT_EQ("Hello World!", res->body);
  7279. res = cli_.Get("/hi");
  7280. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7281. EXPECT_EQ(StatusCode::OK_200, res->status);
  7282. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7283. EXPECT_EQ("Hello World!", res->body);
  7284. res = cli_.Get("/hi");
  7285. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7286. EXPECT_EQ(StatusCode::OK_200, res->status);
  7287. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7288. EXPECT_EQ("Hello World!", res->body);
  7289. res = cli_.Get("/not-exist");
  7290. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7291. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7292. res = cli_.Post("/empty", "", "text/plain");
  7293. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7294. EXPECT_EQ(StatusCode::OK_200, res->status);
  7295. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7296. EXPECT_EQ("empty", res->body);
  7297. EXPECT_EQ("close", res->get_header_value("Connection"));
  7298. res = cli_.Post(
  7299. "/empty", 0, [&](size_t, size_t, DataSink &) { return true; },
  7300. "text/plain");
  7301. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7302. EXPECT_EQ(StatusCode::OK_200, res->status);
  7303. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7304. EXPECT_EQ("empty", res->body);
  7305. cli_.set_keep_alive(false);
  7306. res = cli_.Get("/last-request");
  7307. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7308. EXPECT_EQ(StatusCode::OK_200, res->status);
  7309. EXPECT_EQ("close", res->get_header_value("Connection"));
  7310. }
  7311. TEST_F(ServerTest, TooManyRedirect) {
  7312. cli_.set_follow_location(true);
  7313. auto res = cli_.Get("/redirect/0");
  7314. ASSERT_TRUE(!res);
  7315. EXPECT_EQ(Error::ExceedRedirectCount, res.error());
  7316. }
  7317. TEST_F(ServerTest, BadRequestLineCancelsKeepAlive) {
  7318. Request req;
  7319. req.method = "FOOBAR";
  7320. req.path = "/hi";
  7321. cli_.set_keep_alive(true);
  7322. auto res = cli_.send(req);
  7323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7324. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7325. EXPECT_EQ("close", res->get_header_value("Connection"));
  7326. EXPECT_FALSE(cli_.is_socket_open());
  7327. }
  7328. TEST_F(ServerTest, CustomRouteReadsBody) {
  7329. const std::string xml =
  7330. R"(<?xml version="1.0"?><propfind><allprop/></propfind>)";
  7331. Request req;
  7332. req.method = "PROPFIND";
  7333. req.path = "/dav/dir";
  7334. req.set_header("Depth", "1");
  7335. req.body = xml;
  7336. auto res = cli_.send(req);
  7337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7338. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7339. EXPECT_EQ(xml, res->body);
  7340. EXPECT_EQ(std::to_string(xml.size()), res->get_header_value("x-body-size"));
  7341. EXPECT_EQ("application/xml", res->get_header_value("Content-Type"));
  7342. }
  7343. TEST_F(ServerTest, CustomRouteMatchedRouteAndPathParams) {
  7344. Request req;
  7345. req.method = "PROPFIND";
  7346. req.path = "/dav/42";
  7347. auto res = cli_.send(req);
  7348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7349. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7350. EXPECT_EQ("/dav/:id", res->get_header_value("x-matched-route"));
  7351. EXPECT_EQ("42", res->get_header_value("x-dav-id"));
  7352. }
  7353. TEST_F(ServerTest, CustomRouteRegexPattern) {
  7354. Request req;
  7355. req.method = "PROPFIND";
  7356. req.path = "/dav-re/123";
  7357. auto res = cli_.send(req);
  7358. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7359. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7360. EXPECT_EQ("123", res->get_header_value("x-dav-match"));
  7361. }
  7362. TEST_F(ServerTest, CustomRouteWithoutBody) {
  7363. Request req;
  7364. req.method = "MKCOL";
  7365. req.path = "/dav-mkcol";
  7366. auto res = cli_.send(req);
  7367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7368. EXPECT_EQ(StatusCode::Created_201, res->status);
  7369. }
  7370. TEST_F(ServerTest, CustomRouteWithContentReader) {
  7371. const std::string xml = R"(<?xml version="1.0"?><sync-collection/>)";
  7372. Request req;
  7373. req.method = "REPORT";
  7374. req.path = "/dav-report";
  7375. req.body = xml;
  7376. auto res = cli_.send(req);
  7377. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7378. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7379. EXPECT_EQ(xml, res->body);
  7380. }
  7381. // A content reader route must fire even when the request carries no body,
  7382. // the way the built-in Delete(pattern, HandlerWithContentReader) does.
  7383. // Without that, a body-less PROPFIND-style request would fall through to 404.
  7384. TEST_F(ServerTest, CustomRouteWithContentReaderWithoutBody) {
  7385. Request req;
  7386. req.method = "REPORT";
  7387. req.path = "/dav-report";
  7388. auto res = cli_.send(req);
  7389. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7390. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7391. EXPECT_EQ("0", res->get_header_value("x-body-size"));
  7392. }
  7393. TEST_F(ServerTest, CustomRouteUnmatchedPathReturns404) {
  7394. Request req;
  7395. req.method = "PROPFIND";
  7396. req.path = "/not-dav";
  7397. auto res = cli_.send(req);
  7398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7399. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7400. }
  7401. TEST_F(ServerTest, CustomRouteUnregisteredMethodIsRejected) {
  7402. Request req;
  7403. req.method = "UNLOCK";
  7404. req.path = "/dav/dir";
  7405. cli_.set_keep_alive(true);
  7406. auto res = cli_.send(req);
  7407. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7408. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  7409. EXPECT_EQ("close", res->get_header_value("Connection"));
  7410. EXPECT_FALSE(cli_.is_socket_open());
  7411. }
  7412. TEST_F(ServerTest, CustomRouteDoesNotServeStaticFiles) {
  7413. // The mount point serves this path, but only for GET and HEAD.
  7414. auto get_res = cli_.Get("/dir/index.html");
  7415. ASSERT_TRUE(get_res) << "Error: " << to_string(get_res.error());
  7416. ASSERT_EQ(StatusCode::OK_200, get_res->status);
  7417. Request req;
  7418. req.method = "PROPFIND";
  7419. req.path = "/dir/index.html";
  7420. auto res = cli_.send(req);
  7421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7422. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  7423. }
  7424. TEST_F(ServerTest, CustomRouteKeepAlive) {
  7425. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7426. cli_.set_keep_alive(true);
  7427. for (auto i = 0; i < 2; i++) {
  7428. Request req;
  7429. req.method = "PROPFIND";
  7430. req.path = "/dav/dir";
  7431. req.body = xml;
  7432. auto res = cli_.send(req);
  7433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7434. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7435. EXPECT_EQ(xml, res->body);
  7436. EXPECT_TRUE(cli_.is_socket_open());
  7437. }
  7438. // A built-in method must still be served on the same connection.
  7439. cli_.set_keep_alive(false);
  7440. auto res = cli_.Get("/hi");
  7441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7442. EXPECT_EQ(StatusCode::OK_200, res->status);
  7443. EXPECT_EQ("close", res->get_header_value("Connection"));
  7444. }
  7445. TEST_F(ServerTest, CustomRouteExpect100Continue) {
  7446. const std::string xml = R"(<?xml version="1.0"?><propfind/>)";
  7447. Request req;
  7448. req.method = "PROPFIND";
  7449. req.path = "/dav/dir";
  7450. req.set_header("Expect", "100-continue");
  7451. req.body = xml;
  7452. auto res = cli_.send(req);
  7453. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7454. EXPECT_EQ(StatusCode::MultiStatus_207, res->status);
  7455. EXPECT_EQ(xml, res->body);
  7456. }
  7457. TEST_F(ServerTest, StartTime) { auto res = cli_.Get("/test-start-time"); }
  7458. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7459. TEST_F(ServerTest, Gzip) {
  7460. Headers headers;
  7461. headers.emplace("Accept-Encoding", "gzip, deflate");
  7462. auto res = cli_.Get("/compress", headers);
  7463. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7464. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7465. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7466. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7467. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7468. "7890123456789012345678901234567890",
  7469. res->body);
  7470. EXPECT_EQ(StatusCode::OK_200, res->status);
  7471. }
  7472. TEST_F(ServerTest, GzipWithContentTypeParameters) {
  7473. Headers headers;
  7474. headers.emplace("Accept-Encoding", "gzip, deflate");
  7475. auto res = cli_.Get("/compress-with-charset", headers);
  7476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7477. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7478. EXPECT_EQ("application/json; charset=utf-8",
  7479. res->get_header_value("Content-Type"));
  7480. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7481. "7890123456789012345678901234567890",
  7482. res->body);
  7483. EXPECT_EQ(StatusCode::OK_200, res->status);
  7484. }
  7485. TEST_F(ServerTest, GzipWithoutAcceptEncoding) {
  7486. Headers headers;
  7487. headers.emplace("Accept-Encoding", "");
  7488. auto res = cli_.Get("/compress", headers);
  7489. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7490. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7491. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7492. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7493. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7494. "7890123456789012345678901234567890",
  7495. res->body);
  7496. EXPECT_EQ(StatusCode::OK_200, res->status);
  7497. }
  7498. TEST_F(ServerTest, GzipWithContentReceiver) {
  7499. Headers headers;
  7500. headers.emplace("Accept-Encoding", "gzip, deflate");
  7501. std::string body;
  7502. auto res = cli_.Get("/compress", headers,
  7503. [&](const char *data, uint64_t data_length) {
  7504. EXPECT_EQ(100U, data_length);
  7505. body.append(data, data_length);
  7506. return true;
  7507. });
  7508. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7509. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7510. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7511. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7512. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7513. "7890123456789012345678901234567890",
  7514. body);
  7515. EXPECT_EQ(StatusCode::OK_200, res->status);
  7516. }
  7517. TEST_F(ServerTest, GzipWithoutDecompressing) {
  7518. Headers headers;
  7519. headers.emplace("Accept-Encoding", "gzip, deflate");
  7520. cli_.set_decompress(false);
  7521. auto res = cli_.Get("/compress", headers);
  7522. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7523. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7524. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7525. EXPECT_EQ("33", res->get_header_value("Content-Length"));
  7526. EXPECT_EQ(33U, res->body.size());
  7527. EXPECT_EQ(StatusCode::OK_200, res->status);
  7528. }
  7529. TEST_F(ServerTest, GzipWithContentReceiverWithoutAcceptEncoding) {
  7530. Headers headers;
  7531. headers.emplace("Accept-Encoding", "");
  7532. std::string body;
  7533. auto res = cli_.Get("/compress", headers,
  7534. [&](const char *data, uint64_t data_length) {
  7535. EXPECT_EQ(100U, data_length);
  7536. body.append(data, data_length);
  7537. return true;
  7538. });
  7539. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7540. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7541. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7542. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7543. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7544. "7890123456789012345678901234567890",
  7545. body);
  7546. EXPECT_EQ(StatusCode::OK_200, res->status);
  7547. }
  7548. TEST_F(ServerTest, NoGzip) {
  7549. Headers headers;
  7550. headers.emplace("Accept-Encoding", "gzip, deflate");
  7551. auto res = cli_.Get("/nocompress", headers);
  7552. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7553. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7554. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7555. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7556. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7557. "7890123456789012345678901234567890",
  7558. res->body);
  7559. EXPECT_EQ(StatusCode::OK_200, res->status);
  7560. }
  7561. TEST_F(ServerTest, NoGzipWithContentReceiver) {
  7562. Headers headers;
  7563. headers.emplace("Accept-Encoding", "gzip, deflate");
  7564. std::string body;
  7565. auto res = cli_.Get("/nocompress", headers,
  7566. [&](const char *data, uint64_t data_length) {
  7567. EXPECT_EQ(100U, data_length);
  7568. body.append(data, data_length);
  7569. return true;
  7570. });
  7571. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7572. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  7573. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7574. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7575. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7576. "7890123456789012345678901234567890",
  7577. body);
  7578. EXPECT_EQ(StatusCode::OK_200, res->status);
  7579. }
  7580. TEST_F(ServerTest, MultipartFormDataGzip) {
  7581. UploadFormDataItems items = {
  7582. {"key1", "test", "", ""},
  7583. {"key2", "--abcdefg123", "", ""},
  7584. };
  7585. cli_.set_compress(true);
  7586. auto res = cli_.Post("/compress-multipart", items);
  7587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7588. EXPECT_EQ(StatusCode::OK_200, res->status);
  7589. }
  7590. #endif
  7591. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  7592. // Static file compression is opt-in, so these run their own server rather than
  7593. // flipping it on for the shared ServerTest fixture, which would silently
  7594. // rewrite what every other static file test is asserting.
  7595. class StaticFileCompressionTest : public ::testing::Test {
  7596. protected:
  7597. void TearDown() override {
  7598. if (t_.joinable()) {
  7599. svr_.stop();
  7600. t_.join();
  7601. }
  7602. }
  7603. int start(const std::function<void(Server &)> &configure = nullptr) {
  7604. // Serves the same tree as a directory of build-time compressed assets
  7605. // would be served: the mount point names the coding the files are already
  7606. // stored in. Registered before "/" so it is the one that matches.
  7607. svr_.set_mount_point("/pre-encoded", "./www",
  7608. {{"Content-Encoding", "gzip"}});
  7609. svr_.set_mount_point("/", "./www");
  7610. svr_.Get("/file_content", [](const Request & /*req*/, Response &res) {
  7611. res.set_file_content("./www/dir/index.html", "text/html");
  7612. });
  7613. svr_.Get("/pre-encoded-file-content",
  7614. [](const Request & /*req*/, Response &res) {
  7615. res.set_header("Content-Encoding", "gzip");
  7616. res.set_file_content("./www/dir/index.html", "text/html");
  7617. });
  7618. svr_.Get("/streamed", [](const Request & /*req*/, Response &res) {
  7619. res.set_content_provider(
  7620. 6, "text/plain",
  7621. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7622. sink.write(offset < 3 ? "aaa" : "bbb", 3);
  7623. return true;
  7624. });
  7625. });
  7626. svr_.Get("/slow-stream", [](const Request & /*req*/, Response &res) {
  7627. res.set_content_provider(
  7628. 1000, "text/plain",
  7629. [](size_t offset, size_t /*length*/, DataSink &sink) {
  7630. if (offset < 100) {
  7631. std::string data(100, 'A');
  7632. sink.write(data.data(), data.size());
  7633. return true;
  7634. }
  7635. std::this_thread::sleep_for(std::chrono::seconds(2));
  7636. std::string data(900, 'B');
  7637. sink.write(data.data(), data.size());
  7638. return true;
  7639. });
  7640. });
  7641. if (configure) { configure(svr_); }
  7642. auto port = svr_.bind_to_any_port(HOST);
  7643. t_ = std::thread([&]() { svr_.listen_after_bind(); });
  7644. svr_.wait_until_ready();
  7645. return port;
  7646. }
  7647. static void enable(Server &svr) { svr.set_static_file_compression(true); }
  7648. // Every file under ./www except 1MB.txt is smaller than the default
  7649. // 1400-byte floor, so a test that needs a small file compressed has to lower
  7650. // it out of the way.
  7651. static void enable_without_floor(Server &svr) {
  7652. svr.set_static_file_compression(true);
  7653. svr.set_static_file_compression_min_length(0);
  7654. }
  7655. Server svr_;
  7656. std::thread t_;
  7657. };
  7658. TEST_F(StaticFileCompressionTest, DisabledByDefault) {
  7659. auto port = start();
  7660. Client cli(HOST, port);
  7661. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7662. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7663. EXPECT_EQ(StatusCode::OK_200, res->status);
  7664. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7665. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7666. EXPECT_EQ(1048576U, res->body.size());
  7667. }
  7668. TEST_F(StaticFileCompressionTest, MountPoint) {
  7669. auto port = start(enable);
  7670. Client cli(HOST, port);
  7671. cli.set_decompress(false);
  7672. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7673. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7674. EXPECT_EQ(StatusCode::OK_200, res->status);
  7675. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7676. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7677. EXPECT_EQ("Accept-Encoding", res->get_header_value("Vary"));
  7678. // The response stays self-delimiting: a length, not a chunked body.
  7679. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7680. EXPECT_EQ(std::to_string(res->body.size()),
  7681. res->get_header_value("Content-Length"));
  7682. EXPECT_LT(res->body.size(), 1048576U);
  7683. EXPECT_FALSE(res->body.empty());
  7684. }
  7685. TEST_F(StaticFileCompressionTest, MountPointDecompressed) {
  7686. auto port = start(enable);
  7687. Client cli(HOST, port);
  7688. auto res = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7689. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7690. EXPECT_EQ(StatusCode::OK_200, res->status);
  7691. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7692. EXPECT_EQ(1048576U, res->body.size());
  7693. }
  7694. TEST_F(StaticFileCompressionTest, FileContent) {
  7695. auto port = start(enable_without_floor);
  7696. Client cli(HOST, port);
  7697. auto res = cli.Get("/file_content", Headers{{"Accept-Encoding", "gzip"}});
  7698. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7699. EXPECT_EQ(StatusCode::OK_200, res->status);
  7700. EXPECT_EQ("text/html", res->get_header_value("Content-Type"));
  7701. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7702. EXPECT_EQ(104U, res->body.size());
  7703. }
  7704. // A handler that serves an already-encoded file names the coding itself. The
  7705. // file-backed path decided its coding from Accept-Encoding and the content
  7706. // type alone, so it compressed the stored bytes a second time and appended a
  7707. // second Content-Encoding field line.
  7708. TEST_F(StaticFileCompressionTest, PreEncodedFileContentIsNotCompressedAgain) {
  7709. auto port = start(enable_without_floor);
  7710. Client cli(HOST, port);
  7711. cli.set_decompress(false);
  7712. auto res = cli.Get("/pre-encoded-file-content",
  7713. Headers{{"Accept-Encoding", "gzip"}});
  7714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7715. EXPECT_EQ(StatusCode::OK_200, res->status);
  7716. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7717. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7718. // Vary belongs to a coding the server chose, and it chose none here.
  7719. EXPECT_FALSE(res->has_header("Vary"));
  7720. // The file travels exactly as it is stored on disk.
  7721. EXPECT_EQ(104U, res->body.size());
  7722. }
  7723. // The 1MB file clears the default floor, so this one runs the configuration a
  7724. // deployment would actually have.
  7725. TEST_F(StaticFileCompressionTest, PreEncodedMountPointIsNotCompressedAgain) {
  7726. auto port = start(enable);
  7727. Client cli(HOST, port);
  7728. cli.set_decompress(false);
  7729. auto res =
  7730. cli.Get("/pre-encoded/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7731. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7732. EXPECT_EQ(StatusCode::OK_200, res->status);
  7733. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  7734. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7735. EXPECT_FALSE(res->has_header("Vary"));
  7736. EXPECT_EQ(1048576U, res->body.size());
  7737. EXPECT_EQ("1048576", res->get_header_value("Content-Length"));
  7738. }
  7739. TEST_F(StaticFileCompressionTest, Head) {
  7740. auto port = start(enable);
  7741. Client cli(HOST, port);
  7742. cli.set_decompress(false);
  7743. auto get = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7744. ASSERT_TRUE(get) << "Error: " << to_string(get.error());
  7745. auto res = cli.Head("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7746. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7747. EXPECT_EQ(StatusCode::OK_200, res->status);
  7748. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7749. EXPECT_FALSE(res->has_header("Transfer-Encoding"));
  7750. // HEAD still reports the size a GET would return.
  7751. EXPECT_EQ(get->get_header_value("Content-Length"),
  7752. res->get_header_value("Content-Length"));
  7753. EXPECT_TRUE(res->body.empty());
  7754. }
  7755. TEST_F(StaticFileCompressionTest, RangeStaysIdentity) {
  7756. auto port = start(enable);
  7757. Client cli(HOST, port);
  7758. auto res = cli.Get("/dir/test.abcde", Headers{make_range_header({{2, 3}}),
  7759. {"Accept-Encoding", "gzip"}});
  7760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7761. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  7762. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7763. EXPECT_EQ("2", res->get_header_value("Content-Length"));
  7764. EXPECT_EQ("bytes 2-3/5", res->get_header_value("Content-Range"));
  7765. EXPECT_EQ("cd", res->body);
  7766. }
  7767. TEST_F(StaticFileCompressionTest, NotCompressibleType) {
  7768. auto port = start(enable);
  7769. Client cli(HOST, port);
  7770. auto res = cli.Get("/file", Headers{{"Accept-Encoding", "gzip"}});
  7771. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7772. EXPECT_EQ(StatusCode::OK_200, res->status);
  7773. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  7774. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7775. EXPECT_EQ("5", res->get_header_value("Content-Length"));
  7776. }
  7777. TEST_F(StaticFileCompressionTest, EmptyFile) {
  7778. auto port = start(enable);
  7779. Client cli(HOST, port);
  7780. auto res = cli.Get("/empty_file", Headers{{"Accept-Encoding", "gzip"}});
  7781. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7782. EXPECT_EQ(StatusCode::OK_200, res->status);
  7783. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7784. EXPECT_EQ("0", res->get_header_value("Content-Length"));
  7785. EXPECT_TRUE(res->body.empty());
  7786. }
  7787. TEST_F(StaticFileCompressionTest, MinLength) {
  7788. auto port = start(enable);
  7789. Client cli(HOST, port);
  7790. // 104 bytes, well under the default floor. Compressing it would add the
  7791. // gzip header and trailer to a body that already fits in one packet.
  7792. auto res = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7793. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7794. EXPECT_EQ(StatusCode::OK_200, res->status);
  7795. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7796. EXPECT_EQ("104", res->get_header_value("Content-Length"));
  7797. }
  7798. TEST_F(StaticFileCompressionTest, MinLengthLowered) {
  7799. auto port = start([](Server &svr) {
  7800. svr.set_static_file_compression(true);
  7801. svr.set_static_file_compression_min_length(1);
  7802. });
  7803. Client cli(HOST, port);
  7804. cli.set_decompress(false);
  7805. auto res = cli.Get("/dir/test.html", Headers{{"Accept-Encoding", "gzip"}});
  7806. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7807. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  7808. // A 9-byte file comes back larger than it went in, because gzip's header and
  7809. // trailer outweigh anything deflate can save. That is the end of the range
  7810. // the floor exists to keep out.
  7811. EXPECT_GT(res->body.size(), 9U);
  7812. }
  7813. TEST_F(StaticFileCompressionTest, MaxLength) {
  7814. auto port = start([](Server &svr) {
  7815. svr.set_static_file_compression(true);
  7816. svr.set_static_file_compression_min_length(0);
  7817. svr.set_static_file_compression_max_length(1024);
  7818. });
  7819. Client cli(HOST, port);
  7820. // Over the limit: served as is. Not named `big`/`small`: <rpcndr.h>
  7821. // defines `small` as a macro on Windows.
  7822. auto over = cli.Get("/dir/1MB.txt", Headers{{"Accept-Encoding", "gzip"}});
  7823. ASSERT_TRUE(over) << "Error: " << to_string(over.error());
  7824. EXPECT_FALSE(over->has_header("Content-Encoding"));
  7825. EXPECT_EQ("1048576", over->get_header_value("Content-Length"));
  7826. // Under it: compressed.
  7827. auto under = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7828. ASSERT_TRUE(under) << "Error: " << to_string(under.error());
  7829. EXPECT_EQ("gzip", under->get_header_value("Content-Encoding"));
  7830. }
  7831. TEST_F(StaticFileCompressionTest, EtagPerEncoding) {
  7832. auto port = start(enable_without_floor);
  7833. Client cli(HOST, port);
  7834. auto identity = cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""}});
  7835. ASSERT_TRUE(identity) << "Error: " << to_string(identity.error());
  7836. EXPECT_FALSE(identity->has_header("Content-Encoding"));
  7837. auto identity_etag = identity->get_header_value("ETag");
  7838. ASSERT_FALSE(identity_etag.empty());
  7839. auto gzipped =
  7840. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"}});
  7841. ASSERT_TRUE(gzipped) << "Error: " << to_string(gzipped.error());
  7842. EXPECT_EQ("gzip", gzipped->get_header_value("Content-Encoding"));
  7843. auto gzip_etag = gzipped->get_header_value("ETag");
  7844. ASSERT_FALSE(gzip_etag.empty());
  7845. // Two representations, two validators.
  7846. EXPECT_NE(identity_etag, gzip_etag);
  7847. // Each one revalidates against the request that would produce it...
  7848. auto fresh =
  7849. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", "gzip"},
  7850. {"If-None-Match", gzip_etag}});
  7851. ASSERT_TRUE(fresh) << "Error: " << to_string(fresh.error());
  7852. EXPECT_EQ(StatusCode::NotModified_304, fresh->status);
  7853. auto fresh_identity =
  7854. cli.Get("/dir/index.html", Headers{{"Accept-Encoding", ""},
  7855. {"If-None-Match", identity_etag}});
  7856. ASSERT_TRUE(fresh_identity) << "Error: " << to_string(fresh_identity.error());
  7857. EXPECT_EQ(StatusCode::NotModified_304, fresh_identity->status);
  7858. // ...and not against the other representation.
  7859. auto crossed =
  7860. cli.Get("/dir/index.html",
  7861. Headers{{"Accept-Encoding", ""}, {"If-None-Match", gzip_etag}});
  7862. ASSERT_TRUE(crossed) << "Error: " << to_string(crossed.error());
  7863. EXPECT_EQ(StatusCode::OK_200, crossed->status);
  7864. }
  7865. // The opt-in covers responses the server reads off disk itself. A caller's own
  7866. // known-length provider keeps its Content-Length and, more importantly, keeps
  7867. // delivering incrementally: routing it through a compressor would hold every
  7868. // write back until zlib's window filled.
  7869. TEST_F(StaticFileCompressionTest, KnownLengthProviderUnaffected) {
  7870. auto port = start(enable);
  7871. Client cli(HOST, port);
  7872. auto res = cli.Get("/streamed", Headers{{"Accept-Encoding", "gzip"}});
  7873. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7874. EXPECT_EQ(StatusCode::OK_200, res->status);
  7875. EXPECT_FALSE(res->has_header("Content-Encoding"));
  7876. EXPECT_EQ("6", res->get_header_value("Content-Length"));
  7877. EXPECT_EQ("aaabbb", res->body);
  7878. }
  7879. TEST_F(StaticFileCompressionTest, IncrementalProviderUnaffected) {
  7880. auto port = start(enable);
  7881. Client cli(HOST, port);
  7882. cli.set_read_timeout(1, 0);
  7883. auto handle = cli.open_stream("GET", "/slow-stream", Params{},
  7884. Headers{{"Accept-Encoding", "gzip"}});
  7885. ASSERT_TRUE(handle.is_valid());
  7886. // The provider writes 100 bytes and then stalls for longer than the read
  7887. // timeout. Those first bytes have to arrive anyway: run the response through
  7888. // a compressor and zlib holds them until its window fills, so the read would
  7889. // come back empty instead.
  7890. char buf[256];
  7891. auto n = handle.read(buf, sizeof(buf));
  7892. ASSERT_GT(n, 0) << "first read should return the bytes already written";
  7893. EXPECT_EQ(std::string(100, 'A'), std::string(buf, static_cast<size_t>(n)));
  7894. }
  7895. #endif
  7896. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  7897. TEST_F(ServerTest, Brotli) {
  7898. Headers headers;
  7899. headers.emplace("Accept-Encoding", "br");
  7900. auto res = cli_.Get("/compress", headers);
  7901. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7902. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  7903. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7904. EXPECT_EQ("19", res->get_header_value("Content-Length"));
  7905. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7906. "7890123456789012345678901234567890",
  7907. res->body);
  7908. EXPECT_EQ(StatusCode::OK_200, res->status);
  7909. }
  7910. #endif
  7911. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  7912. TEST_F(ServerTest, Zstd) {
  7913. Headers headers;
  7914. headers.emplace("Accept-Encoding", "zstd");
  7915. auto res = cli_.Get("/compress", headers);
  7916. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7917. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7918. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7919. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7920. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7921. "7890123456789012345678901234567890",
  7922. res->body);
  7923. EXPECT_EQ(StatusCode::OK_200, res->status);
  7924. }
  7925. TEST_F(ServerTest, ZstdWithoutAcceptEncoding) {
  7926. Headers headers;
  7927. headers.emplace("Accept-Encoding", "");
  7928. auto res = cli_.Get("/compress", headers);
  7929. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7930. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7931. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7932. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7933. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7934. "7890123456789012345678901234567890",
  7935. res->body);
  7936. EXPECT_EQ(StatusCode::OK_200, res->status);
  7937. }
  7938. TEST_F(ServerTest, ZstdWithContentReceiver) {
  7939. Headers headers;
  7940. headers.emplace("Accept-Encoding", "zstd");
  7941. std::string body;
  7942. auto res = cli_.Get("/compress", headers,
  7943. [&](const char *data, uint64_t data_length) {
  7944. EXPECT_EQ(100U, data_length);
  7945. body.append(data, data_length);
  7946. return true;
  7947. });
  7948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7949. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7950. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7951. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7952. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7953. "7890123456789012345678901234567890",
  7954. body);
  7955. EXPECT_EQ(StatusCode::OK_200, res->status);
  7956. }
  7957. TEST_F(ServerTest, ZstdWithoutDecompressing) {
  7958. Headers headers;
  7959. headers.emplace("Accept-Encoding", "zstd");
  7960. cli_.set_decompress(false);
  7961. auto res = cli_.Get("/compress", headers);
  7962. unsigned char compressed[26] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x64, 0x8d,
  7963. 0x00, 0x00, 0x50, 0x31, 0x32, 0x33, 0x34,
  7964. 0x35, 0x36, 0x37, 0x38, 0x39, 0x30, 0x01,
  7965. 0x00, 0xd7, 0xa9, 0x20, 0x01};
  7966. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7967. EXPECT_EQ("zstd", res->get_header_value("Content-Encoding"));
  7968. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7969. EXPECT_EQ("26", res->get_header_value("Content-Length"));
  7970. EXPECT_EQ(StatusCode::OK_200, res->status);
  7971. ASSERT_EQ(26U, res->body.size());
  7972. EXPECT_TRUE(std::memcmp(compressed, res->body.data(), sizeof(compressed)) ==
  7973. 0);
  7974. }
  7975. TEST_F(ServerTest, ZstdWithContentReceiverWithoutAcceptEncoding) {
  7976. Headers headers;
  7977. headers.emplace("Accept-Encoding", "");
  7978. std::string body;
  7979. auto res = cli_.Get("/compress", headers,
  7980. [&](const char *data, uint64_t data_length) {
  7981. EXPECT_EQ(100U, data_length);
  7982. body.append(data, data_length);
  7983. return true;
  7984. });
  7985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7986. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  7987. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  7988. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  7989. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  7990. "7890123456789012345678901234567890",
  7991. body);
  7992. EXPECT_EQ(StatusCode::OK_200, res->status);
  7993. }
  7994. TEST_F(ServerTest, NoZstd) {
  7995. Headers headers;
  7996. headers.emplace("Accept-Encoding", "zstd");
  7997. auto res = cli_.Get("/nocompress", headers);
  7998. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  7999. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8000. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8001. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8002. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8003. "7890123456789012345678901234567890",
  8004. res->body);
  8005. EXPECT_EQ(StatusCode::OK_200, res->status);
  8006. }
  8007. TEST_F(ServerTest, NoZstdWithContentReceiver) {
  8008. Headers headers;
  8009. headers.emplace("Accept-Encoding", "zstd");
  8010. std::string body;
  8011. auto res = cli_.Get("/nocompress", headers,
  8012. [&](const char *data, uint64_t data_length) {
  8013. EXPECT_EQ(100U, data_length);
  8014. body.append(data, data_length);
  8015. return true;
  8016. });
  8017. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8018. EXPECT_EQ(false, res->has_header("Content-Encoding"));
  8019. EXPECT_EQ("application/octet-stream", res->get_header_value("Content-Type"));
  8020. EXPECT_EQ("100", res->get_header_value("Content-Length"));
  8021. EXPECT_EQ("123456789012345678901234567890123456789012345678901234567890123456"
  8022. "7890123456789012345678901234567890",
  8023. body);
  8024. EXPECT_EQ(StatusCode::OK_200, res->status);
  8025. }
  8026. // TODO: How to enable zstd ??
  8027. TEST_F(ServerTest, MultipartFormDataZstd) {
  8028. UploadFormDataItems items = {
  8029. {"key1", "test", "", ""},
  8030. {"key2", "--abcdefg123", "", ""},
  8031. };
  8032. Headers headers;
  8033. headers.emplace("Accept-Encoding", "zstd");
  8034. cli_.set_compress(true);
  8035. auto res = cli_.Post("/compress-multipart", headers, items);
  8036. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8037. EXPECT_EQ(StatusCode::OK_200, res->status);
  8038. }
  8039. TEST_F(ServerTest, PutWithContentProviderWithZstd) {
  8040. Headers headers;
  8041. headers.emplace("Accept-Encoding", "zstd");
  8042. cli_.set_compress(true);
  8043. auto res = cli_.Put(
  8044. "/put", headers, 3,
  8045. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  8046. sink.os << "PUT";
  8047. return true;
  8048. },
  8049. "text/plain");
  8050. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8051. EXPECT_EQ(StatusCode::OK_200, res->status);
  8052. EXPECT_EQ("PUT", res->body);
  8053. }
  8054. // Pre-compression logging tests
  8055. TEST_F(ServerTest, PreCompressionLogging) {
  8056. // Test data for compression (matches the actual /compress endpoint content)
  8057. const std::string test_content =
  8058. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8059. "3456789012345678901234567890";
  8060. // Variables to capture logging data
  8061. std::string pre_compression_body;
  8062. std::string pre_compression_content_type;
  8063. std::string pre_compression_content_encoding;
  8064. std::string post_compression_body;
  8065. std::string post_compression_content_type;
  8066. std::string post_compression_content_encoding;
  8067. // Set up pre-compression logger
  8068. svr_.set_pre_compression_logger([&](const Request & /*req*/,
  8069. const Response &res) {
  8070. pre_compression_body = res.body;
  8071. pre_compression_content_type = res.get_header_value("Content-Type");
  8072. pre_compression_content_encoding = res.get_header_value("Content-Encoding");
  8073. });
  8074. // Set up post-compression logger
  8075. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8076. post_compression_body = res.body;
  8077. post_compression_content_type = res.get_header_value("Content-Type");
  8078. post_compression_content_encoding =
  8079. res.get_header_value("Content-Encoding");
  8080. });
  8081. // Test with gzip compression
  8082. Headers headers;
  8083. headers.emplace("Accept-Encoding", "gzip");
  8084. auto res = cli_.Get("/compress", headers);
  8085. // Verify response was compressed
  8086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8087. EXPECT_EQ(StatusCode::OK_200, res->status);
  8088. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8089. // Verify pre-compression logger captured uncompressed content
  8090. EXPECT_EQ(test_content, pre_compression_body);
  8091. EXPECT_EQ("text/plain", pre_compression_content_type);
  8092. EXPECT_TRUE(pre_compression_content_encoding
  8093. .empty()); // No encoding header before compression
  8094. // Verify post-compression logger captured compressed content
  8095. EXPECT_NE(test_content,
  8096. post_compression_body); // Should be different after compression
  8097. EXPECT_EQ("text/plain", post_compression_content_type);
  8098. EXPECT_EQ("gzip", post_compression_content_encoding);
  8099. // Verify compressed content is smaller
  8100. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8101. }
  8102. TEST_F(ServerTest, PreCompressionLoggingWithBrotli) {
  8103. const std::string test_content =
  8104. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8105. "3456789012345678901234567890";
  8106. std::string pre_compression_body;
  8107. std::string post_compression_body;
  8108. svr_.set_pre_compression_logger(
  8109. [&](const Request & /*req*/, const Response &res) {
  8110. pre_compression_body = res.body;
  8111. });
  8112. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8113. post_compression_body = res.body;
  8114. });
  8115. Headers headers;
  8116. headers.emplace("Accept-Encoding", "br");
  8117. auto res = cli_.Get("/compress", headers);
  8118. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8119. EXPECT_EQ(StatusCode::OK_200, res->status);
  8120. EXPECT_EQ("br", res->get_header_value("Content-Encoding"));
  8121. // Verify pre-compression content is uncompressed
  8122. EXPECT_EQ(test_content, pre_compression_body);
  8123. // Verify post-compression content is compressed
  8124. EXPECT_NE(test_content, post_compression_body);
  8125. EXPECT_LT(post_compression_body.size(), pre_compression_body.size());
  8126. }
  8127. TEST_F(ServerTest, PreCompressionLoggingWithoutCompression) {
  8128. const std::string test_content =
  8129. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8130. "3456789012345678901234567890";
  8131. std::string pre_compression_body;
  8132. std::string post_compression_body;
  8133. svr_.set_pre_compression_logger(
  8134. [&](const Request & /*req*/, const Response &res) {
  8135. pre_compression_body = res.body;
  8136. });
  8137. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8138. post_compression_body = res.body;
  8139. });
  8140. // Request without compression (use /nocompress endpoint)
  8141. Headers headers;
  8142. auto res = cli_.Get("/nocompress", headers);
  8143. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8144. EXPECT_EQ(StatusCode::OK_200, res->status);
  8145. EXPECT_TRUE(res->get_header_value("Content-Encoding").empty());
  8146. // Pre-compression logger should not be called when no compression is applied
  8147. EXPECT_TRUE(
  8148. pre_compression_body.empty()); // Pre-compression logger not called
  8149. EXPECT_EQ(
  8150. test_content,
  8151. post_compression_body); // Post-compression logger captures final content
  8152. }
  8153. TEST_F(ServerTest, LoggerSeesContentLength) {
  8154. size_t logged_content_length = 0;
  8155. std::string logged_content_length_header;
  8156. svr_.set_logger([&](const Request & /*req*/, const Response &res) {
  8157. logged_content_length = res.content_length_;
  8158. logged_content_length_header = res.get_header_value("Content-Length");
  8159. });
  8160. auto res = cli_.Get("/nocompress");
  8161. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8162. EXPECT_EQ(StatusCode::OK_200, res->status);
  8163. EXPECT_EQ(res->body.size(), logged_content_length);
  8164. EXPECT_EQ(std::to_string(logged_content_length),
  8165. logged_content_length_header);
  8166. }
  8167. TEST_F(ServerTest, PreCompressionLoggingOnlyPreLogger) {
  8168. const std::string test_content =
  8169. "123456789012345678901234567890123456789012345678901234567890123456789012"
  8170. "3456789012345678901234567890";
  8171. std::string pre_compression_body;
  8172. bool pre_logger_called = false;
  8173. // Set only pre-compression logger
  8174. svr_.set_pre_compression_logger(
  8175. [&](const Request & /*req*/, const Response &res) {
  8176. pre_compression_body = res.body;
  8177. pre_logger_called = true;
  8178. });
  8179. Headers headers;
  8180. headers.emplace("Accept-Encoding", "gzip");
  8181. auto res = cli_.Get("/compress", headers);
  8182. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8183. EXPECT_EQ(StatusCode::OK_200, res->status);
  8184. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  8185. // Verify pre-compression logger was called
  8186. EXPECT_TRUE(pre_logger_called);
  8187. EXPECT_EQ(test_content, pre_compression_body);
  8188. }
  8189. TEST_F(ServerTest, SendLargeBodyAfterRequestLineError) {
  8190. {
  8191. // Test with Expect: 100-continue header - success case
  8192. // Server returns 100 Continue, client sends body, server returns 200 OK
  8193. Request req;
  8194. req.method = "POST";
  8195. req.path = "/post-large";
  8196. req.set_header("Expect", "100-continue");
  8197. req.body = LARGE_DATA;
  8198. Response res;
  8199. auto error = Error::Success;
  8200. cli_.set_keep_alive(true);
  8201. auto ret = cli_.send(req, res, error);
  8202. EXPECT_TRUE(ret);
  8203. EXPECT_EQ(StatusCode::OK_200, res.status);
  8204. EXPECT_EQ(LARGE_DATA, res.body);
  8205. }
  8206. {
  8207. // Test with Expect: 100-continue header - error case
  8208. // Client should not send the body when server returns an error
  8209. Request req;
  8210. req.method = "POST";
  8211. req.path = "/post-large?q=" + LONG_QUERY_VALUE;
  8212. req.set_header("Expect", "100-continue");
  8213. req.body = LARGE_DATA;
  8214. Response res;
  8215. auto error = Error::Success;
  8216. auto start = std::chrono::high_resolution_clock::now();
  8217. cli_.set_keep_alive(true);
  8218. auto ret = cli_.send(req, res, error);
  8219. auto end = std::chrono::high_resolution_clock::now();
  8220. auto elapsed =
  8221. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8222. .count();
  8223. // With Expect: 100-continue, request completes successfully but with error
  8224. EXPECT_TRUE(ret);
  8225. EXPECT_EQ(StatusCode::UriTooLong_414, res.status);
  8226. EXPECT_EQ("close", res.get_header_value("Connection"));
  8227. EXPECT_FALSE(cli_.is_socket_open());
  8228. EXPECT_LE(elapsed, 2000);
  8229. }
  8230. {
  8231. // Send an extra GET request to ensure error recovery without hanging
  8232. Request req;
  8233. req.method = "GET";
  8234. req.path = "/hi";
  8235. auto start = std::chrono::high_resolution_clock::now();
  8236. auto res = cli_.send(req);
  8237. auto end = std::chrono::high_resolution_clock::now();
  8238. auto elapsed =
  8239. std::chrono::duration_cast<std::chrono::milliseconds>(end - start)
  8240. .count();
  8241. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  8242. EXPECT_EQ(StatusCode::OK_200, res->status);
  8243. EXPECT_EQ("Hello World!", res->body);
  8244. EXPECT_LE(elapsed, 500);
  8245. }
  8246. }
  8247. TEST(ZstdDecompressor, ChunkedDecompression) {
  8248. std::string data;
  8249. for (size_t i = 0; i < 32 * 1024; ++i) {
  8250. data.push_back(static_cast<char>('a' + i % 26));
  8251. }
  8252. std::string compressed_data;
  8253. {
  8254. httplib::detail::zstd_compressor compressor;
  8255. bool result = compressor.compress(
  8256. data.data(), data.size(),
  8257. /*last=*/true,
  8258. [&](const char *compressed_data_chunk, size_t compressed_data_size) {
  8259. compressed_data.insert(compressed_data.size(), compressed_data_chunk,
  8260. compressed_data_size);
  8261. return true;
  8262. });
  8263. ASSERT_TRUE(result);
  8264. }
  8265. std::string decompressed_data;
  8266. {
  8267. httplib::detail::zstd_decompressor decompressor;
  8268. // Chunk size is chosen specifically to have a decompressed chunk size equal
  8269. // to 16384 bytes 16384 bytes is the size of decompressor output buffer
  8270. size_t chunk_size = 130;
  8271. for (size_t chunk_begin = 0; chunk_begin < compressed_data.size();
  8272. chunk_begin += chunk_size) {
  8273. size_t current_chunk_size =
  8274. std::min(compressed_data.size() - chunk_begin, chunk_size);
  8275. bool result = decompressor.decompress(
  8276. compressed_data.data() + chunk_begin, current_chunk_size,
  8277. [&](const char *decompressed_data_chunk,
  8278. size_t decompressed_data_chunk_size) {
  8279. decompressed_data.insert(decompressed_data.size(),
  8280. decompressed_data_chunk,
  8281. decompressed_data_chunk_size);
  8282. return true;
  8283. });
  8284. ASSERT_TRUE(result);
  8285. }
  8286. }
  8287. ASSERT_EQ(data, decompressed_data);
  8288. }
  8289. TEST(ZstdDecompressor, Decompress) {
  8290. std::string original_text = "Compressed with ZSTD";
  8291. unsigned char data[29] = {0x28, 0xb5, 0x2f, 0xfd, 0x20, 0x14, 0xa1, 0x00,
  8292. 0x00, 0x43, 0x6f, 0x6d, 0x70, 0x72, 0x65, 0x73,
  8293. 0x73, 0x65, 0x64, 0x20, 0x77, 0x69, 0x74, 0x68,
  8294. 0x20, 0x5a, 0x53, 0x54, 0x44};
  8295. std::string compressed_data(data, data + sizeof(data) / sizeof(data[0]));
  8296. std::string decompressed_data;
  8297. {
  8298. httplib::detail::zstd_decompressor decompressor;
  8299. bool result = decompressor.decompress(
  8300. compressed_data.data(), compressed_data.size(),
  8301. [&](const char *decompressed_data_chunk,
  8302. size_t decompressed_data_chunk_size) {
  8303. decompressed_data.insert(decompressed_data.size(),
  8304. decompressed_data_chunk,
  8305. decompressed_data_chunk_size);
  8306. return true;
  8307. });
  8308. ASSERT_TRUE(result);
  8309. }
  8310. ASSERT_EQ(original_text, decompressed_data);
  8311. }
  8312. #endif
  8313. // Sends a raw request to a server listening at HOST:PORT, writing it in
  8314. // separate chunks so that the server sees each part in its own read(). Used to
  8315. // place a read boundary at a specific offset of a request body.
  8316. static bool send_request_in_parts(time_t read_timeout_sec,
  8317. const std::vector<std::string> &parts,
  8318. std::string *resp = nullptr,
  8319. int port = PORT) {
  8320. auto error = Error::Success;
  8321. auto client_sock = detail::create_client_socket(
  8322. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  8323. /*connection_timeout_sec=*/5, 0,
  8324. /*read_timeout_sec=*/5, 0,
  8325. /*write_timeout_sec=*/5, 0, std::string(), error);
  8326. if (client_sock == INVALID_SOCKET) { return false; }
  8327. auto ret = detail::process_client_socket(
  8328. client_sock, read_timeout_sec, 0, 0, 0, 0,
  8329. std::chrono::steady_clock::time_point::min(), [&](Stream &strm) {
  8330. for (size_t i = 0; i < parts.size(); i++) {
  8331. const auto &part = parts[i];
  8332. if (part.size() !=
  8333. static_cast<size_t>(strm.write(part.data(), part.size()))) {
  8334. return false;
  8335. }
  8336. if (i + 1 < parts.size()) {
  8337. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  8338. }
  8339. }
  8340. char buf[512];
  8341. detail::stream_line_reader line_reader(strm, buf, sizeof(buf));
  8342. while (line_reader.getline()) {
  8343. if (resp) { *resp += line_reader.ptr(); }
  8344. }
  8345. return true;
  8346. });
  8347. detail::close_socket(client_sock);
  8348. return ret;
  8349. }
  8350. // Sends a raw request to a server listening at HOST:PORT.
  8351. static bool send_request(time_t read_timeout_sec, const std::string &req,
  8352. std::string *resp = nullptr, int port = PORT) {
  8353. return send_request_in_parts(read_timeout_sec, {req}, resp, port);
  8354. }
  8355. TEST(ServerRequestParsingTest, TrimWhitespaceFromHeaderValues) {
  8356. Server svr;
  8357. std::string header_value;
  8358. svr.Get("/validate-ws-in-headers", [&](const Request &req, Response &res) {
  8359. header_value = req.get_header_value("foo");
  8360. res.set_content("ok", "text/plain");
  8361. });
  8362. thread t = thread([&] { svr.listen(HOST, PORT); });
  8363. auto se = detail::scope_exit([&] {
  8364. svr.stop();
  8365. t.join();
  8366. ASSERT_FALSE(svr.is_running());
  8367. });
  8368. svr.wait_until_ready();
  8369. // Only space and horizontal tab are whitespace. Make sure other whitespace-
  8370. // like characters are not treated the same - use vertical tab and escape.
  8371. const std::string req = "GET /validate-ws-in-headers HTTP/1.1\r\n"
  8372. "foo: \t \v bar \x1B\t \r\n"
  8373. "Connection: close\r\n"
  8374. "\r\n";
  8375. std::string res;
  8376. ASSERT_TRUE(send_request(5, req, &res));
  8377. EXPECT_EQ(header_value, "");
  8378. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, 24));
  8379. }
  8380. TEST(HeadersOrderTest, ReceivedFieldsKeepTheirOrder) {
  8381. Server svr;
  8382. std::string received;
  8383. svr.Get("/order", [&](const Request &req, Response &res) {
  8384. received = entries_to_string(req.headers);
  8385. res.set_content("ok", "text/plain");
  8386. });
  8387. auto port = svr.bind_to_any_port(HOST);
  8388. thread t = thread([&] { svr.listen_after_bind(); });
  8389. auto se = detail::scope_exit([&] {
  8390. svr.stop();
  8391. t.join();
  8392. ASSERT_FALSE(svr.is_running());
  8393. });
  8394. svr.wait_until_ready();
  8395. const std::string req = "GET /order HTTP/1.1\r\n"
  8396. "X-First: 1\r\n"
  8397. "X-Dup: a\r\n"
  8398. "X-Second: 2\r\n"
  8399. "X-Dup: b\r\n"
  8400. "Connection: close\r\n"
  8401. "\r\n";
  8402. std::string res;
  8403. ASSERT_TRUE(send_request(5, req, &res, port));
  8404. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8405. EXPECT_EQ("X-First=1 X-Dup=a X-Second=2 X-Dup=b Connection=close ", received);
  8406. }
  8407. TEST(HeadersOrderTest, SentFieldsKeepTheirOrder) {
  8408. Server svr;
  8409. svr.Get("/cookies", [](const Request & /*req*/, Response &res) {
  8410. res.set_header("Set-Cookie", "first=1");
  8411. res.set_header("X-Between", "y");
  8412. res.set_header("Set-Cookie", "second=2");
  8413. res.set_content("ok", "text/plain");
  8414. });
  8415. auto port = svr.bind_to_any_port(HOST);
  8416. thread t = thread([&] { svr.listen_after_bind(); });
  8417. auto se = detail::scope_exit([&] {
  8418. svr.stop();
  8419. t.join();
  8420. ASSERT_FALSE(svr.is_running());
  8421. });
  8422. svr.wait_until_ready();
  8423. Client cli(HOST, port);
  8424. auto res = cli.Get("/cookies");
  8425. ASSERT_TRUE(res);
  8426. EXPECT_EQ(2U, res->get_header_value_count("Set-Cookie"));
  8427. EXPECT_EQ("first=1", res->get_header_value("Set-Cookie", "", 0));
  8428. EXPECT_EQ("second=2", res->get_header_value("Set-Cookie", "", 1));
  8429. }
  8430. TEST(ServerResponseSplittingTest, ChunkedTrailerCRLFInjection) {
  8431. Server svr;
  8432. svr.Get("/injected-trailer", [&](const Request & /*req*/, Response &res) {
  8433. auto i = new int(0);
  8434. res.set_header("Trailer", "X-Safe, X-Reflected");
  8435. res.set_chunked_content_provider(
  8436. "text/plain",
  8437. [i](size_t /*offset*/, DataSink &sink) {
  8438. if (*i == 0) {
  8439. sink.os << "body";
  8440. } else {
  8441. Headers trailer;
  8442. // A valid trailer that must survive.
  8443. trailer.emplace("X-Safe", "safe");
  8444. // Attacker-controlled value carrying CR/LF (response splitting).
  8445. trailer.emplace("X-Reflected",
  8446. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8447. // Attacker-controlled name carrying CR/LF.
  8448. trailer.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8449. sink.done_with_trailer(trailer);
  8450. }
  8451. (*i)++;
  8452. return true;
  8453. },
  8454. [i](bool /*success*/) { delete i; });
  8455. });
  8456. thread t = thread([&] { svr.listen(HOST, PORT); });
  8457. auto se = detail::scope_exit([&] {
  8458. svr.stop();
  8459. t.join();
  8460. ASSERT_FALSE(svr.is_running());
  8461. });
  8462. svr.wait_until_ready();
  8463. const std::string req = std::string("GET /injected-trailer HTTP/1.1\r\n") +
  8464. "Host: " + HOST +
  8465. "\r\n"
  8466. "Connection: close\r\n"
  8467. "\r\n";
  8468. std::string res;
  8469. ASSERT_TRUE(send_request(5, req, &res));
  8470. // The injected fields must not appear anywhere in the raw response.
  8471. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8472. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8473. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8474. // Invalid trailers are dropped entirely, matching set_header().
  8475. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8476. // The valid trailer still passes through.
  8477. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8478. }
  8479. TEST(ServerResponseSplittingTest, ResponseHeaderCRLFInjection) {
  8480. Server svr;
  8481. svr.Get("/injected-header", [&](const Request & /*req*/, Response &res) {
  8482. // res.headers is a public field an application can populate directly,
  8483. // bypassing set_header()'s validation (e.g. reflecting a request value).
  8484. // A valid header that must survive.
  8485. res.headers.emplace("X-Safe", "safe");
  8486. // Attacker-controlled value carrying CR/LF (response splitting).
  8487. res.headers.emplace("X-Reflected",
  8488. "legit\r\nInjected-Header: pwned\r\nX-Evil: also");
  8489. // Attacker-controlled name carrying CR/LF.
  8490. res.headers.emplace("X-Bad\r\nSet-Cookie: a=1", "x");
  8491. res.set_content("body", "text/plain");
  8492. });
  8493. thread t = thread([&] { svr.listen(HOST, PORT); });
  8494. auto se = detail::scope_exit([&] {
  8495. svr.stop();
  8496. t.join();
  8497. ASSERT_FALSE(svr.is_running());
  8498. });
  8499. svr.wait_until_ready();
  8500. const std::string req = std::string("GET /injected-header HTTP/1.1\r\n") +
  8501. "Host: " + HOST +
  8502. "\r\n"
  8503. "Connection: close\r\n"
  8504. "\r\n";
  8505. std::string res;
  8506. ASSERT_TRUE(send_request(5, req, &res));
  8507. // The injected fields must not appear anywhere in the raw response.
  8508. EXPECT_EQ(std::string::npos, res.find("Injected-Header"));
  8509. EXPECT_EQ(std::string::npos, res.find("X-Evil"));
  8510. EXPECT_EQ(std::string::npos, res.find("Set-Cookie"));
  8511. // Invalid headers are dropped entirely, matching set_header().
  8512. EXPECT_EQ(std::string::npos, res.find("X-Reflected:"));
  8513. // The valid header still passes through.
  8514. EXPECT_NE(std::string::npos, res.find("X-Safe: safe"));
  8515. }
  8516. // Forward declaration: in split builds split.py strips `inline` and moves the
  8517. // definition into httplib.cc, so detail::write_request_line is not visible from
  8518. // the public httplib.h. Re-declaring it here lets the tests link against the
  8519. // symbol in both header-only and split builds.
  8520. namespace httplib {
  8521. namespace detail {
  8522. ssize_t write_request_line(Stream &strm, const std::string &method,
  8523. const std::string &path);
  8524. } // namespace detail
  8525. } // namespace httplib
  8526. TEST(RequestLineInjectionTest, RejectsCRLFInTarget) {
  8527. // A well-formed target is written verbatim.
  8528. {
  8529. detail::BufferStream strm;
  8530. auto n = detail::write_request_line(strm, "GET", "/path?a=b");
  8531. EXPECT_GT(n, 0);
  8532. EXPECT_EQ("GET /path?a=b HTTP/1.1\r\n", strm.get_buffer());
  8533. }
  8534. // A target carrying CR/LF must be rejected before anything reaches the wire,
  8535. // otherwise it splits the request line and injects a header or a whole
  8536. // request. This is what a decoded redirect Location ("%0D%0A") turns into
  8537. // when path encoding is disabled.
  8538. const std::string evil_targets[] = {
  8539. "/a\r\nInjected: pwned",
  8540. "/a\rInjected",
  8541. "/a\nInjected",
  8542. "/a\r\n\r\nGET /evil HTTP/1.1\r\nHost: victim\r\n\r\n",
  8543. };
  8544. for (const auto &evil : evil_targets) {
  8545. detail::BufferStream strm;
  8546. auto n = detail::write_request_line(strm, "GET", evil);
  8547. EXPECT_LT(n, 0);
  8548. EXPECT_TRUE(strm.get_buffer().empty());
  8549. }
  8550. }
  8551. TEST(RequestLineInjectionTest, ClientRejectsCRLFTargetEndToEnd) {
  8552. // End-to-end counterpart to RejectsCRLFInTarget. With path encoding disabled
  8553. // the client transmits the target verbatim, so a CR/LF-bearing target -- what
  8554. // a redirect Location "%0D%0A" decodes to -- reaches write_request. The
  8555. // client must fail cleanly with Error::Write instead of putting a
  8556. // request-line-less, header-injecting request on the wire.
  8557. Server svr;
  8558. svr.Get("/a", [](const Request &, Response &res) {
  8559. res.set_content("ok", "text/plain");
  8560. });
  8561. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  8562. auto se = detail::scope_exit([&] {
  8563. svr.stop();
  8564. thread.join();
  8565. ASSERT_FALSE(svr.is_running());
  8566. });
  8567. svr.wait_until_ready();
  8568. {
  8569. Client cli(HOST, PORT);
  8570. cli.set_path_encode(false);
  8571. // The request is rejected before anything is written, so the connection
  8572. // stays silent and the subsequent response read would otherwise block for
  8573. // the full default read timeout. Shorten it -- the assertion is on the
  8574. // error, not the timeout.
  8575. cli.set_read_timeout(1, 0);
  8576. auto res = cli.Get("/a\r\nInjected: pwned");
  8577. EXPECT_FALSE(res);
  8578. EXPECT_EQ(Error::Write, res.error());
  8579. }
  8580. }
  8581. TEST(RequestLineInjectionTest, RejectsNonTokenMethod) {
  8582. // Methods that are tokens (RFC 9110 Section 9.1) are written verbatim,
  8583. // including extension methods.
  8584. const std::string good_methods[] = {"GET", "PROPFIND", "M-SEARCH"};
  8585. for (const auto &method : good_methods) {
  8586. detail::BufferStream strm;
  8587. auto n = detail::write_request_line(strm, method, "/");
  8588. EXPECT_GT(n, 0);
  8589. EXPECT_EQ(method + " / HTTP/1.1\r\n", strm.get_buffer());
  8590. }
  8591. // A method carrying CR/LF would split the request line and smuggle a whole
  8592. // request ahead of the real one. A space or an empty method corrupts the
  8593. // request line. All must be rejected before anything reaches the wire.
  8594. const std::string evil_methods[] = {
  8595. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8596. "GET\r\nInjected: pwned",
  8597. "GET\r",
  8598. "GET\n",
  8599. "GE T",
  8600. "",
  8601. };
  8602. for (const auto &evil : evil_methods) {
  8603. detail::BufferStream strm;
  8604. auto n = detail::write_request_line(strm, evil, "/");
  8605. EXPECT_LT(n, 0);
  8606. EXPECT_TRUE(strm.get_buffer().empty());
  8607. }
  8608. }
  8609. TEST(RequestLineInjectionTest, ClientRejectsNonTokenMethodEndToEnd) {
  8610. // End-to-end counterpart to RejectsNonTokenMethod: a smuggling method passed
  8611. // through Client::send must fail with Error::Write and no request, neither
  8612. // the smuggled one nor the real one, may reach the server.
  8613. Server svr;
  8614. std::atomic<int> request_count(0);
  8615. svr.set_pre_routing_handler([&](const Request &, Response &res) {
  8616. request_count++;
  8617. res.status = StatusCode::OK_200;
  8618. return Server::HandlerResponse::Handled;
  8619. });
  8620. auto port = svr.bind_to_any_port(HOST);
  8621. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  8622. auto se = detail::scope_exit([&] {
  8623. svr.stop();
  8624. thread.join();
  8625. ASSERT_FALSE(svr.is_running());
  8626. });
  8627. svr.wait_until_ready();
  8628. {
  8629. Client cli(HOST, port);
  8630. const std::string evil_methods[] = {
  8631. "GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET",
  8632. "GE T",
  8633. "",
  8634. };
  8635. for (const auto &evil : evil_methods) {
  8636. Request req;
  8637. req.method = evil;
  8638. req.path = "/";
  8639. auto res = cli.send(req);
  8640. EXPECT_FALSE(res);
  8641. EXPECT_EQ(Error::Write, res.error());
  8642. }
  8643. auto handle =
  8644. cli.open_stream("GET /smuggled HTTP/1.1\r\nHost: x\r\n\r\nGET", "/");
  8645. EXPECT_FALSE(handle.is_valid());
  8646. EXPECT_EQ(Error::Write, handle.error);
  8647. // A valid request on the same client still goes through.
  8648. auto res = cli.Get("/");
  8649. ASSERT_TRUE(res);
  8650. EXPECT_EQ(StatusCode::OK_200, res->status);
  8651. }
  8652. EXPECT_EQ(1, request_count.load());
  8653. }
  8654. // Sends a raw request and verifies that there isn't a crash or exception.
  8655. static void test_raw_request(const std::string &req,
  8656. std::string *out = nullptr) {
  8657. Server svr;
  8658. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  8659. res.set_content("ok", "text/plain");
  8660. });
  8661. svr.Put("/put_hi", [&](const Request & /*req*/, Response &res) {
  8662. res.set_content("ok", "text/plain");
  8663. });
  8664. svr.Get("/header_field_value_check",
  8665. [&](const Request & /*req*/, Response &res) {
  8666. res.set_content("ok", "text/plain");
  8667. });
  8668. svr.CustomRoute("PROPFIND", "/dav",
  8669. [&](const Request & /*req*/, Response &res) {
  8670. res.status = StatusCode::MultiStatus_207;
  8671. });
  8672. // Server read timeout must be longer than the client read timeout for the
  8673. // bug to reproduce, probably to force the server to process a request
  8674. // without a trailing blank line.
  8675. const time_t client_read_timeout_sec = 1;
  8676. svr.set_read_timeout(std::chrono::seconds(client_read_timeout_sec + 1));
  8677. bool listen_thread_ok = false;
  8678. thread t = thread([&] { listen_thread_ok = svr.listen(HOST, PORT); });
  8679. auto se = detail::scope_exit([&] {
  8680. svr.stop();
  8681. t.join();
  8682. ASSERT_FALSE(svr.is_running());
  8683. EXPECT_TRUE(listen_thread_ok);
  8684. });
  8685. svr.wait_until_ready();
  8686. ASSERT_TRUE(send_request(client_read_timeout_sec, req, out));
  8687. }
  8688. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity) {
  8689. // A certain header line causes an exception if the header property is parsed
  8690. // naively with a single regex. This occurs with libc++ but not libstdc++.
  8691. test_raw_request(
  8692. "GET /hi HTTP/1.1\r\n"
  8693. " : "
  8694. " "
  8695. " ");
  8696. }
  8697. TEST(ServerRequestParsingTest, ReadHeadersRegexComplexity2) {
  8698. // A certain header line causes an exception if the header property *name* is
  8699. // parsed with a regular expression starting with "(.+?):" - this is a non-
  8700. // greedy matcher and requires backtracking when there are a lot of ":"
  8701. // characters.
  8702. // This occurs with libc++ but not libstdc++.
  8703. test_raw_request(
  8704. "GET /hi HTTP/1.1\r\n"
  8705. ":-:::::::::::::::::::::::::::-::::::::::::::::::::::::@-&&&&&&&&&&&"
  8706. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8707. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-:::::"
  8708. "::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::::::::::::::::::::"
  8709. ":::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::"
  8710. "::::::::-:::::::::::::::::@-&&&&&&&--:::::::-::::::::::::::::::::::"
  8711. ":::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::"
  8712. "::::::::::-:::::::::::::::::@-&&&&&::::::::::::-:::::::::::::::::@-"
  8713. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8714. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8715. "::::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::@-&&"
  8716. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8717. "::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&"
  8718. "--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&"
  8719. "&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&"
  8720. "&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@-&&"
  8721. "&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::::@"
  8722. "-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::::"
  8723. "::@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::"
  8724. ":::::@-&&&&&&&&&&&::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-::::::"
  8725. ":::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-:::"
  8726. "::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&--:::::::-"
  8727. ":::::::::::::::::::::::::::::-:::::::::::::::::@-&&&&&&&&&&&---&&:&"
  8728. "&&.0------------:-:::::::::::::::::::::::::::::-:::::::::::::::::@-"
  8729. "&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-::::::::::::::::"
  8730. ":@-&&&&&&&&&&&--:::::::-:::::::::::::::::::::::::::::-:::::::::::::"
  8731. "::::@-&&&&&&&&&&&---&&:&&&.0------------O--------\rH PUTHTTP/1.1\r\n"
  8732. "&&&%%%");
  8733. }
  8734. TEST(ServerRequestParsingTest, ExcessiveWhitespaceInUnparsableHeaderLine) {
  8735. // Make sure this doesn't crash the server.
  8736. // In a previous version of the header line regex, the "\r" rendered the line
  8737. // unparsable and the regex engine repeatedly backtracked, trying to look for
  8738. // a new position where the leading white space ended and the field value
  8739. // began.
  8740. // The crash occurs with libc++ but not libstdc++.
  8741. test_raw_request("GET /hi HTTP/1.1\r\n"
  8742. "a:" +
  8743. std::string(2000, ' ') + '\r' + std::string(20, 'z') +
  8744. "\r\n"
  8745. "\r\n");
  8746. }
  8747. TEST(ServerRequestParsingTest, InvalidFirstChunkLengthInRequest) {
  8748. std::string out;
  8749. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8750. "Content-Type: text/plain\r\n"
  8751. "Transfer-Encoding: chunked\r\n"
  8752. "\r\n"
  8753. "nothex\r\n",
  8754. &out);
  8755. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8756. }
  8757. TEST(ServerRequestParsingTest, InvalidSecondChunkLengthInRequest) {
  8758. std::string out;
  8759. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8760. "Content-Type: text/plain\r\n"
  8761. "Transfer-Encoding: chunked\r\n"
  8762. "\r\n"
  8763. "3\r\n"
  8764. "xyz\r\n"
  8765. "NaN\r\n",
  8766. &out);
  8767. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8768. }
  8769. TEST(ServerRequestParsingTest, ChunkLengthTooHighInRequest) {
  8770. std::string out;
  8771. test_raw_request("PUT /put_hi HTTP/1.1\r\n"
  8772. "Content-Type: text/plain\r\n"
  8773. "Transfer-Encoding: chunked\r\n"
  8774. "\r\n"
  8775. // Length is too large for 64 bits.
  8776. "1ffffffffffffffff\r\n"
  8777. "xyz\r\n",
  8778. &out);
  8779. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8780. }
  8781. TEST(ServerRequestParsingTest, InvalidHeaderTextWithExtraCR) {
  8782. test_raw_request("GET /hi HTTP/1.1\r\n"
  8783. "Content-Type: text/plain\r\n\r");
  8784. }
  8785. TEST(ServerRequestParsingTest, InvalidSpaceInURL) {
  8786. std::string out;
  8787. test_raw_request("GET /h i HTTP/1.1\r\n\r\n", &out);
  8788. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8789. }
  8790. TEST(ServerRequestParsingTest, InvalidControlCharInURL) {
  8791. for (auto target : {"/h\ri", "/h\x7fi"}) {
  8792. std::string out;
  8793. test_raw_request(std::string("GET ") + target + " HTTP/1.1\r\n\r\n", &out);
  8794. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24)) << target;
  8795. }
  8796. }
  8797. TEST(ServerRequestParsingTest, NonAsciiInURLAccepted) {
  8798. std::string out;
  8799. test_raw_request("GET /hi?q=\xE3\x81\x82 HTTP/1.1\r\n"
  8800. "Connection: close\r\n\r\n",
  8801. &out);
  8802. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8803. }
  8804. TEST(ServerRequestParsingTest, RemoteAddrSetOnBadRequest) {
  8805. Server svr;
  8806. svr.set_error_handler([&](const Request &req, Response & /*res*/) {
  8807. EXPECT_TRUE(!req.remote_addr.empty());
  8808. });
  8809. thread t = thread([&] { svr.listen(HOST, PORT); });
  8810. auto se = detail::scope_exit([&] {
  8811. svr.stop();
  8812. t.join();
  8813. ASSERT_FALSE(svr.is_running());
  8814. });
  8815. svr.wait_until_ready();
  8816. // Send an invalid request line to trigger Bad Request
  8817. const std::string bad_req = "BADMETHOD / HTTP/1.1\r\nHost: localhost\r\n\r\n";
  8818. std::string out;
  8819. ASSERT_TRUE(send_request(5, bad_req, &out));
  8820. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8821. }
  8822. // A custom method with neither Content-Length nor Transfer-Encoding must be
  8823. // answered right away rather than blocking on a read that waits for EOF.
  8824. TEST(ServerRequestParsingTest, CustomMethodWithoutFraming) {
  8825. std::string out;
  8826. test_raw_request("PROPFIND /dav HTTP/1.1\r\nHost: localhost\r\n\r\n", &out);
  8827. EXPECT_EQ("HTTP/1.1 207 Multi-Status", out.substr(0, 25));
  8828. }
  8829. TEST(CustomRouteRegistrationTest, RejectsBuiltInMethods) {
  8830. const char *methods[] = {"GET", "HEAD", "POST", "PUT", "DELETE",
  8831. "CONNECT", "OPTIONS", "TRACE", "PATCH", "PRI"};
  8832. for (const auto *method : methods) {
  8833. Server svr;
  8834. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8835. EXPECT_FALSE(svr.is_valid()) << method;
  8836. EXPECT_FALSE(svr.listen(HOST, PORT)) << method;
  8837. }
  8838. }
  8839. TEST(CustomRouteRegistrationTest, RejectsNonTokenMethods) {
  8840. const char *methods[] = {"", "PRO PFIND", "PROP\tFIND", "PROP/FIND",
  8841. "PROP,FIND", "PROP:FIND", "PROP(FIND)", "\x01FIND"};
  8842. for (const auto *method : methods) {
  8843. Server svr;
  8844. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8845. EXPECT_FALSE(svr.is_valid()) << method;
  8846. }
  8847. }
  8848. TEST(CustomRouteRegistrationTest, AcceptsWebDavAndUpnpMethods) {
  8849. const char *methods[] = {"PROPFIND", "PROPPATCH", "MKCOL",
  8850. "COPY", "MOVE", "LOCK",
  8851. "UNLOCK", "REPORT", "SUBSCRIBE"};
  8852. Server svr;
  8853. for (const auto *method : methods) {
  8854. svr.CustomRoute(method, "/x", [](const Request &, Response &) {});
  8855. }
  8856. EXPECT_TRUE(svr.is_valid());
  8857. }
  8858. TEST(CustomRouteRegistrationTest, ContentReaderOverloadRejectsBuiltInMethods) {
  8859. Server svr;
  8860. svr.CustomRoute("POST", "/x",
  8861. [](const Request &, Response &, const ContentReader &) {});
  8862. EXPECT_FALSE(svr.is_valid());
  8863. }
  8864. TEST(CustomRouteRegistrationTest, RejectionIsSticky) {
  8865. Server svr;
  8866. svr.CustomRoute("PROPFIND", "/a", [](const Request &, Response &) {});
  8867. svr.CustomRoute("GET", "/b", [](const Request &, Response &) {});
  8868. svr.CustomRoute("MKCOL", "/c", [](const Request &, Response &) {});
  8869. EXPECT_FALSE(svr.is_valid());
  8870. }
  8871. TEST(CustomRouteRegistrationTest, ReportsRejectionToErrorLogger) {
  8872. Server svr;
  8873. auto captured = Error::Success;
  8874. svr.set_error_logger(
  8875. [&](const Error &err, const Request * /*req*/) { captured = err; });
  8876. svr.CustomRoute("POST", "/x", [](const Request &, Response &) {});
  8877. EXPECT_EQ(Error::InvalidHTTPMethod, captured);
  8878. }
  8879. TEST(ServerRequestParsingTest, InvalidFieldValueContains_CR_LF_NUL) {
  8880. std::string out;
  8881. std::string request(
  8882. "GET /header_field_value_check HTTP/1.1\r\nTest: [\r\x00\n]\r\n\r\n", 55);
  8883. test_raw_request(request, &out);
  8884. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8885. }
  8886. TEST(ServerRequestParsingTest, InvalidFieldValueContains_LF) {
  8887. std::string out;
  8888. std::string request(
  8889. "GET /header_field_value_check HTTP/1.1\r\nTest: [\n\n\n]\r\n\r\n", 55);
  8890. test_raw_request(request, &out);
  8891. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8892. }
  8893. TEST(ServerRequestParsingTest, InvalidFieldNameContains_PreceedingSpaces) {
  8894. std::string out;
  8895. std::string request(
  8896. "GET /header_field_value_check HTTP/1.1\r\n Test: val\r\n\r\n", 55);
  8897. test_raw_request(request, &out);
  8898. EXPECT_EQ("HTTP/1.1 400 Bad Request", out.substr(0, 24));
  8899. }
  8900. TEST(ServerRequestParsingTest, EmptyFieldValue) {
  8901. std::string out;
  8902. test_raw_request("GET /header_field_value_check HTTP/1.1\r\n"
  8903. "Test: \r\n\r\n",
  8904. &out);
  8905. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  8906. }
  8907. TEST(ServerRequestParsingTest, HeaderValueNotPercentDecoded) {
  8908. Server svr;
  8909. std::string x_custom;
  8910. std::string cookie;
  8911. std::string xff;
  8912. std::string x_unicode;
  8913. std::string x_iis;
  8914. svr.Get("/check", [&](const Request &req, Response &res) {
  8915. x_custom = req.get_header_value("X-Custom");
  8916. cookie = req.get_header_value("Cookie");
  8917. xff = req.get_header_value("X-Forwarded-For");
  8918. x_unicode = req.get_header_value("X-Unicode");
  8919. x_iis = req.get_header_value("X-IIS");
  8920. res.set_content("ok", "text/plain");
  8921. });
  8922. thread t = thread([&] { svr.listen(HOST, PORT); });
  8923. auto se = detail::scope_exit([&] {
  8924. svr.stop();
  8925. t.join();
  8926. ASSERT_FALSE(svr.is_running());
  8927. });
  8928. svr.wait_until_ready();
  8929. const std::string req = "GET /check HTTP/1.1\r\n"
  8930. "Host: localhost\r\n"
  8931. "X-Custom: a%0D%0AInjected: b\r\n"
  8932. "Cookie: session%3Dvictim%3B%20admin%3Dyes\r\n"
  8933. "X-Forwarded-For: 1.2.3.4%2C5.6.7.8\r\n"
  8934. "X-Unicode: %E3%81%82\r\n"
  8935. "X-IIS: %u00E9\r\n"
  8936. "Connection: close\r\n"
  8937. "\r\n";
  8938. std::string res;
  8939. ASSERT_TRUE(send_request(5, req, &res));
  8940. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8941. // Every value must be returned verbatim (wire form), with no decoding.
  8942. EXPECT_EQ("a%0D%0AInjected: b", x_custom);
  8943. EXPECT_EQ("session%3Dvictim%3B%20admin%3Dyes", cookie);
  8944. EXPECT_EQ("1.2.3.4%2C5.6.7.8", xff);
  8945. EXPECT_EQ("%E3%81%82", x_unicode);
  8946. EXPECT_EQ("%u00E9", x_iis);
  8947. }
  8948. // Applications that previously relied on automatic percent-decoding can
  8949. // reproduce the old behavior by explicitly calling decode_path_component()
  8950. // or, for RFC 3986 conformance, decode_uri_component().
  8951. TEST(ServerRequestParsingTest, HeaderValueExplicitDecodingByApplication) {
  8952. Server svr;
  8953. std::string decoded;
  8954. svr.Get("/check", [&](const Request &req, Response &res) {
  8955. decoded = decode_uri_component(req.get_header_value("X-Custom"));
  8956. res.set_content("ok", "text/plain");
  8957. });
  8958. thread t = thread([&] { svr.listen(HOST, PORT); });
  8959. auto se = detail::scope_exit([&] {
  8960. svr.stop();
  8961. t.join();
  8962. ASSERT_FALSE(svr.is_running());
  8963. });
  8964. svr.wait_until_ready();
  8965. const std::string req = "GET /check HTTP/1.1\r\n"
  8966. "Host: localhost\r\n"
  8967. "X-Custom: hello%20world\r\n"
  8968. "Connection: close\r\n"
  8969. "\r\n";
  8970. std::string res;
  8971. ASSERT_TRUE(send_request(5, req, &res));
  8972. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  8973. EXPECT_EQ("hello world", decoded);
  8974. }
  8975. // Regression test for #2033. Browsers send Referer values that include
  8976. // percent-encoded characters such as %0A inside the URL. Decoding the
  8977. // header value would either trip the post-decode CR/LF/NUL guard (the
  8978. // original bug, returning 400) or, after that guard was relaxed, silently
  8979. // store a literal LF — both unacceptable. The wire form must round-trip.
  8980. TEST(ServerRequestParsingTest, RefererWithPercentEncodedNewline) {
  8981. Server svr;
  8982. std::string referer;
  8983. svr.Get("/check", [&](const Request &req, Response &res) {
  8984. referer = req.get_header_value("Referer");
  8985. res.set_content("ok", "text/plain");
  8986. });
  8987. thread t = thread([&] { svr.listen(HOST, PORT); });
  8988. auto se = detail::scope_exit([&] {
  8989. svr.stop();
  8990. t.join();
  8991. ASSERT_FALSE(svr.is_running());
  8992. });
  8993. svr.wait_until_ready();
  8994. const std::string req = "GET /check HTTP/1.1\r\n"
  8995. "Host: localhost\r\n"
  8996. "Referer: http://localhost:1111/?q=Hello%0A\r\n"
  8997. "Connection: close\r\n"
  8998. "\r\n";
  8999. std::string res;
  9000. ASSERT_TRUE(send_request(5, req, &res));
  9001. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  9002. EXPECT_EQ("http://localhost:1111/?q=Hello%0A", referer);
  9003. }
  9004. TEST(ServerStopTest, StopServerWithChunkedTransmission) {
  9005. Server svr;
  9006. svr.Get("/events", [](const Request & /*req*/, Response &res) {
  9007. res.set_header("Cache-Control", "no-cache");
  9008. res.set_chunked_content_provider(
  9009. "text/event-stream", [](size_t offset, DataSink &sink) {
  9010. std::string s = "data:";
  9011. s += std::to_string(offset);
  9012. s += "\n\n";
  9013. auto ret = sink.write(s.data(), s.size());
  9014. EXPECT_TRUE(ret);
  9015. std::this_thread::sleep_for(std::chrono::seconds(1));
  9016. return true;
  9017. });
  9018. });
  9019. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9020. svr.wait_until_ready();
  9021. Client client(HOST, PORT);
  9022. const Headers headers = {{"Accept", "text/event-stream"}};
  9023. auto get_thread = std::thread([&client, &headers]() {
  9024. auto res = client.Get(
  9025. "/events", headers,
  9026. [](const char * /*data*/, size_t /*len*/) -> bool { return true; });
  9027. });
  9028. auto se = detail::scope_exit([&] {
  9029. svr.stop();
  9030. get_thread.join();
  9031. listen_thread.join();
  9032. ASSERT_FALSE(svr.is_running());
  9033. });
  9034. // Give GET time to get a few messages.
  9035. std::this_thread::sleep_for(std::chrono::seconds(2));
  9036. }
  9037. TEST(ServerStopTest, ClientAccessAfterServerDown) {
  9038. httplib::Server svr;
  9039. svr.Post("/hi",
  9040. [&](const httplib::Request & /*req*/, httplib::Response &res) {
  9041. res.status = StatusCode::OK_200;
  9042. });
  9043. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  9044. svr.wait_until_ready();
  9045. Client cli(HOST, PORT);
  9046. auto res = cli.Post("/hi", "data", "text/plain");
  9047. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9048. EXPECT_EQ(StatusCode::OK_200, res->status);
  9049. svr.stop();
  9050. thread.join();
  9051. ASSERT_FALSE(svr.is_running());
  9052. res = cli.Post("/hi", "data", "text/plain");
  9053. ASSERT_FALSE(res);
  9054. }
  9055. TEST(ServerStopTest, ListenFailure) {
  9056. Server svr;
  9057. auto t = thread([&]() {
  9058. auto ret = svr.listen("????", PORT);
  9059. EXPECT_FALSE(ret);
  9060. });
  9061. svr.wait_until_ready();
  9062. svr.stop();
  9063. t.join();
  9064. }
  9065. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  9066. TEST(ServerStopTest, Decommision) {
  9067. Server svr;
  9068. svr.Get("/hi", [&](const Request &, Response &res) { res.body = "hi..."; });
  9069. for (int i = 0; i < 4; i++) {
  9070. auto is_even = !(i % 2);
  9071. std::thread t{[&] {
  9072. try {
  9073. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  9074. if (is_even) {
  9075. throw std::runtime_error("Some thing that happens to go wrong.");
  9076. }
  9077. svr.listen(HOST, PORT);
  9078. } catch (...) { svr.decommission(); }
  9079. }};
  9080. svr.wait_until_ready();
  9081. // Server is up
  9082. {
  9083. Client cli(HOST, PORT);
  9084. auto res = cli.Get("/hi");
  9085. if (is_even) {
  9086. EXPECT_FALSE(res);
  9087. } else {
  9088. EXPECT_TRUE(res);
  9089. EXPECT_EQ("hi...", res->body);
  9090. }
  9091. }
  9092. svr.stop();
  9093. t.join();
  9094. // Server is down...
  9095. {
  9096. Client cli(HOST, PORT);
  9097. auto res = cli.Get("/hi");
  9098. EXPECT_FALSE(res);
  9099. }
  9100. }
  9101. }
  9102. #endif
  9103. // Helper function for string body upload progress tests
  9104. template <typename SetupHandler, typename ClientCall>
  9105. void TestStringBodyUploadProgress(SetupHandler &&setup_handler,
  9106. ClientCall &&client_call,
  9107. const string &body) {
  9108. Server svr;
  9109. setup_handler(svr);
  9110. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9111. auto se = detail::scope_exit([&] {
  9112. svr.stop();
  9113. t.join();
  9114. });
  9115. svr.wait_until_ready();
  9116. Client cli(HOST, PORT);
  9117. vector<uint64_t> progress_values;
  9118. bool progress_called = false;
  9119. auto res =
  9120. client_call(cli, body, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9121. progress_values.push_back(current);
  9122. progress_called = true;
  9123. return true;
  9124. });
  9125. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9126. EXPECT_EQ(200, res->status);
  9127. EXPECT_TRUE(progress_called);
  9128. }
  9129. TEST(UploadProgressTest, PostStringBodyBasic) {
  9130. TestStringBodyUploadProgress(
  9131. [](Server &svr) {
  9132. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9133. res.set_content("received", "text/plain");
  9134. });
  9135. },
  9136. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9137. return cli.Post("/test", body, "text/plain", progress_callback);
  9138. },
  9139. "test data for upload progress");
  9140. }
  9141. TEST(UploadProgressTest, PutStringBodyBasic) {
  9142. TestStringBodyUploadProgress(
  9143. [](Server &svr) {
  9144. svr.Put("/test", [](const Request & /*req*/, Response &res) {
  9145. res.set_content("put received", "text/plain");
  9146. });
  9147. },
  9148. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9149. return cli.Put("/test", body, "text/plain", progress_callback);
  9150. },
  9151. "put test data for upload progress");
  9152. }
  9153. TEST(UploadProgressTest, PatchStringBodyBasic) {
  9154. TestStringBodyUploadProgress(
  9155. [](Server &svr) {
  9156. svr.Patch("/test", [](const Request & /*req*/, Response &res) {
  9157. res.set_content("patch received", "text/plain");
  9158. });
  9159. },
  9160. [](Client &cli, const string &body, UploadProgress progress_callback) {
  9161. return cli.Patch("/test", body, "text/plain", progress_callback);
  9162. },
  9163. "patch test data for upload progress");
  9164. }
  9165. // Helper function for content provider upload progress tests
  9166. template <typename SetupHandler, typename ClientCall>
  9167. void TestContentProviderUploadProgress(SetupHandler &&setup_handler,
  9168. ClientCall &&client_call) {
  9169. Server svr;
  9170. setup_handler(svr);
  9171. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9172. auto se = detail::scope_exit([&] {
  9173. svr.stop();
  9174. t.join();
  9175. });
  9176. svr.wait_until_ready();
  9177. Client cli(HOST, PORT);
  9178. vector<uint64_t> progress_values;
  9179. auto res =
  9180. client_call(cli, [&](uint64_t current, uint64_t /*total*/) -> bool {
  9181. progress_values.push_back(current);
  9182. return true;
  9183. });
  9184. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9185. EXPECT_EQ(200, res->status);
  9186. EXPECT_FALSE(progress_values.empty());
  9187. }
  9188. TEST(UploadProgressTest, PostContentProviderProgress) {
  9189. TestContentProviderUploadProgress(
  9190. [](Server &svr) {
  9191. svr.Post("/test", [](const Request & /*req*/, Response &res) {
  9192. res.set_content("provider received", "text/plain");
  9193. });
  9194. },
  9195. [](Client &cli, UploadProgress progress_callback) {
  9196. return cli.Post(
  9197. "/test", 10,
  9198. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) -> bool {
  9199. sink.os << "test data";
  9200. return true;
  9201. },
  9202. "text/plain", progress_callback);
  9203. });
  9204. }
  9205. // Helper function for multipart upload progress tests
  9206. template <typename SetupHandler, typename ClientCall>
  9207. void TestMultipartUploadProgress(SetupHandler &&setup_handler,
  9208. ClientCall &&client_call,
  9209. const string &endpoint) {
  9210. Server svr;
  9211. setup_handler(svr);
  9212. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9213. auto se = detail::scope_exit([&] {
  9214. svr.stop();
  9215. t.join();
  9216. });
  9217. svr.wait_until_ready();
  9218. Client cli(HOST, PORT);
  9219. vector<uint64_t> progress_values;
  9220. UploadFormDataItems items = {
  9221. {"field1", "value1", "", ""},
  9222. {"field2", "longer value for progress tracking test", "", ""},
  9223. {"file1", "file content data for upload progress", "test.txt",
  9224. "text/plain"}};
  9225. auto res = client_call(cli, endpoint, items,
  9226. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9227. progress_values.push_back(current);
  9228. return true;
  9229. });
  9230. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9231. EXPECT_EQ(200, res->status);
  9232. EXPECT_FALSE(progress_values.empty());
  9233. }
  9234. TEST(UploadProgressTest, PostMultipartProgress) {
  9235. TestMultipartUploadProgress(
  9236. [](Server &svr) {
  9237. svr.Post("/multipart", [](const Request &req, Response &res) {
  9238. EXPECT_TRUE(!req.form.files.empty() || !req.form.fields.empty());
  9239. res.set_content("multipart received", "text/plain");
  9240. });
  9241. },
  9242. [](Client &cli, const string &endpoint, const UploadFormDataItems &items,
  9243. UploadProgress progress_callback) {
  9244. return cli.Post(endpoint, items, progress_callback);
  9245. },
  9246. "/multipart");
  9247. }
  9248. // Helper function for basic download progress tests
  9249. template <typename SetupHandler, typename ClientCall>
  9250. void TestBasicDownloadProgress(SetupHandler &&setup_handler,
  9251. ClientCall &&client_call, const string &endpoint,
  9252. size_t expected_content_size) {
  9253. Server svr;
  9254. setup_handler(svr);
  9255. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9256. auto se = detail::scope_exit([&] {
  9257. svr.stop();
  9258. t.join();
  9259. });
  9260. svr.wait_until_ready();
  9261. Client cli(HOST, PORT);
  9262. vector<uint64_t> progress_values;
  9263. auto res = client_call(cli, endpoint,
  9264. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9265. progress_values.push_back(current);
  9266. return true;
  9267. });
  9268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9269. EXPECT_EQ(200, res->status);
  9270. EXPECT_FALSE(progress_values.empty());
  9271. EXPECT_EQ(expected_content_size, res->body.size());
  9272. }
  9273. TEST(DownloadProgressTest, GetBasic) {
  9274. TestBasicDownloadProgress(
  9275. [](Server &svr) {
  9276. svr.Get("/download", [](const Request & /*req*/, Response &res) {
  9277. string content(1000, 'D');
  9278. res.set_content(content, "text/plain");
  9279. });
  9280. },
  9281. [](Client &cli, const string &endpoint,
  9282. DownloadProgress progress_callback) {
  9283. return cli.Get(endpoint, progress_callback);
  9284. },
  9285. "/download", 1000u);
  9286. }
  9287. // Helper function for content receiver download progress tests
  9288. template <typename SetupHandler, typename ClientCall>
  9289. void TestContentReceiverDownloadProgress(SetupHandler &&setup_handler,
  9290. ClientCall &&client_call,
  9291. const string &endpoint,
  9292. size_t expected_content_size) {
  9293. Server svr;
  9294. setup_handler(svr);
  9295. thread t = thread([&]() { svr.listen(HOST, PORT); });
  9296. auto se = detail::scope_exit([&] {
  9297. svr.stop();
  9298. t.join();
  9299. });
  9300. svr.wait_until_ready();
  9301. Client cli(HOST, PORT);
  9302. vector<uint64_t> progress_values;
  9303. string received_body;
  9304. auto res = client_call(
  9305. cli, endpoint,
  9306. [&](const char *data, size_t data_length) -> bool {
  9307. received_body.append(data, data_length);
  9308. return true;
  9309. },
  9310. [&](uint64_t current, uint64_t /*total*/) -> bool {
  9311. progress_values.push_back(current);
  9312. return true;
  9313. });
  9314. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9315. EXPECT_EQ(200, res->status);
  9316. EXPECT_FALSE(progress_values.empty());
  9317. EXPECT_EQ(expected_content_size, received_body.size());
  9318. EXPECT_TRUE(res->body.empty());
  9319. }
  9320. TEST(DownloadProgressTest, GetWithContentReceiver) {
  9321. TestContentReceiverDownloadProgress(
  9322. [](Server &svr) {
  9323. svr.Get("/download-receiver",
  9324. [](const Request & /*req*/, Response &res) {
  9325. string content(2000, 'R');
  9326. res.set_content(content, "text/plain");
  9327. });
  9328. },
  9329. [](Client &cli, const string &endpoint, ContentReceiver content_receiver,
  9330. DownloadProgress progress_callback) {
  9331. return cli.Get(endpoint, content_receiver, progress_callback);
  9332. },
  9333. "/download-receiver", 2000u);
  9334. }
  9335. TEST(StreamingTest, ChunkedZeroLengthWriteDoesNotEndTheBody) {
  9336. // A provider reaching a pass with nothing to hand over - an empty buffer
  9337. // popped off a queue, say - must not be taken to mean the body is finished.
  9338. // It used to end the loop with the terminating chunk unwritten while the
  9339. // server still considered the response complete, so the peer waited for an
  9340. // end that never arrived.
  9341. Server svr;
  9342. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9343. auto step = std::make_shared<int>(0);
  9344. res.set_chunked_content_provider("text/plain",
  9345. [step](size_t /*offset*/, DataSink &sink) {
  9346. switch ((*step)++) {
  9347. case 0: sink.write("", 0); break;
  9348. case 1: sink.write("hello", 5); break;
  9349. default: sink.done(); break;
  9350. }
  9351. return true;
  9352. });
  9353. });
  9354. auto port = svr.bind_to_any_port(HOST);
  9355. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9356. auto listen_se = detail::scope_exit([&] {
  9357. svr.stop();
  9358. listen_thread.join();
  9359. ASSERT_FALSE(svr.is_running());
  9360. });
  9361. svr.wait_until_ready();
  9362. Client cli(HOST, port);
  9363. // Without the fix the body is never terminated, so bound the wait rather
  9364. // than letting the test hang on the default read timeout.
  9365. cli.set_read_timeout(5, 0);
  9366. auto res = cli.Get("/stream");
  9367. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9368. EXPECT_EQ(StatusCode::OK_200, res->status);
  9369. EXPECT_EQ("hello", res->body);
  9370. }
  9371. TEST(StreamingTest, NoContentLengthStreaming) {
  9372. Server svr;
  9373. svr.Get("/stream", [](const Request & /*req*/, Response &res) {
  9374. res.set_content_provider("text/plain", [](size_t offset, DataSink &sink) {
  9375. if (offset < 6) {
  9376. sink.os << (offset < 3 ? "a" : "b");
  9377. } else {
  9378. sink.done();
  9379. }
  9380. return true;
  9381. });
  9382. });
  9383. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9384. auto listen_se = detail::scope_exit([&] {
  9385. svr.stop();
  9386. listen_thread.join();
  9387. ASSERT_FALSE(svr.is_running());
  9388. });
  9389. svr.wait_until_ready();
  9390. Client client(HOST, PORT);
  9391. auto get_thread = std::thread([&client]() {
  9392. std::string s;
  9393. auto res =
  9394. client.Get("/stream", [&s](const char *data, size_t len) -> bool {
  9395. s += std::string(data, len);
  9396. return true;
  9397. });
  9398. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9399. EXPECT_EQ(StatusCode::OK_200, res->status);
  9400. EXPECT_EQ("aaabbb", s);
  9401. });
  9402. auto get_se = detail::scope_exit([&] { get_thread.join(); });
  9403. // Give GET time to get a few messages.
  9404. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  9405. }
  9406. TEST(MountTest, Unmount) {
  9407. Server svr;
  9408. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9409. auto se = detail::scope_exit([&] {
  9410. svr.stop();
  9411. listen_thread.join();
  9412. ASSERT_FALSE(svr.is_running());
  9413. });
  9414. svr.wait_until_ready();
  9415. Client cli("localhost", PORT);
  9416. svr.set_mount_point("/mount2", "./www2");
  9417. auto res = cli.Get("/");
  9418. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9419. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9420. res = cli.Get("/mount2/dir/test.html");
  9421. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9422. EXPECT_EQ(StatusCode::OK_200, res->status);
  9423. svr.set_mount_point("/", "./www");
  9424. res = cli.Get("/dir/");
  9425. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9426. EXPECT_EQ(StatusCode::OK_200, res->status);
  9427. svr.remove_mount_point("/");
  9428. res = cli.Get("/dir/");
  9429. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9430. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9431. svr.remove_mount_point("/mount2");
  9432. res = cli.Get("/mount2/dir/test.html");
  9433. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9434. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9435. }
  9436. TEST(MountTest, PathSegmentBoundary) {
  9437. Server svr;
  9438. svr.set_mount_point("/mount2", "./www2");
  9439. svr.set_mount_point("/", "./www");
  9440. auto port = svr.bind_to_any_port(HOST);
  9441. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9442. auto se = detail::scope_exit([&] {
  9443. svr.stop();
  9444. listen_thread.join();
  9445. ASSERT_FALSE(svr.is_running());
  9446. });
  9447. svr.wait_until_ready();
  9448. Client cli(HOST, port);
  9449. auto res = cli.Get("/mount2/dir/test.html");
  9450. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9451. EXPECT_EQ(StatusCode::OK_200, res->status);
  9452. // "/mount2" must not match part-way through a path segment.
  9453. res = cli.Get("/mount2dir/test.html");
  9454. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9455. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9456. // A mount point ending in '/' keeps matching every path below it.
  9457. res = cli.Get("/dir/test.html");
  9458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9459. EXPECT_EQ(StatusCode::OK_200, res->status);
  9460. }
  9461. TEST(MountTest, Redicect) {
  9462. Server svr;
  9463. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9464. auto se = detail::scope_exit([&] {
  9465. svr.stop();
  9466. listen_thread.join();
  9467. ASSERT_FALSE(svr.is_running());
  9468. });
  9469. svr.set_mount_point("/", "./www");
  9470. svr.wait_until_ready();
  9471. Client cli("localhost", PORT);
  9472. auto res = cli.Get("/dir/");
  9473. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9474. EXPECT_EQ(StatusCode::OK_200, res->status);
  9475. res = cli.Get("/dir");
  9476. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9477. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  9478. res = cli.Get("/file");
  9479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9480. EXPECT_EQ(StatusCode::OK_200, res->status);
  9481. res = cli.Get("/file/");
  9482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9483. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9484. cli.set_follow_location(true);
  9485. res = cli.Get("/dir");
  9486. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9487. EXPECT_EQ(StatusCode::OK_200, res->status);
  9488. }
  9489. TEST(MountTest, MultibytesPathName) {
  9490. Server svr;
  9491. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9492. auto se = detail::scope_exit([&] {
  9493. svr.stop();
  9494. listen_thread.join();
  9495. ASSERT_FALSE(svr.is_running());
  9496. });
  9497. svr.set_mount_point("/", "./www");
  9498. svr.wait_until_ready();
  9499. Client cli("localhost", PORT);
  9500. auto res = cli.Get(U8("/日本語Dir/日本語File.txt"));
  9501. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9502. EXPECT_EQ(StatusCode::OK_200, res->status);
  9503. EXPECT_EQ(U8("日本語コンテンツ"), res->body);
  9504. }
  9505. #ifdef _WIN32
  9506. // Issue #2435: mmap::open() must succeed even when another handle holds
  9507. // the file open for writing (e.g. an active log file).
  9508. TEST(MmapTest, OpenWhileFileHeldForWriting) {
  9509. const char *path = "mmap_concurrent_writer_test.txt";
  9510. const char *content = "hello";
  9511. {
  9512. std::ofstream f(path, std::ios::binary);
  9513. f.write(content, static_cast<std::streamsize>(strlen(content)));
  9514. }
  9515. auto file_cleanup = detail::scope_exit([&] { std::remove(path); });
  9516. HANDLE writer = ::CreateFileA(path, GENERIC_WRITE, FILE_SHARE_READ, NULL,
  9517. OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, NULL);
  9518. ASSERT_NE(INVALID_HANDLE_VALUE, writer);
  9519. auto handle_cleanup = detail::scope_exit([&] { ::CloseHandle(writer); });
  9520. detail::mmap m(path);
  9521. ASSERT_TRUE(m.is_open());
  9522. EXPECT_EQ(strlen(content), m.size());
  9523. EXPECT_EQ(0, std::memcmp(content, m.data(), strlen(content)));
  9524. }
  9525. #endif
  9526. #ifndef _WIN32
  9527. // A failed ::mmap() must not be reported as an open mapping, otherwise data()
  9528. // hands the caller the MAP_FAILED sentinel. A directory is the easiest way to
  9529. // reach it, since ::open() and fstat() succeed for one but ::mmap() doesn't.
  9530. TEST(MmapTest, FailedMappingIsNotOpen) {
  9531. const char *path = "./mmap_failed_mapping_test_dir";
  9532. ASSERT_EQ(0, ::mkdir(path, 0755));
  9533. auto dir_cleanup = detail::scope_exit([&] { ::rmdir(path); });
  9534. detail::mmap m(path);
  9535. EXPECT_FALSE(m.is_open());
  9536. EXPECT_EQ(0U, m.size());
  9537. EXPECT_NE(static_cast<const void *>(m.data()),
  9538. static_cast<const void *>(MAP_FAILED));
  9539. }
  9540. #endif
  9541. TEST(KeepAliveTest, ReadTimeout) {
  9542. Server svr;
  9543. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9544. std::this_thread::sleep_for(std::chrono::seconds(2));
  9545. res.set_content("a", "text/plain");
  9546. });
  9547. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  9548. res.set_content("b", "text/plain");
  9549. });
  9550. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9551. auto se = detail::scope_exit([&] {
  9552. svr.stop();
  9553. listen_thread.join();
  9554. ASSERT_FALSE(svr.is_running());
  9555. });
  9556. svr.wait_until_ready();
  9557. Client cli("localhost", PORT);
  9558. cli.set_keep_alive(true);
  9559. cli.set_read_timeout(std::chrono::seconds(1));
  9560. auto resa = cli.Get("/a");
  9561. ASSERT_FALSE(resa);
  9562. EXPECT_EQ(Error::Read, resa.error());
  9563. auto resb = cli.Get("/b");
  9564. ASSERT_TRUE(resb);
  9565. EXPECT_EQ(StatusCode::OK_200, resb->status);
  9566. EXPECT_EQ("b", resb->body);
  9567. }
  9568. TEST(KeepAliveTest, MaxCount) {
  9569. size_t keep_alive_max_count = 3;
  9570. Server svr;
  9571. svr.set_keep_alive_max_count(keep_alive_max_count);
  9572. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9573. res.set_content("Hello World!", "text/plain");
  9574. });
  9575. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9576. auto se = detail::scope_exit([&] {
  9577. svr.stop();
  9578. listen_thread.join();
  9579. ASSERT_FALSE(svr.is_running());
  9580. });
  9581. svr.wait_until_ready();
  9582. Client cli(HOST, PORT);
  9583. cli.set_keep_alive(true);
  9584. for (size_t i = 0; i < 5; i++) {
  9585. auto result = cli.Get("/hi");
  9586. ASSERT_TRUE(result);
  9587. EXPECT_EQ(StatusCode::OK_200, result->status);
  9588. if (i == keep_alive_max_count - 1) {
  9589. EXPECT_EQ("close", result->get_header_value("Connection"));
  9590. } else {
  9591. EXPECT_FALSE(result->has_header("Connection"));
  9592. }
  9593. }
  9594. }
  9595. TEST(KeepAliveTest, Issue1041) {
  9596. Server svr;
  9597. svr.set_keep_alive_timeout(3);
  9598. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9599. res.set_content("Hello World!", "text/plain");
  9600. });
  9601. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9602. auto se = detail::scope_exit([&] {
  9603. svr.stop();
  9604. listen_thread.join();
  9605. ASSERT_FALSE(svr.is_running());
  9606. });
  9607. svr.wait_until_ready();
  9608. Client cli(HOST, PORT);
  9609. cli.set_keep_alive(true);
  9610. auto result = cli.Get("/hi");
  9611. ASSERT_TRUE(result);
  9612. EXPECT_EQ(StatusCode::OK_200, result->status);
  9613. std::this_thread::sleep_for(std::chrono::seconds(5));
  9614. result = cli.Get("/hi");
  9615. ASSERT_TRUE(result);
  9616. EXPECT_EQ(StatusCode::OK_200, result->status);
  9617. }
  9618. TEST(KeepAliveTest, Issue1959) {
  9619. Server svr;
  9620. svr.set_keep_alive_timeout(5);
  9621. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  9622. res.set_content("a", "text/plain");
  9623. });
  9624. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9625. auto se = detail::scope_exit([&] {
  9626. if (!svr.is_running()) return;
  9627. svr.stop();
  9628. listen_thread.join();
  9629. ASSERT_FALSE(svr.is_running());
  9630. });
  9631. svr.wait_until_ready();
  9632. Client cli("localhost", PORT);
  9633. cli.set_keep_alive(true);
  9634. using namespace std::chrono;
  9635. auto start = steady_clock::now();
  9636. cli.Get("/a");
  9637. svr.stop();
  9638. listen_thread.join();
  9639. auto end = steady_clock::now();
  9640. auto elapsed = duration_cast<milliseconds>(end - start).count();
  9641. EXPECT_LT(elapsed, 5000);
  9642. }
  9643. #ifdef CPPHTTPLIB_SSL_ENABLED
  9644. TEST(KeepAliveTest, SSLClientReconnection) {
  9645. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9646. ASSERT_TRUE(svr.is_valid());
  9647. svr.set_keep_alive_timeout(1);
  9648. svr.Get("/hi", [](const httplib::Request &, httplib::Response &res) {
  9649. res.set_content("Hello World!", "text/plain");
  9650. });
  9651. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9652. auto se = detail::scope_exit([&] {
  9653. svr.stop();
  9654. listen_thread.join();
  9655. ASSERT_FALSE(svr.is_running());
  9656. });
  9657. svr.wait_until_ready();
  9658. SSLClient cli(HOST, PORT);
  9659. cli.enable_server_certificate_verification(false);
  9660. cli.set_keep_alive(true);
  9661. auto result = cli.Get("/hi");
  9662. ASSERT_TRUE(result);
  9663. EXPECT_EQ(StatusCode::OK_200, result->status);
  9664. result = cli.Get("/hi");
  9665. ASSERT_TRUE(result);
  9666. EXPECT_EQ(StatusCode::OK_200, result->status);
  9667. std::this_thread::sleep_for(std::chrono::seconds(2));
  9668. // Recoonect
  9669. result = cli.Get("/hi");
  9670. ASSERT_TRUE(result);
  9671. EXPECT_EQ(StatusCode::OK_200, result->status);
  9672. result = cli.Get("/hi");
  9673. ASSERT_TRUE(result);
  9674. EXPECT_EQ(StatusCode::OK_200, result->status);
  9675. }
  9676. TEST(KeepAliveTest, SSLClientReconnectionPost) {
  9677. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9678. ASSERT_TRUE(svr.is_valid());
  9679. svr.set_keep_alive_timeout(1);
  9680. std::string content = "reconnect";
  9681. svr.Post("/hi", [](const httplib::Request &, httplib::Response &res) {
  9682. res.set_content("Hello World!", "text/plain");
  9683. });
  9684. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9685. auto se = detail::scope_exit([&] {
  9686. svr.stop();
  9687. listen_thread.join();
  9688. ASSERT_FALSE(svr.is_running());
  9689. });
  9690. svr.wait_until_ready();
  9691. SSLClient cli(HOST, PORT);
  9692. cli.enable_server_certificate_verification(false);
  9693. cli.set_keep_alive(true);
  9694. auto result = cli.Post(
  9695. "/hi", content.size(),
  9696. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9697. sink.write(content.c_str(), content.size());
  9698. return true;
  9699. },
  9700. "text/plain");
  9701. ASSERT_TRUE(result);
  9702. EXPECT_EQ(200, result->status);
  9703. std::this_thread::sleep_for(std::chrono::seconds(2));
  9704. // Recoonect
  9705. result = cli.Post(
  9706. "/hi", content.size(),
  9707. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9708. sink.write(content.c_str(), content.size());
  9709. return true;
  9710. },
  9711. "text/plain");
  9712. ASSERT_TRUE(result);
  9713. EXPECT_EQ(200, result->status);
  9714. result = cli.Post(
  9715. "/hi", content.size(),
  9716. [&content](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9717. sink.write(content.c_str(), content.size());
  9718. return true;
  9719. },
  9720. "text/plain");
  9721. ASSERT_TRUE(result);
  9722. EXPECT_EQ(200, result->status);
  9723. }
  9724. TEST(SNI_AutoDetectionTest, SNI_Logic) {
  9725. using namespace httplib::tls;
  9726. {
  9727. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  9728. ASSERT_TRUE(svr.is_valid());
  9729. svr.Get("/sni", [&](const Request &req, Response &res) {
  9730. std::string expected = req.sni();
  9731. EXPECT_EQ(expected, req.get_param_value("expected"));
  9732. res.set_content("ok", "text/plain");
  9733. });
  9734. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  9735. auto se = detail::scope_exit([&] {
  9736. svr.stop();
  9737. listen_thread.join();
  9738. ASSERT_FALSE(svr.is_running());
  9739. });
  9740. svr.wait_until_ready();
  9741. {
  9742. SSLClient cli("localhost", PORT);
  9743. cli.enable_server_certificate_verification(false);
  9744. auto res = cli.Get("/sni?expected=localhost");
  9745. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9746. }
  9747. {
  9748. SSLClient cli("::1", PORT);
  9749. cli.enable_server_certificate_verification(false);
  9750. auto res = cli.Get("/sni?expected=");
  9751. // NOTE: This may fail if the server is listening on IPv4 only
  9752. // (e.g., when localhost resolves to 127.0.0.1 only)
  9753. if (res) {
  9754. EXPECT_EQ(StatusCode::OK_200, res->status);
  9755. } else {
  9756. EXPECT_EQ(Error::Connection, res.error());
  9757. }
  9758. }
  9759. }
  9760. }
  9761. #endif
  9762. TEST(ClientProblemDetectionTest, ContentProvider) {
  9763. Server svr;
  9764. size_t content_length = 1024 * 1024;
  9765. svr.Get("/hi", [&](const Request & /*req*/, Response &res) {
  9766. res.set_content_provider(
  9767. content_length, "text/plain",
  9768. [&](size_t offset, size_t length, DataSink &sink) {
  9769. auto out_len = std::min(length, static_cast<size_t>(1024));
  9770. std::string out(out_len, '@');
  9771. sink.write(out.data(), out_len);
  9772. return offset < 4096;
  9773. },
  9774. [](bool success) { ASSERT_FALSE(success); });
  9775. });
  9776. svr.Get("/empty", [&](const Request & /*req*/, Response &res) {
  9777. res.set_content_provider(
  9778. 0, "text/plain",
  9779. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) -> bool {
  9780. EXPECT_TRUE(false);
  9781. return true;
  9782. },
  9783. [](bool success) { ASSERT_FALSE(success); });
  9784. });
  9785. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9786. auto se = detail::scope_exit([&] {
  9787. svr.stop();
  9788. listen_thread.join();
  9789. ASSERT_FALSE(svr.is_running());
  9790. });
  9791. svr.wait_until_ready();
  9792. Client cli("localhost", PORT);
  9793. {
  9794. auto res = cli.Get("/hi", [&](const char * /*data*/,
  9795. size_t /*data_length*/) { return false; });
  9796. ASSERT_FALSE(res);
  9797. }
  9798. {
  9799. auto res = cli.Get("/empty", [&](const char * /*data*/,
  9800. size_t /*data_length*/) { return false; });
  9801. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9802. }
  9803. }
  9804. TEST(ContentProviderTest, ProviderMakingNoProgressFails) {
  9805. // A provider that reports success without writing anything and without
  9806. // calling done() used to be handed the same offset and length again on every
  9807. // pass, so it spun for as long as the peer stayed connected.
  9808. Server svr;
  9809. svr.Post("/", [](const Request & /*req*/, Response &res) {
  9810. res.set_content("ok", "text/plain");
  9811. });
  9812. auto port = svr.bind_to_any_port(HOST);
  9813. auto listen_thread = std::thread([&svr] { svr.listen_after_bind(); });
  9814. auto se = detail::scope_exit([&] {
  9815. svr.stop();
  9816. listen_thread.join();
  9817. ASSERT_FALSE(svr.is_running());
  9818. });
  9819. svr.wait_until_ready();
  9820. std::atomic<int> call_count{0};
  9821. Client cli(HOST, port);
  9822. auto res = cli.Post(
  9823. "/", 1024,
  9824. [&](size_t /*offset*/, size_t /*length*/, DataSink & /*sink*/) {
  9825. // Give up after enough passes to show the spin, so that losing the
  9826. // check below fails this test instead of hanging it.
  9827. return ++call_count < 100;
  9828. },
  9829. "text/plain");
  9830. ASSERT_FALSE(res);
  9831. EXPECT_EQ(Error::Write, res.error());
  9832. EXPECT_EQ(1, call_count.load());
  9833. }
  9834. TEST(DataSinkTest, OptionalCallbacksAreCallableByDefault) {
  9835. // A writer only has to assign `write`. The other three used to be left as
  9836. // empty std::functions, so a provider calling one threw
  9837. // std::bad_function_call out of the thread running it and took the whole
  9838. // process down.
  9839. DataSink sink;
  9840. std::string written;
  9841. sink.write = [&](const char *data, size_t data_len) {
  9842. written.append(data, data_len);
  9843. return true;
  9844. };
  9845. EXPECT_TRUE(sink.is_writable());
  9846. sink.done();
  9847. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9848. EXPECT_TRUE(written.empty());
  9849. }
  9850. TEST(DataSinkTest, DoneWithTrailerFallsBackToDone) {
  9851. // A sink that cannot carry trailers still has to finish.
  9852. DataSink sink;
  9853. auto done_count = 0;
  9854. sink.done = [&]() { done_count++; };
  9855. sink.done_with_trailer(Headers{{"X-Trailer", "value"}});
  9856. EXPECT_EQ(1, done_count);
  9857. }
  9858. TEST(DataSinkTest, LengthFramedProviderMayCallDoneAfterWritingEverything) {
  9859. Server svr;
  9860. const std::string body(4096, 'x');
  9861. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  9862. res.set_content_provider(body.size(), "text/plain",
  9863. [&](size_t offset, size_t length, DataSink &sink) {
  9864. sink.write(body.data() + offset, length);
  9865. sink.done();
  9866. return true;
  9867. });
  9868. });
  9869. auto port = svr.bind_to_any_port(HOST);
  9870. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9871. auto se = detail::scope_exit([&] {
  9872. svr.stop();
  9873. listen_thread.join();
  9874. ASSERT_FALSE(svr.is_running());
  9875. });
  9876. svr.wait_until_ready();
  9877. Client cli(HOST, port);
  9878. auto res = cli.Get("/");
  9879. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9880. EXPECT_EQ(StatusCode::OK_200, res->status);
  9881. EXPECT_EQ(body, res->body);
  9882. }
  9883. TEST(DataSinkTest, LengthFramedProviderThatFinishesEarlyFailsTheResponse) {
  9884. Server svr;
  9885. svr.Get("/", [](const Request & /*req*/, Response &res) {
  9886. res.set_content_provider(
  9887. 1024, "text/plain",
  9888. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9889. sink.write("hello", 5);
  9890. sink.done(); // short of the 1024 bytes the response promised
  9891. return true;
  9892. });
  9893. });
  9894. auto port = svr.bind_to_any_port(HOST);
  9895. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  9896. auto se = detail::scope_exit([&] {
  9897. svr.stop();
  9898. listen_thread.join();
  9899. ASSERT_FALSE(svr.is_running());
  9900. });
  9901. svr.wait_until_ready();
  9902. Client cli(HOST, port);
  9903. cli.set_read_timeout(5, 0);
  9904. // The response is short of its Content-Length, so the client cannot read a
  9905. // complete body. What matters is that this returns at all: a no-op done()
  9906. // would leave the writer looping over a provider that never makes progress.
  9907. auto res = cli.Get("/");
  9908. EXPECT_FALSE(res);
  9909. }
  9910. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  9911. TEST(DataSinkTest, CompressedRequestProviderThatFinishesEarlyFails) {
  9912. // The compressed path builds the whole body before connecting, so this
  9913. // fails client-side and never reaches a server.
  9914. Client cli(HOST, PORT);
  9915. cli.set_compress(true);
  9916. auto res = cli.Post(
  9917. "/", 1024,
  9918. [](size_t /*offset*/, size_t /*length*/, DataSink &sink) {
  9919. sink.write("hello", 5);
  9920. sink.done(); // short of the 1024 bytes the request announced
  9921. return true;
  9922. },
  9923. "text/plain");
  9924. ASSERT_FALSE(res);
  9925. EXPECT_EQ(Error::Write, res.error());
  9926. }
  9927. #endif
  9928. TEST(ErrorHandlerWithContentProviderTest, ErrorHandler) {
  9929. Server svr;
  9930. svr.set_error_handler([](Request const &, Response &res) -> void {
  9931. res.set_chunked_content_provider(
  9932. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9933. sink.os << "hello";
  9934. sink.os << "world";
  9935. sink.done();
  9936. return true;
  9937. });
  9938. });
  9939. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9940. auto se = detail::scope_exit([&] {
  9941. svr.stop();
  9942. listen_thread.join();
  9943. ASSERT_FALSE(svr.is_running());
  9944. });
  9945. svr.wait_until_ready();
  9946. Client cli("localhost", PORT);
  9947. auto res = cli.Get("/");
  9948. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  9949. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  9950. EXPECT_EQ("helloworld", res->body);
  9951. }
  9952. TEST(LongPollingTest, ClientCloseDetection) {
  9953. Server svr;
  9954. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9955. res.set_chunked_content_provider(
  9956. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9957. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9958. sink.os << "hello";
  9959. auto count = 10;
  9960. while (count > 0 && sink.is_writable()) {
  9961. this_thread::sleep_for(chrono::milliseconds(10));
  9962. count--;
  9963. }
  9964. EXPECT_FALSE(sink.is_writable()); // the socket is closed
  9965. return true;
  9966. });
  9967. });
  9968. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  9969. auto se = detail::scope_exit([&] {
  9970. svr.stop();
  9971. listen_thread.join();
  9972. ASSERT_FALSE(svr.is_running());
  9973. });
  9974. svr.wait_until_ready();
  9975. Client cli("localhost", PORT);
  9976. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  9977. EXPECT_EQ("hello", string(data, data_length));
  9978. return false; // close the socket immediately.
  9979. });
  9980. ASSERT_FALSE(res);
  9981. }
  9982. TEST(LongPollingTest, ClientCloseDetectionWithStreamOperator) {
  9983. Server svr;
  9984. svr.Get("/events", [&](const Request & /*req*/, Response &res) {
  9985. res.set_chunked_content_provider(
  9986. "text/plain", [](std::size_t const, DataSink &sink) -> bool {
  9987. EXPECT_TRUE(sink.is_writable()); // the socket is alive
  9988. sink.os << "hello";
  9989. EXPECT_TRUE(sink.os.good());
  9990. // Wait for the client to close the connection
  9991. auto count = 10;
  9992. while (count > 0 && sink.is_writable()) {
  9993. this_thread::sleep_for(chrono::milliseconds(10));
  9994. count--;
  9995. }
  9996. // After client disconnect, write repeatedly until the socket
  9997. // write actually fails (small writes may be absorbed by the
  9998. // kernel buffer)
  9999. std::string chunk(1024, 'x');
  10000. for (int i = 0; i < 1000 && sink.os.good(); i++) {
  10001. sink.os << chunk;
  10002. }
  10003. EXPECT_TRUE(sink.os.fail());
  10004. return true;
  10005. });
  10006. });
  10007. auto port = svr.bind_to_any_port("localhost");
  10008. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10009. auto se = detail::scope_exit([&] {
  10010. svr.stop();
  10011. listen_thread.join();
  10012. ASSERT_FALSE(svr.is_running());
  10013. });
  10014. svr.wait_until_ready();
  10015. Client cli("localhost", port);
  10016. auto res = cli.Get("/events", [&](const char *data, size_t data_length) {
  10017. EXPECT_EQ("hello", string(data, data_length));
  10018. return false; // close the socket immediately.
  10019. });
  10020. ASSERT_FALSE(res);
  10021. }
  10022. TEST(GetWithParametersTest, GetWithParameters) {
  10023. Server svr;
  10024. svr.Get("/", [&](const Request &req, Response &) {
  10025. EXPECT_EQ("world", req.get_param_value("hello"));
  10026. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10027. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10028. });
  10029. svr.Get("/params", [&](const Request &req, Response &) {
  10030. EXPECT_EQ("world", req.get_param_value("hello"));
  10031. EXPECT_EQ("world2", req.get_param_value("hello2"));
  10032. EXPECT_EQ("world3", req.get_param_value("hello3"));
  10033. });
  10034. svr.Get(R"(/resources/([a-z0-9\\-]+))", [&](const Request &req, Response &) {
  10035. EXPECT_EQ("resource-id", req.matches[1]);
  10036. EXPECT_EQ("foo", req.get_param_value("param1"));
  10037. EXPECT_EQ("bar", req.get_param_value("param2"));
  10038. });
  10039. svr.Get("/users/:id", [&](const Request &req, Response &) {
  10040. EXPECT_EQ("user-id", req.path_params.at("id"));
  10041. EXPECT_EQ("foo", req.get_param_value("param1"));
  10042. EXPECT_EQ("bar", req.get_param_value("param2"));
  10043. });
  10044. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  10045. auto se = detail::scope_exit([&] {
  10046. svr.stop();
  10047. listen_thread.join();
  10048. ASSERT_FALSE(svr.is_running());
  10049. });
  10050. svr.wait_until_ready();
  10051. {
  10052. Client cli(HOST, PORT);
  10053. Params params;
  10054. params.emplace("hello", "world");
  10055. params.emplace("hello2", "world2");
  10056. params.emplace("hello3", "world3");
  10057. auto res = cli.Get("/", params, Headers{});
  10058. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10059. EXPECT_EQ(StatusCode::OK_200, res->status);
  10060. }
  10061. {
  10062. Client cli(HOST, PORT);
  10063. auto res = cli.Get("/params?hello=world&hello2=world2&hello3=world3");
  10064. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10065. EXPECT_EQ(StatusCode::OK_200, res->status);
  10066. }
  10067. {
  10068. Client cli(HOST, PORT);
  10069. auto res = cli.Get("/resources/resource-id?param1=foo&param2=bar");
  10070. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10071. EXPECT_EQ(StatusCode::OK_200, res->status);
  10072. }
  10073. {
  10074. Client cli(HOST, PORT);
  10075. auto res = cli.Get("/users/user-id?param1=foo&param2=bar");
  10076. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10077. EXPECT_EQ(StatusCode::OK_200, res->status);
  10078. }
  10079. }
  10080. TEST(GetWithParametersTest, GetWithParameters2) {
  10081. Server svr;
  10082. svr.Get("/", [&](const Request &req, Response &res) {
  10083. auto text = req.get_param_value("hello");
  10084. res.set_content(text, "text/plain");
  10085. });
  10086. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10087. auto se = detail::scope_exit([&] {
  10088. svr.stop();
  10089. listen_thread.join();
  10090. ASSERT_FALSE(svr.is_running());
  10091. });
  10092. svr.wait_until_ready();
  10093. Client cli("localhost", PORT);
  10094. Params params;
  10095. params.emplace("hello", "world");
  10096. std::string body;
  10097. auto res = cli.Get("/", params, Headers{},
  10098. [&](const char *data, size_t data_length) {
  10099. body.append(data, data_length);
  10100. return true;
  10101. });
  10102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10103. EXPECT_EQ(StatusCode::OK_200, res->status);
  10104. EXPECT_EQ("world", body);
  10105. }
  10106. TEST(GetWithParametersTest, GetWithParamsOnlyNoHeaders) {
  10107. Server svr;
  10108. svr.Get("/search", [&](const Request &req, Response &res) {
  10109. auto q = req.get_param_value("q");
  10110. res.set_content(q, "text/plain");
  10111. });
  10112. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10113. auto se = detail::scope_exit([&] {
  10114. svr.stop();
  10115. listen_thread.join();
  10116. ASSERT_FALSE(svr.is_running());
  10117. });
  10118. svr.wait_until_ready();
  10119. Client cli("localhost", PORT);
  10120. // Verify that Get(path, params) works without requiring Headers argument
  10121. auto res = cli.Get("/search", httplib::Params{{"q", "cpp-httplib"}});
  10122. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10123. EXPECT_EQ(StatusCode::OK_200, res->status);
  10124. EXPECT_EQ("cpp-httplib", res->body);
  10125. }
  10126. TEST(ClientDefaultHeadersTest, DefaultHeaders_Online) {
  10127. auto host = "httpbingo.org";
  10128. auto path = std::string{"/range/32"};
  10129. #ifdef CPPHTTPLIB_SSL_ENABLED
  10130. SSLClient cli(host);
  10131. #else
  10132. Client cli(host);
  10133. #endif
  10134. cli.set_default_headers({make_range_header({{1, 10}})});
  10135. cli.set_connection_timeout(5);
  10136. {
  10137. auto res = cli.Get(path);
  10138. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10139. EXPECT_EQ("bcdefghijk", res->body);
  10140. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10141. }
  10142. {
  10143. auto res = cli.Get(path);
  10144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10145. EXPECT_EQ("bcdefghijk", res->body);
  10146. EXPECT_EQ(StatusCode::PartialContent_206, res->status);
  10147. }
  10148. }
  10149. TEST(ServerDefaultHeadersTest, DefaultHeaders) {
  10150. Server svr;
  10151. svr.set_default_headers({{"Hello", "World"}});
  10152. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  10153. res.set_content("ok", "text/plain");
  10154. });
  10155. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10156. auto se = detail::scope_exit([&] {
  10157. svr.stop();
  10158. listen_thread.join();
  10159. ASSERT_FALSE(svr.is_running());
  10160. });
  10161. svr.wait_until_ready();
  10162. Client cli("localhost", PORT);
  10163. auto res = cli.Get("/");
  10164. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10165. EXPECT_EQ(StatusCode::OK_200, res->status);
  10166. EXPECT_EQ("ok", res->body);
  10167. EXPECT_EQ("World", res->get_header_value("Hello"));
  10168. }
  10169. #ifdef CPPHTTPLIB_SSL_ENABLED
  10170. TEST(KeepAliveTest, ReadTimeoutSSL) {
  10171. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10172. ASSERT_TRUE(svr.is_valid());
  10173. svr.Get("/a", [&](const Request & /*req*/, Response &res) {
  10174. std::this_thread::sleep_for(std::chrono::seconds(2));
  10175. res.set_content("a", "text/plain");
  10176. });
  10177. svr.Get("/b", [&](const Request & /*req*/, Response &res) {
  10178. res.set_content("b", "text/plain");
  10179. });
  10180. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  10181. auto se = detail::scope_exit([&] {
  10182. svr.stop();
  10183. listen_thread.join();
  10184. ASSERT_FALSE(svr.is_running());
  10185. });
  10186. svr.wait_until_ready();
  10187. SSLClient cli("localhost", PORT);
  10188. cli.enable_server_certificate_verification(false);
  10189. cli.set_keep_alive(true);
  10190. cli.set_read_timeout(std::chrono::seconds(1));
  10191. auto resa = cli.Get("/a");
  10192. ASSERT_TRUE(!resa);
  10193. EXPECT_EQ(Error::Read, resa.error());
  10194. auto resb = cli.Get("/b");
  10195. ASSERT_TRUE(resb);
  10196. EXPECT_EQ(StatusCode::OK_200, resb->status);
  10197. EXPECT_EQ("b", resb->body);
  10198. }
  10199. // Closing an idle keep-alive connection sends close_notify and returns. The
  10200. // server must not wait for the client's close_notify: an idle client never
  10201. // sends one, so the worker would be held until the read timeout expires, and
  10202. // stop() would wait for it.
  10203. TEST(KeepAliveTest, SSLIdleCloseDoesNotWaitForPeer) {
  10204. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  10205. ASSERT_TRUE(svr.is_valid());
  10206. svr.set_keep_alive_timeout(1);
  10207. svr.set_read_timeout(10, 0);
  10208. svr.Get("/", [](const Request &, Response &res) {
  10209. res.set_content("ok", "text/plain");
  10210. });
  10211. auto port = svr.bind_to_any_port(HOST);
  10212. auto listen_thread = std::thread([&svr]() { svr.listen_after_bind(); });
  10213. auto se = detail::scope_exit([&] {
  10214. if (listen_thread.joinable()) {
  10215. svr.stop();
  10216. listen_thread.join();
  10217. }
  10218. });
  10219. svr.wait_until_ready();
  10220. SSLClient cli(HOST, port);
  10221. cli.enable_server_certificate_verification(false);
  10222. cli.set_keep_alive(true);
  10223. auto res = cli.Get("/");
  10224. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10225. EXPECT_EQ(StatusCode::OK_200, res->status);
  10226. // Stay idle past the keep-alive timeout so the server closes the connection.
  10227. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  10228. auto start = std::chrono::steady_clock::now();
  10229. svr.stop();
  10230. listen_thread.join();
  10231. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  10232. std::chrono::steady_clock::now() - start)
  10233. .count();
  10234. EXPECT_LT(elapsed, 3000);
  10235. }
  10236. #endif
  10237. class ServerTestWithAI_PASSIVE : public ::testing::Test {
  10238. protected:
  10239. ServerTestWithAI_PASSIVE()
  10240. : cli_(HOST, PORT)
  10241. #ifdef CPPHTTPLIB_SSL_ENABLED
  10242. ,
  10243. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10244. #endif
  10245. {
  10246. #ifdef CPPHTTPLIB_SSL_ENABLED
  10247. cli_.enable_server_certificate_verification(false);
  10248. #endif
  10249. }
  10250. virtual void SetUp() {
  10251. svr_.Get("/hi", [&](const Request & /*req*/, Response &res) {
  10252. res.set_content("Hello World!", "text/plain");
  10253. });
  10254. t_ = thread(
  10255. [&]() { ASSERT_TRUE(svr_.listen(std::string(), PORT, AI_PASSIVE)); });
  10256. svr_.wait_until_ready();
  10257. }
  10258. virtual void TearDown() {
  10259. svr_.stop();
  10260. t_.join();
  10261. }
  10262. #ifdef CPPHTTPLIB_SSL_ENABLED
  10263. SSLClient cli_;
  10264. SSLServer svr_;
  10265. #else
  10266. Client cli_;
  10267. Server svr_;
  10268. #endif
  10269. thread t_;
  10270. };
  10271. TEST_F(ServerTestWithAI_PASSIVE, GetMethod200) {
  10272. auto res = cli_.Get("/hi");
  10273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10274. EXPECT_EQ(StatusCode::OK_200, res->status);
  10275. EXPECT_EQ("text/plain", res->get_header_value("Content-Type"));
  10276. EXPECT_EQ("Hello World!", res->body);
  10277. }
  10278. class ServerUpDownTest : public ::testing::Test {
  10279. protected:
  10280. ServerUpDownTest() : cli_(HOST, PORT) {}
  10281. virtual void SetUp() {
  10282. t_ = thread([&]() {
  10283. svr_.bind_to_any_port(HOST);
  10284. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  10285. ASSERT_TRUE(svr_.listen_after_bind());
  10286. });
  10287. svr_.wait_until_ready();
  10288. }
  10289. virtual void TearDown() {
  10290. svr_.stop();
  10291. t_.join();
  10292. }
  10293. Client cli_;
  10294. Server svr_;
  10295. thread t_;
  10296. };
  10297. TEST_F(ServerUpDownTest, QuickStartStop) {
  10298. // Should not crash, especially when run with
  10299. // --gtest_filter=ServerUpDownTest.QuickStartStop --gtest_repeat=1000
  10300. }
  10301. class PayloadMaxLengthTest : public ::testing::Test {
  10302. protected:
  10303. PayloadMaxLengthTest()
  10304. : cli_(HOST, PORT)
  10305. #ifdef CPPHTTPLIB_SSL_ENABLED
  10306. ,
  10307. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10308. #endif
  10309. {
  10310. #ifdef CPPHTTPLIB_SSL_ENABLED
  10311. cli_.enable_server_certificate_verification(false);
  10312. #endif
  10313. }
  10314. virtual void SetUp() {
  10315. svr_.set_payload_max_length(8);
  10316. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10317. res.set_content("test", "text/plain");
  10318. });
  10319. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10320. svr_.wait_until_ready();
  10321. }
  10322. virtual void TearDown() {
  10323. svr_.stop();
  10324. t_.join();
  10325. }
  10326. #ifdef CPPHTTPLIB_SSL_ENABLED
  10327. SSLClient cli_;
  10328. SSLServer svr_;
  10329. #else
  10330. Client cli_;
  10331. Server svr_;
  10332. #endif
  10333. thread t_;
  10334. };
  10335. TEST_F(PayloadMaxLengthTest, ExceedLimit) {
  10336. auto res = cli_.Post("/test", "123456789", "text/plain");
  10337. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10338. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10339. res = cli_.Post("/test", "12345678", "text/plain");
  10340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10341. EXPECT_EQ(StatusCode::OK_200, res->status);
  10342. }
  10343. TEST_F(PayloadMaxLengthTest, ChunkedEncodingSecurityTest) {
  10344. // Test chunked encoding with payload exceeding the 8-byte limit
  10345. std::string large_chunked_data(16, 'A'); // 16 bytes, exceeds 8-byte limit
  10346. auto res = cli_.Post("/test", large_chunked_data, "text/plain");
  10347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10348. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10349. }
  10350. TEST_F(PayloadMaxLengthTest, ChunkedEncodingWithinLimit) {
  10351. // Test chunked encoding with payload within the 8-byte limit
  10352. std::string small_chunked_data(4, 'B'); // 4 bytes, within 8-byte limit
  10353. auto res = cli_.Post("/test", small_chunked_data, "text/plain");
  10354. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10355. EXPECT_EQ(StatusCode::OK_200, res->status);
  10356. }
  10357. TEST_F(PayloadMaxLengthTest, RawSocketChunkedTest) {
  10358. // Test using send_request to send chunked data exceeding payload limit
  10359. std::string chunked_request = "POST /test HTTP/1.1\r\n"
  10360. "Host: " +
  10361. std::string(HOST) + ":" + std::to_string(PORT) +
  10362. "\r\n"
  10363. "Transfer-Encoding: chunked\r\n"
  10364. "Connection: close\r\n"
  10365. "\r\n"
  10366. "a\r\n" // 10 bytes chunk (exceeds 8-byte limit)
  10367. "0123456789\r\n"
  10368. "0\r\n" // End chunk
  10369. "\r\n";
  10370. std::string response;
  10371. bool result = send_request(1, chunked_request, &response);
  10372. if (!result) {
  10373. // If send_request fails, it might be because the server closed the
  10374. // connection due to payload limit enforcement, which is acceptable
  10375. SUCCEED()
  10376. << "Server rejected oversized chunked request (connection closed)";
  10377. } else {
  10378. // If we got a response, check if it's an error response or connection was
  10379. // closed early Short response length indicates connection was closed due to
  10380. // payload limit
  10381. if (response.length() <= 10) {
  10382. SUCCEED() << "Server closed connection for oversized chunked request";
  10383. } else {
  10384. // Check for error status codes
  10385. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10386. response.find("Payload Too Large") != std::string::npos ||
  10387. response.find("400") != std::string::npos);
  10388. }
  10389. }
  10390. }
  10391. TEST_F(PayloadMaxLengthTest, NoContentLengthPayloadLimit) {
  10392. // Test request without Content-Length header exceeding payload limit
  10393. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10394. "Host: " +
  10395. std::string(HOST) + ":" +
  10396. std::to_string(PORT) +
  10397. "\r\n"
  10398. "Connection: close\r\n"
  10399. "\r\n";
  10400. // Add payload exceeding the 8-byte limit
  10401. std::string large_payload(16, 'X'); // 16 bytes, exceeds 8-byte limit
  10402. request_without_content_length += large_payload;
  10403. std::string response;
  10404. bool result = send_request(1, request_without_content_length, &response);
  10405. if (!result) {
  10406. // If send_request fails, server likely closed connection due to payload
  10407. // limit
  10408. SUCCEED() << "Server rejected oversized request without Content-Length "
  10409. "(connection closed)";
  10410. } else {
  10411. // Check if server responded with error or closed connection early
  10412. if (response.length() <= 10) {
  10413. SUCCEED() << "Server closed connection for oversized request without "
  10414. "Content-Length";
  10415. } else {
  10416. // Check for error status codes
  10417. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10418. response.find("Payload Too Large") != std::string::npos ||
  10419. response.find("400") != std::string::npos);
  10420. }
  10421. }
  10422. }
  10423. TEST_F(PayloadMaxLengthTest, NoContentLengthWithinLimit) {
  10424. // Test request without Content-Length header within payload limit
  10425. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10426. "Host: " +
  10427. std::string(HOST) + ":" +
  10428. std::to_string(PORT) +
  10429. "\r\n"
  10430. "Connection: close\r\n"
  10431. "\r\n";
  10432. // Add payload within the 8-byte limit
  10433. std::string small_payload(4, 'Y'); // 4 bytes, within 8-byte limit
  10434. request_without_content_length += small_payload;
  10435. std::string response;
  10436. bool result = send_request(1, request_without_content_length, &response);
  10437. // For requests without Content-Length, the server may have different behavior
  10438. // The key is that it should not reject due to payload limit for small
  10439. // payloads
  10440. if (result) {
  10441. // Check for any HTTP response (success or error, but not connection closed)
  10442. if (response.length() > 10) {
  10443. SUCCEED()
  10444. << "Server processed request without Content-Length within limit";
  10445. } else {
  10446. // Short response might indicate connection closed, which is acceptable
  10447. SUCCEED() << "Server closed connection for request without "
  10448. "Content-Length (acceptable behavior)";
  10449. }
  10450. } else {
  10451. // Connection failure might be due to protocol requirements
  10452. SUCCEED() << "Connection issue with request without Content-Length "
  10453. "(environment-specific)";
  10454. }
  10455. }
  10456. class LargePayloadMaxLengthTest : public ::testing::Test {
  10457. protected:
  10458. LargePayloadMaxLengthTest()
  10459. : cli_(HOST, PORT)
  10460. #ifdef CPPHTTPLIB_SSL_ENABLED
  10461. ,
  10462. svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE)
  10463. #endif
  10464. {
  10465. #ifdef CPPHTTPLIB_SSL_ENABLED
  10466. cli_.enable_server_certificate_verification(false);
  10467. #endif
  10468. }
  10469. virtual void SetUp() {
  10470. // Set 10MB payload limit
  10471. const size_t LARGE_PAYLOAD_LIMIT = 10 * 1024 * 1024; // 10MB
  10472. svr_.set_payload_max_length(LARGE_PAYLOAD_LIMIT);
  10473. svr_.Post("/test", [&](const Request & /*req*/, Response &res) {
  10474. res.set_content("Large payload test", "text/plain");
  10475. });
  10476. t_ = thread([&]() { ASSERT_TRUE(svr_.listen(HOST, PORT)); });
  10477. svr_.wait_until_ready();
  10478. }
  10479. virtual void TearDown() {
  10480. svr_.stop();
  10481. t_.join();
  10482. }
  10483. #ifdef CPPHTTPLIB_SSL_ENABLED
  10484. SSLClient cli_;
  10485. SSLServer svr_;
  10486. #else
  10487. Client cli_;
  10488. Server svr_;
  10489. #endif
  10490. thread t_;
  10491. };
  10492. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingWithin10MB) {
  10493. // Test chunked encoding with payload within 10MB limit
  10494. std::string medium_payload(5 * 1024 * 1024,
  10495. 'A'); // 5MB payload, within 10MB limit
  10496. auto res = cli_.Post("/test", medium_payload, "application/octet-stream");
  10497. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10498. EXPECT_EQ(StatusCode::OK_200, res->status);
  10499. }
  10500. TEST_F(LargePayloadMaxLengthTest, ChunkedEncodingExceeds10MB) {
  10501. // Test chunked encoding with payload exceeding 10MB limit
  10502. std::string large_payload(12 * 1024 * 1024,
  10503. 'B'); // 12MB payload, exceeds 10MB limit
  10504. auto res = cli_.Post("/test", large_payload, "application/octet-stream");
  10505. // Server may either return 413 or close the connection
  10506. if (res) {
  10507. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10508. } else {
  10509. SUCCEED() << "Server closed connection for payload exceeding 10MB limit";
  10510. }
  10511. }
  10512. TEST_F(LargePayloadMaxLengthTest, NoContentLengthWithin10MB) {
  10513. // Test request without Content-Length header within 10MB limit
  10514. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10515. "Host: " +
  10516. std::string(HOST) + ":" +
  10517. std::to_string(PORT) +
  10518. "\r\n"
  10519. "Connection: close\r\n"
  10520. "\r\n";
  10521. // Add 1MB payload (within 10MB limit)
  10522. std::string medium_payload(1024 * 1024, 'C'); // 1MB payload
  10523. request_without_content_length += medium_payload;
  10524. std::string response;
  10525. bool result = send_request(5, request_without_content_length, &response);
  10526. if (result) {
  10527. // Should get a proper HTTP response for payloads within limit
  10528. if (response.length() > 10) {
  10529. SUCCEED() << "Server processed 1MB request without Content-Length within "
  10530. "10MB limit";
  10531. } else {
  10532. SUCCEED() << "Server closed connection (acceptable behavior for no "
  10533. "Content-Length)";
  10534. }
  10535. } else {
  10536. SUCCEED() << "Connection issue with 1MB payload (environment-specific)";
  10537. }
  10538. }
  10539. TEST_F(LargePayloadMaxLengthTest, NoContentLengthExceeds10MB) {
  10540. // Test request without Content-Length header exceeding 10MB limit
  10541. std::string request_without_content_length = "POST /test HTTP/1.1\r\n"
  10542. "Host: " +
  10543. std::string(HOST) + ":" +
  10544. std::to_string(PORT) +
  10545. "\r\n"
  10546. "Connection: close\r\n"
  10547. "\r\n";
  10548. // Add 12MB payload (exceeds 10MB limit)
  10549. std::string large_payload(12 * 1024 * 1024, 'D'); // 12MB payload
  10550. request_without_content_length += large_payload;
  10551. std::string response;
  10552. bool result = send_request(10, request_without_content_length, &response);
  10553. if (!result) {
  10554. // Server should close connection due to payload limit
  10555. SUCCEED() << "Server rejected 12MB request without Content-Length "
  10556. "(connection closed)";
  10557. } else {
  10558. // Check for error response
  10559. if (response.length() <= 10) {
  10560. SUCCEED()
  10561. << "Server closed connection for 12MB request exceeding 10MB limit";
  10562. } else {
  10563. EXPECT_TRUE(response.find("413") != std::string::npos ||
  10564. response.find("Payload Too Large") != std::string::npos ||
  10565. response.find("400") != std::string::npos);
  10566. }
  10567. }
  10568. }
  10569. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10570. // `payload_max_length` is not enforced on decompressed body in ContentReader
  10571. // path.
  10572. TEST(PayloadLimitBypassTest, StreamingGzipDecompression) {
  10573. Server svr;
  10574. const size_t LIMIT = 64 * 1024; // 64KB
  10575. svr.set_payload_max_length(LIMIT);
  10576. size_t total = 0;
  10577. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10578. const ContentReader &content_reader) {
  10579. content_reader([&](const char * /*data*/, size_t len) {
  10580. total += len;
  10581. return true;
  10582. });
  10583. res.status = 200;
  10584. res.set_content("stream_ok", "text/plain");
  10585. });
  10586. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  10587. auto se = detail::scope_exit([&] {
  10588. svr.stop();
  10589. thread.join();
  10590. ASSERT_FALSE(svr.is_running());
  10591. });
  10592. svr.wait_until_ready();
  10593. // Prepare 256KB raw data and gzip-compress it
  10594. std::string raw(256 * 1024, 'A');
  10595. std::string gz;
  10596. {
  10597. z_stream zs{};
  10598. deflateInit2(&zs, Z_BEST_COMPRESSION, Z_DEFLATED, 15 + 16, 8,
  10599. Z_DEFAULT_STRATEGY);
  10600. zs.next_in = reinterpret_cast<Bytef *>(const_cast<char *>(raw.data()));
  10601. zs.avail_in = static_cast<uInt>(raw.size());
  10602. char outbuf[4096];
  10603. int ret;
  10604. do {
  10605. zs.next_out = reinterpret_cast<Bytef *>(outbuf);
  10606. zs.avail_out = sizeof(outbuf);
  10607. ret = deflate(&zs, Z_FINISH);
  10608. gz.append(outbuf, sizeof(outbuf) - zs.avail_out);
  10609. } while (ret != Z_STREAM_END);
  10610. deflateEnd(&zs);
  10611. }
  10612. Client cli(HOST, PORT);
  10613. cli.set_connection_timeout(std::chrono::seconds(5));
  10614. Headers headers = {{"Content-Encoding", "gzip"}};
  10615. auto res = cli.Post("/stream", headers, gz.data(), gz.size(),
  10616. "application/octet-stream");
  10617. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10618. // Server must reject oversized decompressed payloads with 413.
  10619. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  10620. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10621. EXPECT_LE(total, LIMIT);
  10622. }
  10623. #ifndef CPPHTTPLIB_SSL_ENABLED
  10624. // For a request with neither Content-Length nor Transfer-Encoding, the
  10625. // non-SSL raw-socket fallback in read_content_core() used to hand the
  10626. // compressed wire bytes straight to the ContentReader without ever routing
  10627. // them through the decompressor, so payload_max_length_ only bounded the
  10628. // compressed size on the wire, not the decompressed size.
  10629. TEST(PayloadLimitBypassTest, UnframedGzipDecompression) {
  10630. Server svr;
  10631. const size_t LIMIT = 64 * 1024; // 64KB
  10632. svr.set_payload_max_length(LIMIT);
  10633. size_t total = 0;
  10634. svr.Post("/stream", [&](const Request & /*req*/, Response &res,
  10635. const ContentReader &content_reader) {
  10636. content_reader([&](const char * /*data*/, size_t len) {
  10637. total += len;
  10638. return true;
  10639. });
  10640. res.status = 200;
  10641. res.set_content("stream_ok", "text/plain");
  10642. });
  10643. auto port = svr.bind_to_any_port(HOST);
  10644. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  10645. auto se = detail::scope_exit([&] {
  10646. svr.stop();
  10647. thread.join();
  10648. ASSERT_FALSE(svr.is_running());
  10649. });
  10650. svr.wait_until_ready();
  10651. // Prepare 256KB raw data and gzip-compress it, same payload as the
  10652. // StreamingGzipDecompression test above.
  10653. std::string raw(256 * 1024, 'A');
  10654. std::string gz;
  10655. {
  10656. httplib::detail::gzip_compressor compressor;
  10657. bool result = compressor.compress(raw.data(), raw.size(), /*last=*/true,
  10658. [&](const char *chunk, size_t len) {
  10659. gz.append(chunk, len);
  10660. return true;
  10661. });
  10662. ASSERT_TRUE(result);
  10663. }
  10664. // Send the gzip body over raw TCP with neither Content-Length nor
  10665. // Transfer-Encoding, and Connection: close so the server's stray-body scan
  10666. // kicks in.
  10667. std::string req = "POST /stream HTTP/1.1\r\n"
  10668. "Host: " +
  10669. std::string(HOST) + ":" + std::to_string(port) +
  10670. "\r\n"
  10671. "Content-Encoding: gzip\r\n"
  10672. "Connection: close\r\n"
  10673. "\r\n" +
  10674. gz;
  10675. std::string response;
  10676. ASSERT_TRUE(send_request(5, req, &response, port));
  10677. // Decompressed bytes delivered to the handler must not exceed LIMIT.
  10678. EXPECT_LE(total, LIMIT);
  10679. }
  10680. #endif
  10681. #endif
  10682. // Some servers misuse Content-Encoding to advertise a character set, e.g.
  10683. // `Content-Encoding: UTF-8` on a JPEG. Such a value is not a content coding, so
  10684. // the payload must be passed through untouched instead of being rejected.
  10685. TEST(ContentEncodingTest, UnknownEncodingIsPassedThrough) {
  10686. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10687. Server svr;
  10688. svr.Get("/image", [&](const Request & /*req*/, Response &res) {
  10689. res.set_content(body, "image/jpeg");
  10690. res.set_header("Content-Encoding", "UTF-8");
  10691. });
  10692. svr.Get("/identity", [&](const Request & /*req*/, Response &res) {
  10693. res.set_content(body, "image/jpeg");
  10694. res.set_header("Content-Encoding", "identity");
  10695. });
  10696. svr.Post("/echo", [](const Request &req, Response &res) {
  10697. res.set_content(req.body, "image/jpeg");
  10698. });
  10699. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10700. auto se = detail::scope_exit([&] {
  10701. svr.stop();
  10702. t.join();
  10703. ASSERT_FALSE(svr.is_running());
  10704. });
  10705. svr.wait_until_ready();
  10706. Client cli(HOST, PORT);
  10707. {
  10708. auto res = cli.Get("/image");
  10709. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10710. EXPECT_EQ(StatusCode::OK_200, res->status);
  10711. EXPECT_EQ(body, res->body);
  10712. }
  10713. {
  10714. auto res = cli.Get("/identity");
  10715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10716. EXPECT_EQ(StatusCode::OK_200, res->status);
  10717. EXPECT_EQ(body, res->body);
  10718. }
  10719. {
  10720. // The same applies to a request body reaching the server.
  10721. Headers headers = {{"Content-Encoding", "UTF-8"}};
  10722. auto res = cli.Post("/echo", headers, body, "image/jpeg");
  10723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10724. EXPECT_EQ(StatusCode::OK_200, res->status);
  10725. EXPECT_EQ(body, res->body);
  10726. }
  10727. }
  10728. // "Hello World!" as gzip. Hard-coded so that the test below can serve a
  10729. // gzip-encoded response even when the build has no zlib support.
  10730. static const char GZIPPED_HELLO_WORLD[] = {
  10731. '\x1f', '\x8b', '\x08', '\x00', '\x00', '\x00', '\x00', '\x00',
  10732. '\x02', '\x03', '\xf3', '\x48', '\xcd', '\xc9', '\xc9', '\x57',
  10733. '\x08', '\xcf', '\x2f', '\xca', '\x49', '\x51', '\x04', '\x00',
  10734. '\xa3', '\x1c', '\x29', '\x1c', '\x0c', '\x00', '\x00', '\x00'};
  10735. // A content coding is a whole token, not something the field value merely
  10736. // contains. Matching "br" and "zstd" as substrings made unrelated values such
  10737. // as "fibre" look like Brotli, and turned a multi-coding value like
  10738. // "gzip, br" into a Brotli-labeled body, so a decompressor was run over data
  10739. // it was never meant to see.
  10740. TEST(ContentEncodingTest, SubstringOfACodingIsNotTheCoding) {
  10741. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10742. Server svr;
  10743. svr.Get("/fibre", [&](const Request & /*req*/, Response &res) {
  10744. res.set_content(body, "image/jpeg");
  10745. res.set_header("Content-Encoding", "fibre");
  10746. });
  10747. svr.Get("/multi", [&](const Request & /*req*/, Response &res) {
  10748. res.set_content(body, "image/jpeg");
  10749. res.set_header("Content-Encoding", "gzip, br");
  10750. });
  10751. svr.Get("/zstdish", [&](const Request & /*req*/, Response &res) {
  10752. res.set_content(body, "image/jpeg");
  10753. res.set_header("Content-Encoding", "x-zstd-ish");
  10754. });
  10755. auto port = svr.bind_to_any_port(HOST);
  10756. thread t = thread([&]() { svr.listen_after_bind(); });
  10757. auto se = detail::scope_exit([&] {
  10758. svr.stop();
  10759. t.join();
  10760. ASSERT_FALSE(svr.is_running());
  10761. });
  10762. svr.wait_until_ready();
  10763. Client cli(HOST, port);
  10764. for (const char *path : {"/fibre", "/multi", "/zstdish"}) {
  10765. auto res = cli.Get(path);
  10766. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10767. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10768. // Not a coding we recognize, so the payload comes back untouched
  10769. EXPECT_EQ(body, res->body) << path;
  10770. }
  10771. }
  10772. // A content coding cpp-httplib recognizes but was not built with must be
  10773. // reported as such. Handing the still-compressed payload back to the caller
  10774. // would silently corrupt it.
  10775. TEST(ContentEncodingTest, KnownEncodingWithoutSupportIsReported) {
  10776. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10777. Server svr;
  10778. // "image/jpeg" keeps the server from applying a content coding of its own,
  10779. // so the hand-crafted Content-Encoding below survives.
  10780. svr.Get("/gzipped", [&](const Request & /*req*/, Response &res) {
  10781. res.set_content(gzipped, "image/jpeg");
  10782. res.set_header("Content-Encoding", "gzip");
  10783. });
  10784. // Content codings are case-insensitive (RFC 9110 8.4.1).
  10785. svr.Get("/gzipped-uppercase", [&](const Request & /*req*/, Response &res) {
  10786. res.set_content(gzipped, "image/jpeg");
  10787. res.set_header("Content-Encoding", "GZIP");
  10788. });
  10789. thread t = thread([&]() { svr.listen(HOST, PORT); });
  10790. auto se = detail::scope_exit([&] {
  10791. svr.stop();
  10792. t.join();
  10793. ASSERT_FALSE(svr.is_running());
  10794. });
  10795. svr.wait_until_ready();
  10796. Client cli(HOST, PORT);
  10797. {
  10798. auto res = cli.Get("/gzipped");
  10799. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10800. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10801. EXPECT_EQ("Hello World!", res->body);
  10802. #else
  10803. ASSERT_FALSE(res);
  10804. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10805. #endif
  10806. }
  10807. {
  10808. // open_stream() must behave the same way.
  10809. auto handle = cli.open_stream("GET", "/gzipped");
  10810. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10811. ASSERT_TRUE(handle.is_valid());
  10812. std::string received;
  10813. char buf[256];
  10814. ssize_t n;
  10815. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  10816. received.append(buf, static_cast<size_t>(n));
  10817. }
  10818. EXPECT_EQ("Hello World!", received);
  10819. #else
  10820. EXPECT_FALSE(handle.is_valid());
  10821. EXPECT_EQ(Error::UnsupportedContentEncoding, handle.error);
  10822. #endif
  10823. }
  10824. {
  10825. // A differently-cased coding must not be mistaken for an unknown one, or
  10826. // the body would be handed back still compressed.
  10827. auto res = cli.Get("/gzipped-uppercase");
  10828. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10829. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10830. EXPECT_EQ("Hello World!", res->body);
  10831. #else
  10832. ASSERT_FALSE(res);
  10833. EXPECT_EQ(Error::UnsupportedContentEncoding, res.error());
  10834. #endif
  10835. }
  10836. }
  10837. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  10838. // A handler serving pre-compressed content (e.g. build-time gzipped static
  10839. // assets) sets Content-Encoding itself. The server used to pick a coding from
  10840. // Accept-Encoding and the content type alone, gzipping the already-gzipped
  10841. // body a second time and appending a second Content-Encoding field line, so
  10842. // clients that decode one coding per listed value handed back raw gzip bytes.
  10843. TEST(ContentEncodingTest, PreEncodedResponseIsNotCompressedAgain) {
  10844. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10845. Server svr;
  10846. // text/plain is a compressible type, so only the pre-set Content-Encoding
  10847. // keeps the server from applying a coding of its own.
  10848. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10849. res.set_content(gzipped, "text/plain");
  10850. res.set_header("Content-Encoding", "gzip");
  10851. });
  10852. auto port = svr.bind_to_any_port(HOST);
  10853. thread t = thread([&]() { svr.listen_after_bind(); });
  10854. auto se = detail::scope_exit([&] {
  10855. svr.stop();
  10856. t.join();
  10857. ASSERT_FALSE(svr.is_running());
  10858. });
  10859. svr.wait_until_ready();
  10860. Client cli(HOST, port);
  10861. Headers headers = {{"Accept-Encoding", "gzip"}};
  10862. auto res = cli.Get("/pre-gzipped", headers);
  10863. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10864. EXPECT_EQ(StatusCode::OK_200, res->status);
  10865. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10866. EXPECT_EQ("Hello World!", res->body);
  10867. }
  10868. // A chunked provider settles its coding where the headers are written and
  10869. // reuses it at write time. Both ends of that have to hold: a handler's own
  10870. // Content-Encoding suppresses the coding, and a response without one is still
  10871. // compressed as it always was.
  10872. TEST(ContentEncodingTest, PreEncodedChunkedResponseIsNotCompressedAgain) {
  10873. const std::string gzipped(GZIPPED_HELLO_WORLD, sizeof(GZIPPED_HELLO_WORLD));
  10874. const std::string plain = "Hello World! Hello World! Hello World!";
  10875. Server svr;
  10876. svr.Get("/pre-gzipped", [&](const Request & /*req*/, Response &res) {
  10877. res.set_header("Content-Encoding", "gzip");
  10878. res.set_chunked_content_provider(
  10879. "text/plain", [gzipped](size_t /*offset*/, DataSink &sink) {
  10880. sink.write(gzipped.data(), gzipped.size());
  10881. sink.done();
  10882. return true;
  10883. });
  10884. });
  10885. svr.Get("/negotiated", [&](const Request & /*req*/, Response &res) {
  10886. res.set_chunked_content_provider(
  10887. "text/plain", [plain](size_t /*offset*/, DataSink &sink) {
  10888. sink.write(plain.data(), plain.size());
  10889. sink.done();
  10890. return true;
  10891. });
  10892. });
  10893. auto port = svr.bind_to_any_port(HOST);
  10894. thread t = thread([&]() { svr.listen_after_bind(); });
  10895. auto se = detail::scope_exit([&] {
  10896. svr.stop();
  10897. t.join();
  10898. ASSERT_FALSE(svr.is_running());
  10899. });
  10900. svr.wait_until_ready();
  10901. Client cli(HOST, port);
  10902. Headers headers = {{"Accept-Encoding", "gzip"}};
  10903. {
  10904. auto res = cli.Get("/pre-gzipped", headers);
  10905. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10906. EXPECT_EQ(StatusCode::OK_200, res->status);
  10907. EXPECT_EQ(1U, res->get_header_value_count("Content-Encoding"));
  10908. EXPECT_EQ("Hello World!", res->body);
  10909. }
  10910. {
  10911. auto res = cli.Get("/negotiated", headers);
  10912. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  10913. EXPECT_EQ(StatusCode::OK_200, res->status);
  10914. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  10915. EXPECT_EQ(plain, res->body);
  10916. }
  10917. }
  10918. #endif
  10919. // RFC 9110 Section 5.3: a Content-Encoding split over several field lines is
  10920. // the same message as the comma-joined one, so both have to be read the same
  10921. // way. Reading only the first line made "gzip" followed by "gzip" look like a
  10922. // single gzip coding, and a body the sender says was encoded twice was handed
  10923. // back after one pass, still compressed but presented as decoded.
  10924. TEST(ContentEncodingTest, DuplicateFieldLinesAreTheSameAsTheJoinedValue) {
  10925. const std::string body = "\xff\xd8\xff\xe0 not really a jpeg";
  10926. Server svr;
  10927. svr.Get("/split", [&](const Request & /*req*/, Response &res) {
  10928. res.set_content(body, "image/jpeg");
  10929. res.headers.emplace("Content-Encoding", "gzip");
  10930. res.headers.emplace("Content-Encoding", "gzip");
  10931. });
  10932. svr.Get("/joined", [&](const Request & /*req*/, Response &res) {
  10933. res.set_content(body, "image/jpeg");
  10934. res.set_header("Content-Encoding", "gzip, gzip");
  10935. });
  10936. auto port = svr.bind_to_any_port(HOST);
  10937. thread t = thread([&]() { svr.listen_after_bind(); });
  10938. auto se = detail::scope_exit([&] {
  10939. svr.stop();
  10940. t.join();
  10941. ASSERT_FALSE(svr.is_running());
  10942. });
  10943. svr.wait_until_ready();
  10944. Client cli(HOST, port);
  10945. // Two codings is not something cpp-httplib decodes, so both representations
  10946. // take the pass-through path rather than one of them being gunzipped once.
  10947. for (const char *path : {"/split", "/joined"}) {
  10948. auto res = cli.Get(path);
  10949. ASSERT_TRUE(res) << path << " -> " << to_string(res.error());
  10950. EXPECT_EQ(StatusCode::OK_200, res->status) << path;
  10951. EXPECT_EQ(body, res->body) << path;
  10952. }
  10953. }
  10954. // Regression test for DoS vulnerability: a malicious server sending a response
  10955. // without Content-Length header must not cause unbounded memory consumption on
  10956. // the client side. The client should stop reading after a reasonable limit,
  10957. // similar to the server-side set_payload_max_length protection.
  10958. TEST(ClientVulnerabilityTest, UnboundedReadWithoutContentLength) {
  10959. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  10960. #ifndef _WIN32
  10961. signal(SIGPIPE, SIG_IGN);
  10962. #endif
  10963. auto server_thread = std::thread([] {
  10964. constexpr size_t MALICIOUS_DATA_SIZE = 10 * 1024 * 1024; // 10MB from server
  10965. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  10966. default_socket_options(srv);
  10967. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  10968. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  10969. sockaddr_in addr{};
  10970. addr.sin_family = AF_INET;
  10971. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  10972. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  10973. int opt = 1;
  10974. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  10975. #ifdef _WIN32
  10976. reinterpret_cast<const char *>(&opt),
  10977. #else
  10978. &opt,
  10979. #endif
  10980. sizeof(opt));
  10981. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  10982. ::listen(srv, 1);
  10983. sockaddr_in cli_addr{};
  10984. socklen_t cli_len = sizeof(cli_addr);
  10985. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  10986. if (cli != INVALID_SOCKET) {
  10987. char buf[4096];
  10988. ::recv(cli, buf, sizeof(buf), 0);
  10989. // Malicious response: no Content-Length, no chunked encoding
  10990. std::string response_header = "HTTP/1.1 200 OK\r\n"
  10991. "Connection: close\r\n"
  10992. "\r\n";
  10993. ::send(cli,
  10994. #ifdef _WIN32
  10995. static_cast<const char *>(response_header.c_str()),
  10996. static_cast<int>(response_header.size()),
  10997. #else
  10998. response_header.c_str(), response_header.size(),
  10999. #endif
  11000. 0);
  11001. // Send 10MB of data
  11002. std::string chunk(64 * 1024, 'A');
  11003. size_t total_sent = 0;
  11004. while (total_sent < MALICIOUS_DATA_SIZE) {
  11005. auto to_send = std::min(chunk.size(), MALICIOUS_DATA_SIZE - total_sent);
  11006. auto sent = ::send(cli,
  11007. #ifdef _WIN32
  11008. static_cast<const char *>(chunk.c_str()),
  11009. static_cast<int>(to_send),
  11010. #else
  11011. chunk.c_str(), to_send,
  11012. #endif
  11013. 0);
  11014. if (sent <= 0) break;
  11015. total_sent += static_cast<size_t>(sent);
  11016. }
  11017. detail::close_socket(cli);
  11018. }
  11019. detail::close_socket(srv);
  11020. });
  11021. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11022. size_t total_read = 0;
  11023. {
  11024. Client cli("127.0.0.1", PORT + 2);
  11025. cli.set_read_timeout(5, 0);
  11026. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11027. auto stream = cli.open_stream("GET", "/malicious");
  11028. ASSERT_TRUE(stream.is_valid());
  11029. char buffer[64 * 1024];
  11030. ssize_t n;
  11031. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11032. total_read += static_cast<size_t>(n);
  11033. }
  11034. } // StreamHandle and Client destroyed here, closing the socket
  11035. server_thread.join();
  11036. // With set_payload_max_length, the client must stop reading before consuming
  11037. // all 10MB. The read loop should be cut off at or near the configured limit.
  11038. EXPECT_LE(total_read, CLIENT_READ_LIMIT)
  11039. << "Client read " << total_read << " bytes, exceeding the configured "
  11040. << "payload_max_length of " << CLIENT_READ_LIMIT << " bytes.";
  11041. }
  11042. // Verify that set_payload_max_length(0) means "no limit" and allows reading
  11043. // the entire response body without truncation.
  11044. TEST(ClientVulnerabilityTest, PayloadMaxLengthZeroMeansNoLimit) {
  11045. static constexpr size_t DATA_SIZE = 4 * 1024 * 1024; // 4MB from server
  11046. #ifndef _WIN32
  11047. signal(SIGPIPE, SIG_IGN);
  11048. #endif
  11049. auto server_thread = std::thread([] {
  11050. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11051. default_socket_options(srv);
  11052. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11053. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11054. sockaddr_in addr{};
  11055. addr.sin_family = AF_INET;
  11056. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11057. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11058. int opt = 1;
  11059. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11060. #ifdef _WIN32
  11061. reinterpret_cast<const char *>(&opt),
  11062. #else
  11063. &opt,
  11064. #endif
  11065. sizeof(opt));
  11066. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11067. ::listen(srv, 1);
  11068. sockaddr_in cli_addr{};
  11069. socklen_t cli_len = sizeof(cli_addr);
  11070. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11071. if (cli != INVALID_SOCKET) {
  11072. char buf[4096];
  11073. ::recv(cli, buf, sizeof(buf), 0);
  11074. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11075. "Connection: close\r\n"
  11076. "\r\n";
  11077. ::send(cli,
  11078. #ifdef _WIN32
  11079. static_cast<const char *>(response_header.c_str()),
  11080. static_cast<int>(response_header.size()),
  11081. #else
  11082. response_header.c_str(), response_header.size(),
  11083. #endif
  11084. 0);
  11085. std::string chunk(64 * 1024, 'A');
  11086. size_t total_sent = 0;
  11087. while (total_sent < DATA_SIZE) {
  11088. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11089. auto sent = ::send(cli,
  11090. #ifdef _WIN32
  11091. static_cast<const char *>(chunk.c_str()),
  11092. static_cast<int>(to_send),
  11093. #else
  11094. chunk.c_str(), to_send,
  11095. #endif
  11096. 0);
  11097. if (sent <= 0) break;
  11098. total_sent += static_cast<size_t>(sent);
  11099. }
  11100. #ifdef _WIN32
  11101. ::shutdown(cli, SD_SEND);
  11102. #else
  11103. ::shutdown(cli, SHUT_WR);
  11104. #endif
  11105. // Drain until the client closes its end, ensuring all data is delivered
  11106. char drain[1024];
  11107. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11108. detail::close_socket(cli);
  11109. }
  11110. detail::close_socket(srv);
  11111. });
  11112. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11113. size_t total_read = 0;
  11114. {
  11115. Client cli("127.0.0.1", PORT + 2);
  11116. cli.set_read_timeout(5, 0);
  11117. cli.set_payload_max_length(0); // 0 means no limit
  11118. auto stream = cli.open_stream("GET", "/data");
  11119. ASSERT_TRUE(stream.is_valid());
  11120. char buffer[64 * 1024];
  11121. ssize_t n;
  11122. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11123. total_read += static_cast<size_t>(n);
  11124. }
  11125. }
  11126. server_thread.join();
  11127. EXPECT_EQ(total_read, DATA_SIZE)
  11128. << "With payload_max_length(0), the client should read all " << DATA_SIZE
  11129. << " bytes without truncation, but only read " << total_read << " bytes.";
  11130. }
  11131. // Regression test for OSS-Fuzz issue 508342856: a malicious server sending an
  11132. // enormous Content-Length must not cause the client to pre-allocate a huge
  11133. // response body buffer. The reservation is capped at payload_max_length_, and
  11134. // the read itself fails when the body exceeds the limit.
  11135. TEST(ClientVulnerabilityTest, HugeContentLengthDoesNotPreallocate) {
  11136. #ifndef _WIN32
  11137. signal(SIGPIPE, SIG_IGN);
  11138. #endif
  11139. auto server_thread = std::thread([] {
  11140. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11141. default_socket_options(srv);
  11142. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11143. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11144. sockaddr_in addr{};
  11145. addr.sin_family = AF_INET;
  11146. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11147. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11148. int opt = 1;
  11149. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11150. #ifdef _WIN32
  11151. reinterpret_cast<const char *>(&opt),
  11152. #else
  11153. &opt,
  11154. #endif
  11155. sizeof(opt));
  11156. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11157. ::listen(srv, 1);
  11158. sockaddr_in cli_addr{};
  11159. socklen_t cli_len = sizeof(cli_addr);
  11160. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11161. if (cli != INVALID_SOCKET) {
  11162. char buf[4096];
  11163. ::recv(cli, buf, sizeof(buf), 0);
  11164. // Malicious response: claim a 20GB body but send only a tiny payload.
  11165. std::string response = "HTTP/1.1 200 OK\r\n"
  11166. "Content-Length: 20000000000\r\n"
  11167. "\r\n"
  11168. "abc";
  11169. ::send(cli,
  11170. #ifdef _WIN32
  11171. static_cast<const char *>(response.c_str()),
  11172. static_cast<int>(response.size()),
  11173. #else
  11174. response.c_str(), response.size(),
  11175. #endif
  11176. 0);
  11177. detail::close_socket(cli);
  11178. }
  11179. detail::close_socket(srv);
  11180. });
  11181. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11182. {
  11183. Client cli("127.0.0.1", PORT + 2);
  11184. cli.set_read_timeout(5, 0);
  11185. // Default payload_max_length_ is 100MB; a 20GB Content-Length must not
  11186. // result in a 20GB pre-allocation. The Get() call is expected to fail
  11187. // (server claims more bytes than payload_max_length permits), but it must
  11188. // not exhaust memory before getting there.
  11189. auto res = cli.Get("/malicious");
  11190. EXPECT_FALSE(res); // Read fails because body exceeds payload_max_length_
  11191. }
  11192. server_thread.join();
  11193. }
  11194. // Verify that content_receiver bypasses the default payload_max_length,
  11195. // allowing streaming downloads larger than 100MB without requiring an explicit
  11196. // set_payload_max_length call.
  11197. TEST(ClientVulnerabilityTest, ContentReceiverBypassesDefaultPayloadMaxLength) {
  11198. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11199. #ifndef _WIN32
  11200. signal(SIGPIPE, SIG_IGN);
  11201. #endif
  11202. auto server_thread = std::thread([] {
  11203. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11204. default_socket_options(srv);
  11205. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11206. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11207. sockaddr_in addr{};
  11208. addr.sin_family = AF_INET;
  11209. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11210. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11211. int opt = 1;
  11212. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11213. #ifdef _WIN32
  11214. reinterpret_cast<const char *>(&opt),
  11215. #else
  11216. &opt,
  11217. #endif
  11218. sizeof(opt));
  11219. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11220. ::listen(srv, 1);
  11221. sockaddr_in cli_addr{};
  11222. socklen_t cli_len = sizeof(cli_addr);
  11223. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11224. if (cli != INVALID_SOCKET) {
  11225. char buf[4096];
  11226. ::recv(cli, buf, sizeof(buf), 0);
  11227. // Response with Content-Length larger than default 100MB limit
  11228. auto content_length = std::to_string(DATA_SIZE);
  11229. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11230. "Content-Length: " +
  11231. content_length +
  11232. "\r\n"
  11233. "Connection: close\r\n"
  11234. "\r\n";
  11235. ::send(cli,
  11236. #ifdef _WIN32
  11237. static_cast<const char *>(response_header.c_str()),
  11238. static_cast<int>(response_header.size()),
  11239. #else
  11240. response_header.c_str(), response_header.size(),
  11241. #endif
  11242. 0);
  11243. std::string chunk(64 * 1024, 'A');
  11244. size_t total_sent = 0;
  11245. while (total_sent < DATA_SIZE) {
  11246. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11247. auto sent = ::send(cli,
  11248. #ifdef _WIN32
  11249. static_cast<const char *>(chunk.c_str()),
  11250. static_cast<int>(to_send),
  11251. #else
  11252. chunk.c_str(), to_send,
  11253. #endif
  11254. 0);
  11255. if (sent <= 0) break;
  11256. total_sent += static_cast<size_t>(sent);
  11257. }
  11258. detail::close_socket(cli);
  11259. }
  11260. detail::close_socket(srv);
  11261. });
  11262. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11263. size_t total_received = 0;
  11264. {
  11265. Client cli("127.0.0.1", PORT + 2);
  11266. cli.set_read_timeout(10, 0);
  11267. // Do NOT call set_payload_max_length — use the default 100MB limit
  11268. auto res =
  11269. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11270. total_received += data_length;
  11271. return true;
  11272. });
  11273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11274. EXPECT_EQ(StatusCode::OK_200, res->status);
  11275. }
  11276. server_thread.join();
  11277. EXPECT_EQ(total_received, DATA_SIZE)
  11278. << "With content_receiver, the client should read all " << DATA_SIZE
  11279. << " bytes despite the default 100MB payload_max_length, but only read "
  11280. << total_received << " bytes.";
  11281. }
  11282. // Verify that an explicit set_payload_max_length smaller than the response is
  11283. // enforced even when a content_receiver is used.
  11284. TEST(ClientVulnerabilityTest,
  11285. ContentReceiverRespectsExplicitPayloadMaxLength150MB) {
  11286. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11287. static constexpr size_t EXPLICIT_LIMIT = 150 * 1024 * 1024; // 150MB limit
  11288. #ifndef _WIN32
  11289. signal(SIGPIPE, SIG_IGN);
  11290. #endif
  11291. auto server_thread = std::thread([] {
  11292. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11293. default_socket_options(srv);
  11294. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11295. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11296. sockaddr_in addr{};
  11297. addr.sin_family = AF_INET;
  11298. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11299. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11300. int opt = 1;
  11301. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11302. #ifdef _WIN32
  11303. reinterpret_cast<const char *>(&opt),
  11304. #else
  11305. &opt,
  11306. #endif
  11307. sizeof(opt));
  11308. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11309. ::listen(srv, 1);
  11310. sockaddr_in cli_addr{};
  11311. socklen_t cli_len = sizeof(cli_addr);
  11312. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11313. if (cli != INVALID_SOCKET) {
  11314. char buf[4096];
  11315. ::recv(cli, buf, sizeof(buf), 0);
  11316. auto content_length = std::to_string(DATA_SIZE);
  11317. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11318. "Content-Length: " +
  11319. content_length +
  11320. "\r\n"
  11321. "Connection: close\r\n"
  11322. "\r\n";
  11323. ::send(cli,
  11324. #ifdef _WIN32
  11325. static_cast<const char *>(response_header.c_str()),
  11326. static_cast<int>(response_header.size()),
  11327. #else
  11328. response_header.c_str(), response_header.size(),
  11329. #endif
  11330. 0);
  11331. std::string chunk(64 * 1024, 'A');
  11332. size_t total_sent = 0;
  11333. while (total_sent < DATA_SIZE) {
  11334. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11335. auto sent = ::send(cli,
  11336. #ifdef _WIN32
  11337. static_cast<const char *>(chunk.c_str()),
  11338. static_cast<int>(to_send),
  11339. #else
  11340. chunk.c_str(), to_send,
  11341. #endif
  11342. 0);
  11343. if (sent <= 0) break;
  11344. total_sent += static_cast<size_t>(sent);
  11345. }
  11346. detail::close_socket(cli);
  11347. }
  11348. detail::close_socket(srv);
  11349. });
  11350. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11351. size_t total_received = 0;
  11352. {
  11353. Client cli("127.0.0.1", PORT + 2);
  11354. cli.set_read_timeout(10, 0);
  11355. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 150MB limit
  11356. auto res =
  11357. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11358. total_received += data_length;
  11359. return true;
  11360. });
  11361. // Should fail because 200MB exceeds the explicit 150MB limit
  11362. EXPECT_FALSE(res);
  11363. }
  11364. server_thread.join();
  11365. EXPECT_LE(total_received, EXPLICIT_LIMIT)
  11366. << "Client with content_receiver should respect the explicit "
  11367. << "payload_max_length of " << EXPLICIT_LIMIT << " bytes, but read "
  11368. << total_received << " bytes.";
  11369. }
  11370. // Verify that an explicit set_payload_max_length larger than the response
  11371. // allows the content_receiver to read all data successfully.
  11372. TEST(ClientVulnerabilityTest,
  11373. ContentReceiverRespectsExplicitPayloadMaxLength250MB) {
  11374. static constexpr size_t DATA_SIZE = 200 * 1024 * 1024; // 200MB from server
  11375. static constexpr size_t EXPLICIT_LIMIT = 250 * 1024 * 1024; // 250MB limit
  11376. #ifndef _WIN32
  11377. signal(SIGPIPE, SIG_IGN);
  11378. #endif
  11379. auto server_thread = std::thread([] {
  11380. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11381. default_socket_options(srv);
  11382. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11383. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11384. sockaddr_in addr{};
  11385. addr.sin_family = AF_INET;
  11386. addr.sin_port = htons(static_cast<uint16_t>(PORT + 2));
  11387. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11388. int opt = 1;
  11389. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11390. #ifdef _WIN32
  11391. reinterpret_cast<const char *>(&opt),
  11392. #else
  11393. &opt,
  11394. #endif
  11395. sizeof(opt));
  11396. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  11397. ::listen(srv, 1);
  11398. sockaddr_in cli_addr{};
  11399. socklen_t cli_len = sizeof(cli_addr);
  11400. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11401. if (cli != INVALID_SOCKET) {
  11402. char buf[4096];
  11403. ::recv(cli, buf, sizeof(buf), 0);
  11404. auto content_length = std::to_string(DATA_SIZE);
  11405. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11406. "Content-Length: " +
  11407. content_length +
  11408. "\r\n"
  11409. "Connection: close\r\n"
  11410. "\r\n";
  11411. ::send(cli,
  11412. #ifdef _WIN32
  11413. static_cast<const char *>(response_header.c_str()),
  11414. static_cast<int>(response_header.size()),
  11415. #else
  11416. response_header.c_str(), response_header.size(),
  11417. #endif
  11418. 0);
  11419. std::string chunk(64 * 1024, 'A');
  11420. size_t total_sent = 0;
  11421. while (total_sent < DATA_SIZE) {
  11422. auto to_send = std::min(chunk.size(), DATA_SIZE - total_sent);
  11423. auto sent = ::send(cli,
  11424. #ifdef _WIN32
  11425. static_cast<const char *>(chunk.c_str()),
  11426. static_cast<int>(to_send),
  11427. #else
  11428. chunk.c_str(), to_send,
  11429. #endif
  11430. 0);
  11431. if (sent <= 0) break;
  11432. total_sent += static_cast<size_t>(sent);
  11433. }
  11434. #ifdef _WIN32
  11435. ::shutdown(cli, SD_SEND);
  11436. #else
  11437. ::shutdown(cli, SHUT_WR);
  11438. #endif
  11439. char drain[1024];
  11440. while (::recv(cli, drain, sizeof(drain), 0) > 0) {}
  11441. detail::close_socket(cli);
  11442. }
  11443. detail::close_socket(srv);
  11444. });
  11445. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  11446. size_t total_received = 0;
  11447. {
  11448. Client cli("127.0.0.1", PORT + 2);
  11449. cli.set_read_timeout(10, 0);
  11450. cli.set_payload_max_length(EXPLICIT_LIMIT); // Explicit 250MB limit
  11451. auto res =
  11452. cli.Get("/large", [&](const char * /*data*/, size_t data_length) {
  11453. total_received += data_length;
  11454. return true;
  11455. });
  11456. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11457. EXPECT_EQ(StatusCode::OK_200, res->status);
  11458. }
  11459. server_thread.join();
  11460. EXPECT_EQ(total_received, DATA_SIZE)
  11461. << "With explicit payload_max_length of " << EXPLICIT_LIMIT
  11462. << " bytes (larger than " << DATA_SIZE
  11463. << " bytes response), content_receiver should read all data, but only "
  11464. "read "
  11465. << total_received << " bytes.";
  11466. }
  11467. #if defined(CPPHTTPLIB_ZLIB_SUPPORT) && !defined(_WIN32)
  11468. // Regression test for "zip bomb" attack on the client side: a malicious server
  11469. // sends a small gzip-compressed response that decompresses to a huge payload.
  11470. // The client must enforce payload_max_length on the decompressed size.
  11471. TEST(ClientVulnerabilityTest, ZipBombWithoutContentLength) {
  11472. constexpr size_t DECOMPRESSED_SIZE =
  11473. 10 * 1024 * 1024; // 10MB after decompression
  11474. constexpr size_t CLIENT_READ_LIMIT = 2 * 1024 * 1024; // 2MB safety limit
  11475. // Prepare gzip-compressed data: 10MB of zeros compresses to a few KB
  11476. std::string uncompressed(DECOMPRESSED_SIZE, '\0');
  11477. std::string compressed;
  11478. {
  11479. httplib::detail::gzip_compressor compressor;
  11480. bool ok =
  11481. compressor.compress(uncompressed.data(), uncompressed.size(),
  11482. /*last=*/true, [&](const char *buf, size_t len) {
  11483. compressed.append(buf, len);
  11484. return true;
  11485. });
  11486. ASSERT_TRUE(ok);
  11487. }
  11488. // Sanity: compressed data should be much smaller than the decompressed size
  11489. ASSERT_LT(compressed.size(), DECOMPRESSED_SIZE / 10);
  11490. #ifndef _WIN32
  11491. signal(SIGPIPE, SIG_IGN);
  11492. #endif
  11493. // Set up the listening socket in the main thread so the server is guaranteed
  11494. // to be ready before the client connects (eliminates race condition).
  11495. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  11496. default_socket_options(srv);
  11497. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  11498. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  11499. sockaddr_in addr{};
  11500. addr.sin_family = AF_INET;
  11501. addr.sin_port = htons(static_cast<uint16_t>(PORT + 3));
  11502. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  11503. int opt = 1;
  11504. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  11505. #ifdef _WIN32
  11506. reinterpret_cast<const char *>(&opt),
  11507. #else
  11508. &opt,
  11509. #endif
  11510. sizeof(opt));
  11511. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  11512. ASSERT_EQ(0, ::listen(srv, 1));
  11513. auto server_thread = std::thread([&compressed, srv] {
  11514. sockaddr_in cli_addr{};
  11515. socklen_t cli_len = sizeof(cli_addr);
  11516. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  11517. if (cli != INVALID_SOCKET) {
  11518. // Read the full HTTP request (until \r\n\r\n)
  11519. char buf[4096];
  11520. size_t total = 0;
  11521. while (total < sizeof(buf)) {
  11522. auto n = ::recv(cli, buf + total, sizeof(buf) - total, 0);
  11523. if (n <= 0) break;
  11524. total += static_cast<size_t>(n);
  11525. // Check for end of headers
  11526. if (total >= 4) {
  11527. std::string req(buf, total);
  11528. if (req.find("\r\n\r\n") != std::string::npos) break;
  11529. }
  11530. }
  11531. // Malicious response: gzip-compressed body, no Content-Length
  11532. std::string response_header = "HTTP/1.1 200 OK\r\n"
  11533. "Content-Encoding: gzip\r\n"
  11534. "Connection: close\r\n"
  11535. "\r\n";
  11536. ::send(cli,
  11537. #ifdef _WIN32
  11538. static_cast<const char *>(response_header.c_str()),
  11539. static_cast<int>(response_header.size()),
  11540. #else
  11541. response_header.c_str(), response_header.size(),
  11542. #endif
  11543. 0);
  11544. // Send the compressed payload (small on the wire, huge when decompressed)
  11545. size_t total_sent = 0;
  11546. while (total_sent < compressed.size()) {
  11547. auto to_send = std::min(compressed.size() - total_sent,
  11548. static_cast<size_t>(64 * 1024));
  11549. auto sent =
  11550. ::send(cli,
  11551. #ifdef _WIN32
  11552. static_cast<const char *>(compressed.c_str() + total_sent),
  11553. static_cast<int>(to_send),
  11554. #else
  11555. compressed.c_str() + total_sent, to_send,
  11556. #endif
  11557. 0);
  11558. if (sent <= 0) break;
  11559. total_sent += static_cast<size_t>(sent);
  11560. }
  11561. detail::close_socket(cli);
  11562. }
  11563. });
  11564. auto se = detail::scope_exit([&] {
  11565. detail::close_socket(srv);
  11566. server_thread.join();
  11567. });
  11568. size_t total_decompressed = 0;
  11569. {
  11570. Client cli("127.0.0.1", PORT + 3);
  11571. cli.set_read_timeout(5, 0);
  11572. cli.set_decompress(true);
  11573. cli.set_payload_max_length(CLIENT_READ_LIMIT);
  11574. auto stream = cli.open_stream("GET", "/zipbomb");
  11575. ASSERT_TRUE(stream.is_valid());
  11576. char buffer[64 * 1024];
  11577. ssize_t n;
  11578. while ((n = stream.read(buffer, sizeof(buffer))) > 0) {
  11579. total_decompressed += static_cast<size_t>(n);
  11580. }
  11581. }
  11582. // The decompressed size must be capped by payload_max_length. Without
  11583. // protection, the client would decompress the full 10MB from a tiny
  11584. // compressed payload, enabling a zip bomb DoS attack.
  11585. EXPECT_LE(total_decompressed, CLIENT_READ_LIMIT)
  11586. << "Client decompressed " << total_decompressed
  11587. << " bytes from a gzip response. The decompressed size should be "
  11588. << "limited by set_payload_max_length to prevent zip bomb attacks.";
  11589. }
  11590. #endif
  11591. TEST(HostAndPortPropertiesTest, NoSSL) {
  11592. httplib::Client cli("www.google.com", 1234);
  11593. ASSERT_EQ("www.google.com", cli.host());
  11594. ASSERT_EQ(1234, cli.port());
  11595. }
  11596. TEST(HostAndPortPropertiesTest, NoSSLWithSimpleAPI) {
  11597. httplib::Client cli("www.google.com:1234");
  11598. ASSERT_EQ("www.google.com", cli.host());
  11599. ASSERT_EQ(1234, cli.port());
  11600. }
  11601. TEST(HostAndPortPropertiesTest, OverflowPortNumber) {
  11602. // Port number that overflows int — should not crash, client becomes invalid
  11603. httplib::Client cli("http://www.google.com:99999999999999999999");
  11604. ASSERT_FALSE(cli.is_valid());
  11605. }
  11606. TEST(HostAndPortPropertiesTest, PortOutOfRange) {
  11607. // Port 99999 exceeds valid range (1-65535) — should not crash
  11608. httplib::Client cli("http://www.google.com:99999");
  11609. ASSERT_FALSE(cli.is_valid());
  11610. }
  11611. #ifdef CPPHTTPLIB_SSL_ENABLED
  11612. TEST(HostAndPortPropertiesTest, SSL) {
  11613. httplib::SSLClient cli("www.google.com");
  11614. ASSERT_EQ("www.google.com", cli.host());
  11615. ASSERT_EQ(443, cli.port());
  11616. }
  11617. TEST(SSLClientTest, UpdateCAStoreWithPem_Online) {
  11618. // Test updating CA store multiple times using PEM-based load_ca_cert_store
  11619. std::string cert;
  11620. read_file(CA_CERT_FILE, cert);
  11621. httplib::SSLClient httplib_client("www.google.com");
  11622. // Load CA store first time
  11623. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11624. // Load CA store second time (update)
  11625. httplib_client.load_ca_cert_store(cert.data(), cert.size());
  11626. // Verify client is still valid and can make connections
  11627. httplib_client.enable_server_certificate_verification(true);
  11628. auto res = httplib_client.Get("/");
  11629. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11630. // Google may return 200 or 301 depending on various factors
  11631. EXPECT_TRUE(res->status == StatusCode::OK_200 ||
  11632. res->status == StatusCode::MovedPermanently_301);
  11633. }
  11634. TEST(SSLClientTest, ServerNameIndication_Online) {
  11635. auto host = "httpbingo.org";
  11636. auto path = std::string{"/get"};
  11637. SSLClient cli(host, 443);
  11638. auto res = cli.Get(path);
  11639. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11640. ASSERT_EQ(StatusCode::OK_200, res->status);
  11641. }
  11642. TEST(SSLClientTest, ServerCertificateVerificationError_Online) {
  11643. // Use a site that will cause SSL verification failure due to self-signed cert
  11644. SSLClient cli("self-signed.badssl.com", 443);
  11645. cli.enable_server_certificate_verification(true);
  11646. auto res = cli.Get("/");
  11647. ASSERT_TRUE(!res);
  11648. EXPECT_EQ(Error::SSLServerVerification, res.error());
  11649. // Verify backend error is captured for SSLServerVerification
  11650. // This occurs when certificate verification fails
  11651. // OpenSSL: X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT (18)
  11652. // Mbed TLS: MBEDTLS_X509_BADCERT_NOT_TRUSTED or similar flags
  11653. EXPECT_NE(0UL, res.ssl_backend_error());
  11654. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11655. // For OpenSSL, ssl_error is 0 for verification errors
  11656. EXPECT_EQ(0, res.ssl_error());
  11657. #if !defined(_WIN32) || \
  11658. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11659. // On non-Windows or when Windows Schannel is disabled, the error comes
  11660. // from OpenSSL's verification
  11661. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_DEPTH_ZERO_SELF_SIGNED_CERT),
  11662. res.ssl_backend_error());
  11663. #endif
  11664. #endif
  11665. }
  11666. TEST(SSLClientTest, ServerHostnameVerificationError_Online) {
  11667. // Use a site where hostname doesn't match the certificate
  11668. // badssl.com provides wrong.host.badssl.com which has cert for *.badssl.com
  11669. SSLClient cli("wrong.host.badssl.com", 443);
  11670. cli.enable_server_certificate_verification(true);
  11671. cli.enable_server_hostname_verification(true);
  11672. auto res = cli.Get("/");
  11673. ASSERT_TRUE(!res);
  11674. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  11675. // Verify backend error is captured for hostname verification failure
  11676. EXPECT_NE(0UL, res.ssl_backend_error());
  11677. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11678. // For OpenSSL, ssl_error is 0 for verification errors
  11679. EXPECT_EQ(0, res.ssl_error());
  11680. #if !defined(_WIN32) || \
  11681. defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11682. // On non-Windows or when Windows Schannel is disabled, the error comes
  11683. // from OpenSSL's hostname verification
  11684. EXPECT_EQ(static_cast<unsigned long>(X509_V_ERR_HOSTNAME_MISMATCH),
  11685. res.ssl_backend_error());
  11686. #endif
  11687. #endif
  11688. }
  11689. #if defined(_WIN32) && defined(CPPHTTPLIB_SSL_ENABLED) && \
  11690. !defined(CPPHTTPLIB_DISABLE_WINDOWS_AUTOMATIC_ROOT_CERTIFICATES_UPDATE)
  11691. TEST(SSLClientTest, WindowsCertificateVerification_DefaultEnabled) {
  11692. SSLClient cli("www.google.com", 443);
  11693. cli.enable_server_certificate_verification(true);
  11694. auto res = cli.Get("/");
  11695. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11696. }
  11697. TEST(SSLClientTest, WindowsCertificateVerification_Disabled) {
  11698. SSLClient cli("www.google.com", 443);
  11699. cli.enable_server_certificate_verification(true);
  11700. cli.enable_windows_certificate_verification(false);
  11701. auto res = cli.Get("/");
  11702. if (res) { EXPECT_NE(StatusCode::InternalServerError_500, res->status); }
  11703. }
  11704. #endif
  11705. TEST(SSLClientTest, ServerCertificateVerification1_Online) {
  11706. Client cli("https://google.com");
  11707. auto res = cli.Get("/");
  11708. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11709. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11710. }
  11711. TEST(SSLClientTest, ServerCertificateVerification2_Online) {
  11712. SSLClient cli("google.com");
  11713. cli.set_ca_cert_path(CA_CERT_FILE);
  11714. auto res = cli.Get("/");
  11715. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11716. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11717. }
  11718. TEST(SSLClientTest, ServerCertificateVerification3_Online) {
  11719. SSLClient cli("google.com");
  11720. cli.enable_server_certificate_verification(true);
  11721. cli.set_ca_cert_path("hello");
  11722. auto res = cli.Get("/");
  11723. ASSERT_TRUE(!res);
  11724. EXPECT_EQ(Error::SSLLoadingCerts, res.error());
  11725. // For SSL_CTX operations, ssl_error should be 0, only ssl_backend_error
  11726. // should be set
  11727. EXPECT_EQ(0, res.ssl_error());
  11728. // Verify backend error is captured for SSLLoadingCerts
  11729. // This error occurs when loading CA certificates fails
  11730. EXPECT_NE(0UL, res.ssl_backend_error());
  11731. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  11732. // OpenSSL specific error codes:
  11733. // > openssl errstr 0x80000002
  11734. // error:80000002:system library::No such file or directory
  11735. // > openssl errstr 0xA000126
  11736. // error:0A000126:SSL routines::unexpected eof while reading
  11737. EXPECT_TRUE(res.ssl_backend_error() == 0x80000002 ||
  11738. res.ssl_backend_error() == 0xA000126);
  11739. #endif
  11740. }
  11741. TEST(SSLClientTest, ServerCertificateVerification4) {
  11742. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  11743. ASSERT_TRUE(svr.is_valid());
  11744. svr.Get("/test", [&](const Request &, Response &res) {
  11745. res.set_content("test", "text/plain");
  11746. svr.stop();
  11747. ASSERT_TRUE(true);
  11748. });
  11749. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  11750. auto se = detail::scope_exit([&] {
  11751. t.join();
  11752. ASSERT_FALSE(svr.is_running());
  11753. });
  11754. svr.wait_until_ready();
  11755. SSLClient cli("127.0.0.1", PORT);
  11756. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  11757. cli.enable_server_certificate_verification(true);
  11758. cli.set_connection_timeout(30);
  11759. auto res = cli.Get("/test");
  11760. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11761. ASSERT_EQ(StatusCode::OK_200, res->status);
  11762. }
  11763. TEST(SSLClientTest, ServerCertificateVerification5_Online) {
  11764. std::string cert;
  11765. read_file(CA_CERT_FILE, cert);
  11766. SSLClient cli("google.com");
  11767. cli.load_ca_cert_store(cert.data(), cert.size());
  11768. const auto res = cli.Get("/");
  11769. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11770. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11771. }
  11772. TEST(SSLClientTest, ServerCertificateVerification6_Online) {
  11773. // clang-format off
  11774. static constexpr char cert[] =
  11775. "GlobalSign Root CA\n"
  11776. "==================\n"
  11777. "-----BEGIN CERTIFICATE-----\n"
  11778. "MIIDdTCCAl2gAwIBAgILBAAAAAABFUtaw5QwDQYJKoZIhvcNAQEFBQAwVzELMAkGA1UEBhMCQkUx\n"
  11779. "GTAXBgNVBAoTEEdsb2JhbFNpZ24gbnYtc2ExEDAOBgNVBAsTB1Jvb3QgQ0ExGzAZBgNVBAMTEkds\n"
  11780. "b2JhbFNpZ24gUm9vdCBDQTAeFw05ODA5MDExMjAwMDBaFw0yODAxMjgxMjAwMDBaMFcxCzAJBgNV\n"
  11781. "BAYTAkJFMRkwFwYDVQQKExBHbG9iYWxTaWduIG52LXNhMRAwDgYDVQQLEwdSb290IENBMRswGQYD\n"
  11782. "VQQDExJHbG9iYWxTaWduIFJvb3QgQ0EwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAwggEKAoIBAQDa\n"
  11783. "DuaZjc6j40+Kfvvxi4Mla+pIH/EqsLmVEQS98GPR4mdmzxzdzxtIK+6NiY6arymAZavpxy0Sy6sc\n"
  11784. "THAHoT0KMM0VjU/43dSMUBUc71DuxC73/OlS8pF94G3VNTCOXkNz8kHp1Wrjsok6Vjk4bwY8iGlb\n"
  11785. "Kk3Fp1S4bInMm/k8yuX9ifUSPJJ4ltbcdG6TRGHRjcdGsnUOhugZitVtbNV4FpWi6cgKOOvyJBNP\n"
  11786. "c1STE4U6G7weNLWLBYy5d4ux2x8gkasJU26Qzns3dLlwR5EiUWMWea6xrkEmCMgZK9FGqkjWZCrX\n"
  11787. "gzT/LCrBbBlDSgeF59N89iFo7+ryUp9/k5DPAgMBAAGjQjBAMA4GA1UdDwEB/wQEAwIBBjAPBgNV\n"
  11788. "HRMBAf8EBTADAQH/MB0GA1UdDgQWBBRge2YaRQ2XyolQL30EzTSo//z9SzANBgkqhkiG9w0BAQUF\n"
  11789. "AAOCAQEA1nPnfE920I2/7LqivjTFKDK1fPxsnCwrvQmeU79rXqoRSLblCKOzyj1hTdNGCbM+w6Dj\n"
  11790. "Y1Ub8rrvrTnhQ7k4o+YviiY776BQVvnGCv04zcQLcFGUl5gE38NflNUVyRRBnMRddWQVDf9VMOyG\n"
  11791. "j/8N7yy5Y0b2qvzfvGn9LhJIZJrglfCm7ymPAbEVtQwdpf5pLGkkeB6zpxxxYu7KyJesF12KwvhH\n"
  11792. "hm4qxFYxldBniYUr+WymXUadDKqC5JlR3XC321Y9YeRq4VzW9v493kHMB65jUr9TU/Qr6cf9tveC\n"
  11793. "X4XSQRjbgbMEHMUfpIBvFSDJ3gyICh3WZlXi/EjJKSZp4A==\n"
  11794. "-----END CERTIFICATE-----\n";
  11795. // clang-format on
  11796. SSLClient cli("google.com");
  11797. cli.load_ca_cert_store(cert, sizeof(cert));
  11798. const auto res = cli.Get("/");
  11799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11800. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  11801. }
  11802. TEST(SSLClientTest, WildcardHostNameMatch_Online) {
  11803. SSLClient cli("www.youtube.com");
  11804. cli.set_ca_cert_path(CA_CERT_FILE);
  11805. cli.enable_server_certificate_verification(true);
  11806. cli.set_follow_location(true);
  11807. auto res = cli.Get("/");
  11808. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11809. ASSERT_EQ(StatusCode::OK_200, res->status);
  11810. }
  11811. TEST(SSLClientTest, WildcardHostNameMatchCase_Online) {
  11812. SSLClient cli("wWw.YouTube.Com");
  11813. cli.set_ca_cert_path(CA_CERT_FILE);
  11814. cli.enable_server_certificate_verification(true);
  11815. cli.enable_server_hostname_verification(true);
  11816. cli.set_follow_location(true);
  11817. auto res = cli.Get("/");
  11818. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11819. ASSERT_EQ(StatusCode::OK_200, res->status);
  11820. }
  11821. TEST(SSLClientTest, HostNameMatchCase_Online) {
  11822. SSLClient cli("gOoGlE.COm");
  11823. cli.enable_server_certificate_verification(true);
  11824. cli.enable_server_hostname_verification(true);
  11825. cli.set_follow_location(true);
  11826. auto res = cli.Get("/");
  11827. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11828. ASSERT_EQ(StatusCode::OK_200, res->status);
  11829. }
  11830. TEST(SSLClientTest, Issue2004_Online) {
  11831. Client client("https://google.com");
  11832. client.set_follow_location(true);
  11833. auto res = client.Get("/");
  11834. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11835. ASSERT_EQ(StatusCode::OK_200, res->status);
  11836. auto body = res->body;
  11837. EXPECT_EQ(body.substr(0, 15), "<!doctype html>");
  11838. }
  11839. TEST(SSLClientTest, ErrorReportingWhenInvalid) {
  11840. // Create SSLClient with invalid cert/key to make is_valid() return false
  11841. SSLClient cli("localhost", 8080, "nonexistent_cert.pem",
  11842. "nonexistent_key.pem");
  11843. // is_valid() should be false due to cert loading failure
  11844. ASSERT_FALSE(cli.is_valid());
  11845. auto res = cli.Get("/");
  11846. ASSERT_FALSE(res);
  11847. EXPECT_EQ(Error::SSLConnection, res.error());
  11848. }
  11849. TEST(SSLClientTest, Issue2251_SwappedClientCertAndKey) {
  11850. // Test for Issue #2251: SSL error not properly reported when client cert
  11851. // and key paths are swapped or mismatched
  11852. // This simulates the scenario where user accidentally swaps the cert and key
  11853. // files
  11854. // Using client cert file as private key and vice versa (completely wrong)
  11855. SSLClient cli("localhost", 8080, "client.key.pem", "client.cert.pem");
  11856. // Should fail validation due to cert/key mismatch
  11857. ASSERT_FALSE(cli.is_valid());
  11858. // Attempt to make a request should fail with proper error
  11859. auto res = cli.Get("/");
  11860. ASSERT_FALSE(res);
  11861. EXPECT_EQ(Error::SSLConnection, res.error());
  11862. // SSL error should be recorded in the Result object (this is the key fix for
  11863. // Issue #2251)
  11864. auto backend_error = res.ssl_backend_error();
  11865. EXPECT_NE(0u, backend_error);
  11866. }
  11867. // Tests cert/key mismatch detection at the TLS context level
  11868. TEST(TlsApiTest, ClientCertKeyMismatch) {
  11869. // Test that using mismatched cert/key causes connection failure.
  11870. // We verify this at the SSLClient level rather than through internal
  11871. // TLS API functions.
  11872. SSLClient cli(HOST, PORT, "client.cert.pem", "key.pem");
  11873. cli.enable_server_certificate_verification(false);
  11874. cli.set_connection_timeout(2);
  11875. // The mismatch should cause a connection or handshake error
  11876. auto res = cli.Get("/test");
  11877. // OpenSSL detects mismatch at context setup, MbedTLS at handshake
  11878. // Either way, the request should fail
  11879. EXPECT_FALSE(res);
  11880. }
  11881. #endif
  11882. #if 0
  11883. TEST(SSLClientTest, SetInterfaceWithINET6) {
  11884. auto cli = std::make_shared<httplib::Client>("https://httpcan.org");
  11885. ASSERT_TRUE(cli != nullptr);
  11886. cli->set_address_family(AF_INET6);
  11887. cli->set_interface("en0");
  11888. auto res = cli->Get("/get");
  11889. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11890. ASSERT_EQ(StatusCode::OK_200, res->status);
  11891. }
  11892. #endif
  11893. // ClientCertPresent uses get_peer_cert() - works with all TLS backends
  11894. #ifdef CPPHTTPLIB_SSL_ENABLED
  11895. void ClientCertPresent(
  11896. const std::string &client_cert_file,
  11897. const std::string &client_private_key_file,
  11898. const std::string &client_encrypted_private_key_pass = std::string()) {
  11899. using namespace httplib::tls;
  11900. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11901. CLIENT_CA_CERT_DIR);
  11902. ASSERT_TRUE(svr.is_valid());
  11903. svr.Get("/test", [&](const Request &req, Response &res) {
  11904. res.set_content("test", "text/plain");
  11905. auto cert = req.peer_cert();
  11906. ASSERT_TRUE(static_cast<bool>(cert));
  11907. std::string common_name = cert.subject_cn();
  11908. EXPECT_EQ("Common Name", common_name);
  11909. });
  11910. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11911. auto se = detail::scope_exit([&] {
  11912. svr.stop();
  11913. t.join();
  11914. ASSERT_FALSE(svr.is_running());
  11915. });
  11916. svr.wait_until_ready();
  11917. SSLClient cli(HOST, PORT, client_cert_file, client_private_key_file,
  11918. client_encrypted_private_key_pass);
  11919. cli.enable_server_certificate_verification(false);
  11920. cli.set_connection_timeout(30);
  11921. auto res = cli.Get("/test");
  11922. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11923. ASSERT_EQ(StatusCode::OK_200, res->status);
  11924. }
  11925. TEST(SSLClientServerTest, ClientCertPresent) {
  11926. ClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11927. }
  11928. TEST(SSLClientServerTest, ClientEncryptedCertPresent) {
  11929. ClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11930. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11931. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11932. }
  11933. // PEM memory-based constructor tests (works with all TLS backends)
  11934. void PemMemoryClientCertPresent(
  11935. const std::string &client_cert_file,
  11936. const std::string &client_private_key_file,
  11937. const std::string &client_encrypted_private_key_pass = std::string()) {
  11938. // Read PEM files into memory
  11939. std::string server_cert_pem, server_key_pem;
  11940. std::string client_ca_pem;
  11941. std::string client_cert_pem, client_key_pem;
  11942. read_file(SERVER_CERT_FILE, server_cert_pem);
  11943. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  11944. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  11945. read_file(client_cert_file, client_cert_pem);
  11946. read_file(client_private_key_file, client_key_pem);
  11947. // Create server with PEM memory
  11948. SSLServer::PemMemory server_pem = {
  11949. server_cert_pem.c_str(),
  11950. server_cert_pem.size(),
  11951. server_key_pem.c_str(),
  11952. server_key_pem.size(),
  11953. client_ca_pem.c_str(),
  11954. client_ca_pem.size(),
  11955. nullptr // no password for server key
  11956. };
  11957. SSLServer svr(server_pem);
  11958. ASSERT_TRUE(svr.is_valid());
  11959. svr.Get("/test", [&](const Request &, Response &res) {
  11960. res.set_content("test", "text/plain");
  11961. });
  11962. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11963. auto se = detail::scope_exit([&] {
  11964. svr.stop();
  11965. t.join();
  11966. ASSERT_FALSE(svr.is_running());
  11967. });
  11968. svr.wait_until_ready();
  11969. // Create client with PEM memory
  11970. const char *password = client_encrypted_private_key_pass.empty()
  11971. ? nullptr
  11972. : client_encrypted_private_key_pass.c_str();
  11973. SSLClient::PemMemory client_pem = {
  11974. client_cert_pem.c_str(), client_cert_pem.size(), client_key_pem.c_str(),
  11975. client_key_pem.size(), password};
  11976. SSLClient cli(HOST, PORT, client_pem);
  11977. cli.enable_server_certificate_verification(false);
  11978. cli.set_connection_timeout(30);
  11979. auto res = cli.Get("/test");
  11980. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  11981. ASSERT_EQ(StatusCode::OK_200, res->status);
  11982. }
  11983. TEST(SSLClientServerTest, PemMemoryClientCertPresent) {
  11984. PemMemoryClientCertPresent(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  11985. }
  11986. TEST(SSLClientServerTest, PemMemoryClientEncryptedCertPresent) {
  11987. PemMemoryClientCertPresent(CLIENT_ENCRYPTED_CERT_FILE,
  11988. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  11989. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  11990. }
  11991. TEST(SSLClientServerTest, ClientCertMissing) {
  11992. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  11993. CLIENT_CA_CERT_DIR);
  11994. ASSERT_TRUE(svr.is_valid());
  11995. svr.Get("/test", [&](const Request &, Response &) { ASSERT_TRUE(false); });
  11996. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  11997. auto se = detail::scope_exit([&] {
  11998. svr.stop();
  11999. t.join();
  12000. ASSERT_FALSE(svr.is_running());
  12001. });
  12002. svr.wait_until_ready();
  12003. SSLClient cli(HOST, PORT);
  12004. cli.set_connection_timeout(30);
  12005. auto res = cli.Get("/test");
  12006. ASSERT_TRUE(!res);
  12007. // When client cert is missing and server requires it, connection fails
  12008. // Error type depends on backend implementation
  12009. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  12010. res.error() == Error::SSLConnection);
  12011. // Verify backend error is captured
  12012. // Note: This test may have different error codes depending on the exact
  12013. // verification failure
  12014. EXPECT_NE(0UL, res.ssl_backend_error());
  12015. }
  12016. TEST(SSLClientServerTest, TrustDirOptional) {
  12017. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12018. ASSERT_TRUE(svr.is_valid());
  12019. svr.Get("/test", [&](const Request &, Response &res) {
  12020. res.set_content("test", "text/plain");
  12021. });
  12022. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12023. auto se = detail::scope_exit([&] {
  12024. svr.stop();
  12025. t.join();
  12026. ASSERT_FALSE(svr.is_running());
  12027. });
  12028. svr.wait_until_ready();
  12029. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12030. cli.enable_server_certificate_verification(false);
  12031. cli.set_connection_timeout(30);
  12032. auto res = cli.Get("/test");
  12033. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12034. ASSERT_EQ(StatusCode::OK_200, res->status);
  12035. }
  12036. TEST(SSLClientServerTest, SSLConnectTimeout) {
  12037. class NoListenSSLServer : public SSLServer {
  12038. public:
  12039. NoListenSSLServer(const char *cert_path, const char *private_key_path,
  12040. const char *client_ca_cert_file_path,
  12041. const char *client_ca_cert_dir_path = nullptr)
  12042. : SSLServer(cert_path, private_key_path, client_ca_cert_file_path,
  12043. client_ca_cert_dir_path),
  12044. stop_(false) {}
  12045. std::atomic_bool stop_;
  12046. private:
  12047. bool process_and_close_socket(socket_t /*sock*/) override {
  12048. // Don't create SSL context
  12049. while (!stop_.load()) {
  12050. std::this_thread::sleep_for(std::chrono::milliseconds(100));
  12051. }
  12052. return true;
  12053. }
  12054. };
  12055. NoListenSSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12056. CLIENT_CA_CERT_FILE);
  12057. ASSERT_TRUE(svr.is_valid());
  12058. svr.Get("/test", [&](const Request &, Response &res) {
  12059. res.set_content("test", "text/plain");
  12060. });
  12061. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12062. auto se = detail::scope_exit([&] {
  12063. svr.stop_ = true;
  12064. svr.stop();
  12065. t.join();
  12066. ASSERT_FALSE(svr.is_running());
  12067. });
  12068. svr.wait_until_ready();
  12069. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12070. cli.enable_server_certificate_verification(false);
  12071. cli.set_connection_timeout(1);
  12072. auto res = cli.Get("/test");
  12073. ASSERT_TRUE(!res);
  12074. EXPECT_EQ(Error::SSLConnection, res.error());
  12075. // Timeout results in WantRead error code (maps to backend-specific value)
  12076. EXPECT_NE(0, res.ssl_error());
  12077. }
  12078. TEST(SSLClientServerTest, CustomizeServerSSLCtxGeneric) {
  12079. // Test SSLServer with client certificate verification using the standard
  12080. // constructor (ContextSetupCallback is tested by backend-specific tests)
  12081. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE,
  12082. CLIENT_CA_CERT_DIR);
  12083. ASSERT_TRUE(svr.is_valid());
  12084. svr.Get("/test", [&](const Request &req, Response &res) {
  12085. res.set_content("test", "text/plain");
  12086. auto cert = req.peer_cert();
  12087. ASSERT_TRUE(static_cast<bool>(cert));
  12088. auto common_name = cert.subject_cn();
  12089. EXPECT_EQ("Common Name", common_name);
  12090. });
  12091. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12092. auto se = detail::scope_exit([&] {
  12093. svr.stop();
  12094. t.join();
  12095. ASSERT_FALSE(svr.is_running());
  12096. });
  12097. svr.wait_until_ready();
  12098. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12099. cli.enable_server_certificate_verification(false);
  12100. cli.set_connection_timeout(30);
  12101. auto res = cli.Get("/test");
  12102. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12103. ASSERT_EQ(StatusCode::OK_200, res->status);
  12104. }
  12105. // Test verify_hostname for both OpenSSL and MbedTLS backends
  12106. // Verifies that wildcard matching and exact matching work consistently
  12107. TEST(SSLClientServerTest, TlsVerifyHostname) {
  12108. using namespace httplib::tls;
  12109. // We need a running server to test against
  12110. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12111. ASSERT_TRUE(svr.is_valid());
  12112. svr.Get("/test", [](const Request &, Response &res) {
  12113. res.set_content("ok", "text/plain");
  12114. });
  12115. thread t([&]() { svr.listen(HOST, PORT); });
  12116. auto se = detail::scope_exit([&] {
  12117. svr.stop();
  12118. t.join();
  12119. });
  12120. svr.wait_until_ready();
  12121. bool verify_callback_called = false;
  12122. bool verify_result_wrong = false;
  12123. SSLClient cli(HOST, PORT);
  12124. cli.enable_server_certificate_verification(true);
  12125. cli.set_ca_cert_path(CA_CERT_FILE);
  12126. cli.set_connection_timeout(5);
  12127. // Note: Test certificate has CN="Common Name", not "localhost"
  12128. bool verify_result_cn = false;
  12129. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12130. verify_callback_called = true;
  12131. if (!ctx.cert) return false;
  12132. // Test 1: "Common Name" should match (our test server cert CN)
  12133. verify_result_cn = ctx.check_hostname("Common Name");
  12134. // Test 2: wrong hostname should not match
  12135. verify_result_wrong = ctx.check_hostname("wronghost.example.com");
  12136. return true; // Accept for the purpose of this test
  12137. });
  12138. auto res = cli.Get("/test");
  12139. // The request may succeed or fail depending on cert configuration
  12140. // but the callback should have been called
  12141. ASSERT_TRUE(verify_callback_called)
  12142. << "Verify callback should have been called";
  12143. // CN="Common Name" should match our test certificate
  12144. //
  12145. // BoringSSL intentionally drops CN-based hostname matching per RFC 6125
  12146. // §6.4.4 — only SubjectAltName is consulted. Other backends (OpenSSL,
  12147. // MbedTLS, wolfSSL) still honor the CN fallback, so flip the expectation
  12148. // for BoringSSL builds. OPENSSL_IS_BORINGSSL is defined by BoringSSL's
  12149. // <openssl/base.h>, which is included transitively when
  12150. // CPPHTTPLIB_OPENSSL_SUPPORT is set against a BoringSSL install.
  12151. #if defined(OPENSSL_IS_BORINGSSL)
  12152. EXPECT_FALSE(verify_result_cn)
  12153. << "BoringSSL should reject CN-based hostname matching (SAN-only)";
  12154. #else
  12155. EXPECT_TRUE(verify_result_cn)
  12156. << "verify_hostname should match 'Common Name' (certificate CN)";
  12157. #endif
  12158. // Wrong hostname should not match
  12159. EXPECT_FALSE(verify_result_wrong)
  12160. << "verify_hostname should not match 'wronghost.example.com'";
  12161. }
  12162. // An IP-literal host must only be authenticated via an iPAddress SAN, never via
  12163. // the certificate's Common Name (RFC 9110). This mirrors the OpenSSL backend's
  12164. // X509_check_ip behavior and must hold for every backend.
  12165. TEST(SSLClientServerTest, TlsVerifyHostnameIpNotMatchedByCommonName) {
  12166. using namespace httplib::tls;
  12167. // Certificate CN is the IPv4 literal "127.0.0.1" and it carries no SAN.
  12168. SSLServer svr(SERVER_CERT_IP_CN_FILE, SERVER_PRIVATE_KEY_FILE);
  12169. ASSERT_TRUE(svr.is_valid());
  12170. svr.Get("/test", [](const Request &, Response &res) {
  12171. res.set_content("ok", "text/plain");
  12172. });
  12173. thread t([&]() { svr.listen(HOST, PORT); });
  12174. auto se = detail::scope_exit([&] {
  12175. svr.stop();
  12176. t.join();
  12177. });
  12178. svr.wait_until_ready();
  12179. bool verify_callback_called = false;
  12180. bool ip_matched_via_cn = true;
  12181. SSLClient cli(HOST, PORT);
  12182. cli.enable_server_certificate_verification(true);
  12183. cli.set_ca_cert_path(CA_CERT_FILE);
  12184. cli.set_connection_timeout(5);
  12185. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12186. verify_callback_called = true;
  12187. if (!ctx.cert) return false;
  12188. // The IP appears only in the CN, so it must NOT be accepted.
  12189. ip_matched_via_cn = ctx.check_hostname("127.0.0.1");
  12190. return true; // Accept for the purpose of this test
  12191. });
  12192. cli.Get("/test");
  12193. ASSERT_TRUE(verify_callback_called)
  12194. << "Verify callback should have been called";
  12195. EXPECT_FALSE(ip_matched_via_cn)
  12196. << "An IP host must not be authenticated via the certificate CN";
  12197. }
  12198. // IPv6 hosts must be matched against IPv6 iPAddress SANs (and only those).
  12199. TEST(SSLClientServerTest, TlsVerifyHostnameIpv6San) {
  12200. using namespace httplib::tls;
  12201. // Certificate CN is "::1" and it carries an IPv6 SAN for "2001:db8::1".
  12202. SSLServer svr(SERVER_CERT_IPV6_FILE, SERVER_PRIVATE_KEY_FILE);
  12203. ASSERT_TRUE(svr.is_valid());
  12204. svr.Get("/test", [](const Request &, Response &res) {
  12205. res.set_content("ok", "text/plain");
  12206. });
  12207. thread t([&]() { svr.listen(HOST, PORT); });
  12208. auto se = detail::scope_exit([&] {
  12209. svr.stop();
  12210. t.join();
  12211. });
  12212. svr.wait_until_ready();
  12213. bool verify_callback_called = false;
  12214. bool san_matched = false;
  12215. bool wrong_ipv6_matched = true;
  12216. bool cn_ipv6_matched = true;
  12217. SSLClient cli(HOST, PORT);
  12218. cli.enable_server_certificate_verification(true);
  12219. cli.set_ca_cert_path(CA_CERT_FILE);
  12220. cli.set_connection_timeout(5);
  12221. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12222. verify_callback_called = true;
  12223. if (!ctx.cert) return false;
  12224. // Matches the IPv6 iPAddress SAN.
  12225. san_matched = ctx.check_hostname("2001:db8::1");
  12226. // A different IPv6 address must not match.
  12227. wrong_ipv6_matched = ctx.check_hostname("2001:db8::2");
  12228. // "::1" lives only in the CN, so it must not be accepted.
  12229. cn_ipv6_matched = ctx.check_hostname("::1");
  12230. return true; // Accept for the purpose of this test
  12231. });
  12232. cli.Get("/test");
  12233. ASSERT_TRUE(verify_callback_called)
  12234. << "Verify callback should have been called";
  12235. EXPECT_TRUE(san_matched)
  12236. << "verify_hostname should match an IPv6 iPAddress SAN";
  12237. EXPECT_FALSE(wrong_ipv6_matched)
  12238. << "verify_hostname should not match a non-matching IPv6 address";
  12239. EXPECT_FALSE(cn_ipv6_matched)
  12240. << "An IPv6 host must not be authenticated via the certificate CN";
  12241. }
  12242. #endif
  12243. // mbedTLS-specific callback constructor test
  12244. // Tests that the void* callback can customize TLS settings via MbedTlsContext
  12245. #ifdef CPPHTTPLIB_SSL_ENABLED
  12246. TEST(SSLClientServerTest, ClientCAListSentToClient) {
  12247. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12248. ASSERT_TRUE(svr.is_valid());
  12249. // Set up a handler to verify client certificate is present
  12250. bool client_cert_verified = false;
  12251. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  12252. // Verify that client certificate was provided
  12253. client_cert_verified = true;
  12254. res.set_content("success", "text/plain");
  12255. });
  12256. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12257. auto se = detail::scope_exit([&] {
  12258. svr.stop();
  12259. t.join();
  12260. ASSERT_FALSE(svr.is_running());
  12261. });
  12262. svr.wait_until_ready();
  12263. // Client with certificate
  12264. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12265. cli.enable_server_certificate_verification(false);
  12266. cli.set_connection_timeout(30);
  12267. auto res = cli.Get("/test");
  12268. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12269. ASSERT_EQ(StatusCode::OK_200, res->status);
  12270. ASSERT_TRUE(client_cert_verified);
  12271. EXPECT_EQ("success", res->body);
  12272. }
  12273. #endif
  12274. // ClientCAListSetInContext uses get_peer_cert() - works with all TLS
  12275. // backends
  12276. #ifdef CPPHTTPLIB_SSL_ENABLED
  12277. TEST(SSLClientServerTest, ClientCAListSetInContext) {
  12278. using namespace httplib::tls;
  12279. // Test that when client CA cert file is provided,
  12280. // the server properly requests and validates client certificates
  12281. // Create a server with client authentication
  12282. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  12283. ASSERT_TRUE(svr.is_valid());
  12284. bool handler_called = false;
  12285. svr.Get("/test", [&](const Request &req, Response &res) {
  12286. handler_called = true;
  12287. // Verify that a client certificate was provided
  12288. auto cert = req.peer_cert();
  12289. ASSERT_TRUE(static_cast<bool>(cert));
  12290. // Get the issuer name
  12291. std::string issuer_str = cert.issuer_name();
  12292. ASSERT_FALSE(issuer_str.empty());
  12293. // The client certificate should be issued by our test CA
  12294. EXPECT_TRUE(issuer_str.find("Root CA Name") != std::string::npos);
  12295. res.set_content("authenticated", "text/plain");
  12296. });
  12297. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12298. auto se = detail::scope_exit([&] {
  12299. svr.stop();
  12300. t.join();
  12301. ASSERT_FALSE(svr.is_running());
  12302. });
  12303. svr.wait_until_ready();
  12304. // Connect with a client certificate issued by the CA
  12305. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12306. cli.enable_server_certificate_verification(false);
  12307. cli.set_connection_timeout(30);
  12308. auto res = cli.Get("/test");
  12309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12310. ASSERT_EQ(StatusCode::OK_200, res->status);
  12311. ASSERT_TRUE(handler_called);
  12312. EXPECT_EQ("authenticated", res->body);
  12313. }
  12314. TEST(TlsCertIntrospectionTest, GetCertSANs) {
  12315. using namespace httplib::tls;
  12316. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12317. ASSERT_TRUE(svr.is_valid());
  12318. svr.Get("/test", [](const Request &, Response &res) {
  12319. res.set_content("ok", "text/plain");
  12320. });
  12321. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12322. auto se = detail::scope_exit([&] {
  12323. svr.stop();
  12324. t.join();
  12325. });
  12326. svr.wait_until_ready();
  12327. SSLClient cli(HOST, PORT);
  12328. cli.enable_server_certificate_verification(false);
  12329. cli.set_connection_timeout(30);
  12330. bool cert_checked = false;
  12331. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12332. if (ctx.cert) {
  12333. auto sans = ctx.sans();
  12334. // Test certificate may or may not have SANs - just verify the API
  12335. // works If SANs exist, verify the types are valid
  12336. for (const auto &san : sans) {
  12337. EXPECT_TRUE(san.type == SanType::DNS || san.type == SanType::IP ||
  12338. san.type == SanType::EMAIL || san.type == SanType::URI ||
  12339. san.type == SanType::OTHER);
  12340. EXPECT_FALSE(san.value.empty());
  12341. }
  12342. cert_checked = true;
  12343. }
  12344. return true;
  12345. });
  12346. auto res = cli.Get("/test");
  12347. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12348. EXPECT_TRUE(cert_checked);
  12349. }
  12350. TEST(TlsCertIntrospectionTest, GetCertValidity) {
  12351. using namespace httplib::tls;
  12352. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12353. ASSERT_TRUE(svr.is_valid());
  12354. svr.Get("/test", [](const Request &, Response &res) {
  12355. res.set_content("ok", "text/plain");
  12356. });
  12357. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12358. auto se = detail::scope_exit([&] {
  12359. svr.stop();
  12360. t.join();
  12361. });
  12362. svr.wait_until_ready();
  12363. SSLClient cli(HOST, PORT);
  12364. cli.enable_server_certificate_verification(false);
  12365. cli.set_connection_timeout(30);
  12366. bool validity_checked = false;
  12367. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12368. if (ctx.cert) {
  12369. time_t not_before = 0, not_after = 0;
  12370. bool result = ctx.validity(not_before, not_after);
  12371. EXPECT_TRUE(result);
  12372. // Verify that not_before < now < not_after for a valid cert
  12373. time_t now = time(nullptr);
  12374. EXPECT_LT(not_before, now);
  12375. EXPECT_GT(not_after, now);
  12376. validity_checked = true;
  12377. }
  12378. return true;
  12379. });
  12380. auto res = cli.Get("/test");
  12381. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12382. EXPECT_TRUE(validity_checked);
  12383. }
  12384. TEST(TlsCertIntrospectionTest, GetCertSerial) {
  12385. using namespace httplib::tls;
  12386. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12387. ASSERT_TRUE(svr.is_valid());
  12388. svr.Get("/test", [](const Request &, Response &res) {
  12389. res.set_content("ok", "text/plain");
  12390. });
  12391. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12392. auto se = detail::scope_exit([&] {
  12393. svr.stop();
  12394. t.join();
  12395. });
  12396. svr.wait_until_ready();
  12397. SSLClient cli(HOST, PORT);
  12398. cli.enable_server_certificate_verification(false);
  12399. cli.set_connection_timeout(30);
  12400. bool serial_checked = false;
  12401. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12402. if (ctx.cert) {
  12403. std::string serial = ctx.serial();
  12404. EXPECT_FALSE(serial.empty());
  12405. // Serial should be a hex string
  12406. for (char c : serial) {
  12407. EXPECT_TRUE((c >= '0' && c <= '9') || (c >= 'A' && c <= 'F') ||
  12408. (c >= 'a' && c <= 'f'));
  12409. }
  12410. serial_checked = true;
  12411. }
  12412. return true;
  12413. });
  12414. auto res = cli.Get("/test");
  12415. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12416. EXPECT_TRUE(serial_checked);
  12417. }
  12418. TEST(SSLClientServerTest, ClientCAListLoadErrorRecorded) {
  12419. // Test 1: Valid CA file - no error should be recorded
  12420. {
  12421. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  12422. CLIENT_CA_CERT_FILE);
  12423. ASSERT_TRUE(svr.is_valid());
  12424. // With valid setup, last_ssl_error should be 0
  12425. EXPECT_EQ(0, svr.ssl_last_error());
  12426. }
  12427. // Test 2: Invalid CA file content
  12428. // When SSL_load_client_CA_file fails, last_ssl_error_ should be set
  12429. {
  12430. // Create a temporary file with completely invalid content
  12431. const char *temp_invalid_ca = "./temp_invalid_ca_for_test.txt";
  12432. {
  12433. std::ofstream ofs(temp_invalid_ca);
  12434. ofs << "This is not a certificate file at all\n";
  12435. ofs << "Just plain text content\n";
  12436. }
  12437. // Create server with invalid CA file
  12438. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, temp_invalid_ca);
  12439. // Clean up temporary file
  12440. std::remove(temp_invalid_ca);
  12441. // When there's an SSL error (from either SSL_CTX_load_verify_locations
  12442. // or SSL_load_client_CA_file), last_ssl_error_ should be non-zero
  12443. // Note: SSL_CTX_load_verify_locations typically fails first,
  12444. // but our error handling code path is still exercised
  12445. if (!svr.is_valid()) { EXPECT_NE(0, svr.ssl_last_error()); }
  12446. }
  12447. }
  12448. TEST(VerifyCallbackTest, VerifyContextFields) {
  12449. using namespace httplib::tls;
  12450. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12451. ASSERT_TRUE(svr.is_valid());
  12452. svr.Get("/test", [](const Request &, Response &res) {
  12453. res.set_content("ok", "text/plain");
  12454. });
  12455. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12456. auto se = detail::scope_exit([&] {
  12457. svr.stop();
  12458. t.join();
  12459. });
  12460. svr.wait_until_ready();
  12461. SSLClient cli(HOST, PORT);
  12462. cli.enable_server_certificate_verification(false);
  12463. cli.set_connection_timeout(30);
  12464. int callback_count = 0;
  12465. bool saw_leaf_cert = false;
  12466. cli.set_server_certificate_verifier([&](const VerifyContext &ctx) -> bool {
  12467. if (ctx.cert) {
  12468. callback_count++;
  12469. // We should see at least one certificate (the leaf)
  12470. std::string cn = ctx.subject_cn();
  12471. if (!cn.empty()) { saw_leaf_cert = true; }
  12472. // Verify context fields are populated
  12473. EXPECT_NE(ctx.session, nullptr);
  12474. EXPECT_GE(ctx.depth, 0);
  12475. }
  12476. return true;
  12477. });
  12478. auto res = cli.Get("/test");
  12479. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12480. EXPECT_GT(callback_count, 0);
  12481. EXPECT_TRUE(saw_leaf_cert);
  12482. }
  12483. TEST(TlsVerifyErrorTest, GetVerifyErrorString) {
  12484. using httplib::tls::TlsError;
  12485. // Test that verify_error_to_string returns empty for success
  12486. std::string success_str = TlsError::verify_error_to_string(0);
  12487. EXPECT_TRUE(success_str.empty());
  12488. // Test that verify_error_to_string returns non-empty for error codes
  12489. // Using a common error code (certificate expired)
  12490. std::string error_str =
  12491. TlsError::verify_error_to_string(10); // X509_V_ERR_CERT_HAS_EXPIRED
  12492. EXPECT_FALSE(error_str.empty());
  12493. }
  12494. TEST(SessionVerifierTest, CertificateAccepted) {
  12495. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12496. ASSERT_TRUE(svr.is_valid());
  12497. svr.Get("/test", [](const Request &, Response &res) {
  12498. res.set_content("ok", "text/plain");
  12499. });
  12500. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12501. auto se = detail::scope_exit([&] {
  12502. svr.stop();
  12503. t.join();
  12504. });
  12505. svr.wait_until_ready();
  12506. SSLClient cli(HOST, PORT);
  12507. cli.enable_server_certificate_verification(false);
  12508. cli.set_connection_timeout(30);
  12509. bool callback_called = false;
  12510. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12511. EXPECT_NE(session, nullptr);
  12512. callback_called = true;
  12513. return SSLVerifierResponse::CertificateAccepted;
  12514. });
  12515. auto res = cli.Get("/test");
  12516. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12517. EXPECT_EQ(200, res->status);
  12518. EXPECT_TRUE(callback_called);
  12519. }
  12520. TEST(SessionVerifierTest, CertificateRejected) {
  12521. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12522. ASSERT_TRUE(svr.is_valid());
  12523. svr.Get("/test", [](const Request &, Response &res) {
  12524. res.set_content("ok", "text/plain");
  12525. });
  12526. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12527. auto se = detail::scope_exit([&] {
  12528. svr.stop();
  12529. t.join();
  12530. });
  12531. svr.wait_until_ready();
  12532. SSLClient cli(HOST, PORT);
  12533. cli.enable_server_certificate_verification(false);
  12534. cli.set_connection_timeout(30);
  12535. bool callback_called = false;
  12536. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12537. EXPECT_NE(session, nullptr);
  12538. callback_called = true;
  12539. return SSLVerifierResponse::CertificateRejected;
  12540. });
  12541. auto res = cli.Get("/test");
  12542. EXPECT_FALSE(res);
  12543. EXPECT_TRUE(callback_called);
  12544. }
  12545. TEST(SessionVerifierTest, NoDecisionFallsThrough) {
  12546. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12547. ASSERT_TRUE(svr.is_valid());
  12548. svr.Get("/test", [](const Request &, Response &res) {
  12549. res.set_content("ok", "text/plain");
  12550. });
  12551. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12552. auto se = detail::scope_exit([&] {
  12553. svr.stop();
  12554. t.join();
  12555. });
  12556. svr.wait_until_ready();
  12557. // NoDecisionMade with verification disabled should succeed (no default check)
  12558. SSLClient cli(HOST, PORT);
  12559. cli.enable_server_certificate_verification(false);
  12560. cli.set_connection_timeout(30);
  12561. bool callback_called = false;
  12562. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12563. EXPECT_NE(session, nullptr);
  12564. callback_called = true;
  12565. return SSLVerifierResponse::NoDecisionMade;
  12566. });
  12567. auto res = cli.Get("/test");
  12568. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12569. EXPECT_EQ(200, res->status);
  12570. EXPECT_TRUE(callback_called);
  12571. }
  12572. TEST(SessionVerifierTest, NoDecisionWithVerificationEnabled) {
  12573. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  12574. ASSERT_TRUE(svr.is_valid());
  12575. svr.Get("/test", [](const Request &, Response &res) {
  12576. res.set_content("ok", "text/plain");
  12577. });
  12578. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  12579. auto se = detail::scope_exit([&] {
  12580. svr.stop();
  12581. t.join();
  12582. });
  12583. svr.wait_until_ready();
  12584. // NoDecisionMade with verification enabled should fail (self-signed cert).
  12585. // Note: On MbedTLS, the handshake itself fails before reaching the verifier,
  12586. // so we only check that the request fails, not whether the callback was
  12587. // called.
  12588. SSLClient cli(HOST, PORT);
  12589. cli.enable_server_certificate_verification(true);
  12590. cli.set_connection_timeout(30);
  12591. cli.set_session_verifier([&](tls::session_t session) -> SSLVerifierResponse {
  12592. EXPECT_NE(session, nullptr);
  12593. return SSLVerifierResponse::NoDecisionMade;
  12594. });
  12595. auto res = cli.Get("/test");
  12596. EXPECT_FALSE(res);
  12597. }
  12598. TEST(SSLClientServerTest, ClientCAListFromPem) {
  12599. // Test SSL server using PemMemory constructor with client CA certificates
  12600. // Read PEM files
  12601. std::string server_cert_pem, server_key_pem, client_ca_pem;
  12602. read_file(SERVER_CERT_FILE, server_cert_pem);
  12603. read_file(SERVER_PRIVATE_KEY_FILE, server_key_pem);
  12604. read_file(CLIENT_CA_CERT_FILE, client_ca_pem);
  12605. // Create SSLServer with PemMemory constructor including client CA
  12606. SSLServer::PemMemory server_pem = {
  12607. server_cert_pem.c_str(),
  12608. server_cert_pem.size(),
  12609. server_key_pem.c_str(),
  12610. server_key_pem.size(),
  12611. client_ca_pem.c_str(),
  12612. client_ca_pem.size(),
  12613. nullptr // no password for server key
  12614. };
  12615. SSLServer svr(server_pem);
  12616. ASSERT_TRUE(svr.is_valid());
  12617. // No SSL error should be recorded for valid setup
  12618. EXPECT_EQ(0, svr.ssl_last_error());
  12619. // Set up server endpoints
  12620. svr.Get("/test-pem-ca", [&](const Request & /*req*/, Response &res) {
  12621. res.set_content("ok", "text/plain");
  12622. });
  12623. // Start server in a thread
  12624. auto server_thread = thread([&]() { svr.listen(HOST, PORT); });
  12625. svr.wait_until_ready();
  12626. // Connect with client certificate (using constructor with paths)
  12627. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  12628. cli.enable_server_certificate_verification(false);
  12629. auto res = cli.Get("/test-pem-ca");
  12630. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12631. EXPECT_EQ(200, res->status);
  12632. EXPECT_EQ("ok", res->body);
  12633. svr.stop();
  12634. server_thread.join();
  12635. }
  12636. #endif
  12637. #ifdef _WIN32
  12638. TEST(CleanupTest, WSACleanup) {
  12639. int ret = WSACleanup();
  12640. ASSERT_EQ(0, ret);
  12641. }
  12642. #endif
  12643. #ifndef CPPHTTPLIB_SSL_ENABLED
  12644. TEST(NoSSLSupport, SimpleInterface) {
  12645. ASSERT_ANY_THROW(Client cli("https://yahoo.com"));
  12646. }
  12647. #endif
  12648. #ifndef CPPHTTPLIB_NO_EXCEPTIONS
  12649. TEST(InvalidScheme, SimpleInterface) {
  12650. ASSERT_ANY_THROW(Client cli("scheme://yahoo.com"));
  12651. }
  12652. #endif
  12653. TEST(NoScheme, SimpleInterface) {
  12654. Client cli("yahoo.com:80");
  12655. ASSERT_TRUE(cli.is_valid());
  12656. }
  12657. TEST(SendAPI, SimpleInterface_Online) {
  12658. Client cli("http://yahoo.com");
  12659. Request req;
  12660. req.method = "GET";
  12661. req.path = "/";
  12662. auto res = cli.send(req);
  12663. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12664. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12665. }
  12666. TEST(SendAPI, WithParamsInRequest) {
  12667. Server svr;
  12668. svr.Get("/", [&](const Request &req, Response & /*res*/) {
  12669. EXPECT_TRUE(req.has_param("test"));
  12670. EXPECT_EQ("test_value", req.get_param_value("test"));
  12671. });
  12672. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  12673. auto se = detail::scope_exit([&] {
  12674. svr.stop();
  12675. t.join();
  12676. ASSERT_FALSE(svr.is_running());
  12677. });
  12678. svr.wait_until_ready();
  12679. Client cli(HOST, PORT);
  12680. {
  12681. Request req;
  12682. req.method = "GET";
  12683. req.path = "/";
  12684. req.params.emplace("test", "test_value");
  12685. auto res = cli.send(req);
  12686. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12687. }
  12688. {
  12689. auto res = cli.Get("/", {{"test", "test_value"}}, Headers{});
  12690. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12691. }
  12692. }
  12693. TEST(ClientImplMethods, GetSocketTest) {
  12694. httplib::Server svr;
  12695. svr.Get("/", [&](const httplib::Request & /*req*/, httplib::Response &res) {
  12696. res.status = StatusCode::OK_200;
  12697. });
  12698. auto port = svr.bind_to_any_port("127.0.0.1");
  12699. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  12700. auto se = detail::scope_exit([&] {
  12701. svr.stop();
  12702. thread.join();
  12703. ASSERT_FALSE(svr.is_running());
  12704. });
  12705. svr.wait_until_ready();
  12706. {
  12707. httplib::Client cli("127.0.0.1", port);
  12708. cli.set_keep_alive(true);
  12709. // Use the behavior of cpp-httplib of opening the connection
  12710. // only when the first request happens. If that changes,
  12711. // this test would be obsolete.
  12712. EXPECT_EQ(cli.socket(), INVALID_SOCKET);
  12713. // This also implicitly tests the server. But other tests would fail much
  12714. // earlier than this one to be considered.
  12715. auto res = cli.Get("/");
  12716. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12717. EXPECT_EQ(StatusCode::OK_200, res->status);
  12718. ASSERT_TRUE(cli.socket() != INVALID_SOCKET);
  12719. }
  12720. }
  12721. #ifdef CPPHTTPLIB_SSL_ENABLED
  12722. TEST(YahooRedirectTest2, SimpleInterface_Online) {
  12723. Client cli("http://yahoo.com");
  12724. auto res = cli.Get("/");
  12725. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12726. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12727. cli.set_follow_location(true);
  12728. res = cli.Get("/");
  12729. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12730. EXPECT_EQ(StatusCode::OK_200, res->status);
  12731. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12732. }
  12733. TEST(YahooRedirectTest3, SimpleInterface_Online) {
  12734. Client cli("https://yahoo.com");
  12735. auto res = cli.Get("/");
  12736. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12737. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12738. cli.set_follow_location(true);
  12739. res = cli.Get("/");
  12740. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12741. EXPECT_EQ(StatusCode::OK_200, res->status);
  12742. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12743. }
  12744. TEST(YahooRedirectTest3, NewResultInterface_Online) {
  12745. Client cli("https://yahoo.com");
  12746. auto res = cli.Get("/");
  12747. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12748. ASSERT_FALSE(!res);
  12749. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12750. ASSERT_FALSE(res == nullptr);
  12751. ASSERT_TRUE(res != nullptr);
  12752. EXPECT_EQ(Error::Success, res.error());
  12753. EXPECT_EQ(StatusCode::MovedPermanently_301, res.value().status);
  12754. EXPECT_EQ(StatusCode::MovedPermanently_301, (*res).status);
  12755. EXPECT_EQ(StatusCode::MovedPermanently_301, res->status);
  12756. cli.set_follow_location(true);
  12757. res = cli.Get("/");
  12758. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12759. EXPECT_EQ(Error::Success, res.error());
  12760. EXPECT_EQ(StatusCode::OK_200, res.value().status);
  12761. EXPECT_EQ(StatusCode::OK_200, (*res).status);
  12762. EXPECT_EQ(StatusCode::OK_200, res->status);
  12763. EXPECT_EQ("https://www.yahoo.com/", res->location);
  12764. }
  12765. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  12766. TEST(DecodeWithChunkedEncoding, BrotliEncoding_Online) {
  12767. Client cli("https://cdnjs.cloudflare.com");
  12768. auto res = cli.Get("/ajax/libs/jquery/3.5.1/jquery.js",
  12769. Headers{{"Accept-Encoding", "br"}});
  12770. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12771. EXPECT_EQ(StatusCode::OK_200, res->status);
  12772. EXPECT_EQ(287630U, res->body.size());
  12773. EXPECT_EQ("application/javascript; charset=utf-8",
  12774. res->get_header_value("Content-Type"));
  12775. }
  12776. #endif
  12777. // Previously "https://nghttp2.org" "/httpbin/redirect-to"
  12778. #undef REDIR_HOST // Silence compiler warning
  12779. #define REDIR_HOST "https://httpbingo.org"
  12780. TEST(HttpsToHttpRedirectTest, SimpleInterface_Online) {
  12781. Client cli(REDIR_HOST);
  12782. cli.set_follow_location(true);
  12783. auto res =
  12784. cli.Get(REDIR_PATH "?url=http%3A%2F%2Fexample.com&status_code=302");
  12785. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12786. EXPECT_EQ(StatusCode::OK_200, res->status);
  12787. }
  12788. TEST(HttpsToHttpRedirectTest2, SimpleInterface_Online) {
  12789. Client cli(REDIR_HOST);
  12790. cli.set_follow_location(true);
  12791. Params params;
  12792. params.emplace("url", "http://example.com");
  12793. params.emplace("status_code", "302");
  12794. auto res = cli.Get(REDIR_PATH, params, Headers{});
  12795. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12796. EXPECT_EQ(StatusCode::OK_200, res->status);
  12797. }
  12798. TEST(HttpsToHttpRedirectTest3, SimpleInterface_Online) {
  12799. Client cli(REDIR_HOST);
  12800. cli.set_follow_location(true);
  12801. Params params;
  12802. params.emplace("url", "http://example.com");
  12803. auto res = cli.Get(REDIR_PATH "?status_code=302", params, Headers{});
  12804. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12805. EXPECT_EQ(StatusCode::OK_200, res->status);
  12806. }
  12807. TEST(HttpToHttpsRedirectTest, CertFile) {
  12808. auto ssl_port = PORT + 1;
  12809. Server svr;
  12810. ASSERT_TRUE(svr.is_valid());
  12811. svr.Get("/index", [&](const Request &, Response &res) {
  12812. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12813. "/index");
  12814. svr.stop();
  12815. });
  12816. SSLServer ssl_svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12817. ASSERT_TRUE(ssl_svr.is_valid());
  12818. ssl_svr.Get("/index", [&](const Request &, Response &res) {
  12819. res.set_content("test", "text/plain");
  12820. ssl_svr.stop();
  12821. });
  12822. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12823. thread t2 =
  12824. thread([&]() { ASSERT_TRUE(ssl_svr.listen("127.0.0.1", ssl_port)); });
  12825. auto se = detail::scope_exit([&] {
  12826. t2.join();
  12827. t.join();
  12828. ASSERT_FALSE(svr.is_running());
  12829. });
  12830. svr.wait_until_ready();
  12831. ssl_svr.wait_until_ready();
  12832. Client cli("127.0.0.1", PORT);
  12833. cli.set_ca_cert_path(SERVER_CERT2_FILE);
  12834. cli.enable_server_certificate_verification(true);
  12835. cli.set_follow_location(true);
  12836. cli.set_connection_timeout(30);
  12837. auto res = cli.Get("/index");
  12838. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12839. ASSERT_EQ(StatusCode::OK_200, res->status);
  12840. }
  12841. TEST(SSLClientRedirectTest, CertFile) {
  12842. auto ssl_port = PORT + 1;
  12843. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12844. ASSERT_TRUE(ssl_svr1.is_valid());
  12845. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12846. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12847. "/index");
  12848. ssl_svr1.stop();
  12849. });
  12850. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12851. ASSERT_TRUE(ssl_svr2.is_valid());
  12852. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12853. res.set_content("test", "text/plain");
  12854. ssl_svr2.stop();
  12855. });
  12856. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12857. thread t2 =
  12858. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12859. auto se = detail::scope_exit([&] {
  12860. t2.join();
  12861. t.join();
  12862. ASSERT_FALSE(ssl_svr1.is_running());
  12863. });
  12864. ssl_svr1.wait_until_ready();
  12865. ssl_svr2.wait_until_ready();
  12866. SSLClient cli("127.0.0.1", PORT);
  12867. std::string cert;
  12868. read_file(SERVER_CERT2_FILE, cert);
  12869. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12870. cli.enable_server_certificate_verification(true);
  12871. cli.set_follow_location(true);
  12872. cli.set_connection_timeout(30);
  12873. auto res = cli.Get("/index");
  12874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12875. ASSERT_EQ(StatusCode::OK_200, res->status);
  12876. }
  12877. #endif
  12878. #ifdef CPPHTTPLIB_SSL_ENABLED
  12879. // Test that set_ca_cert_store() skips system certs (consistent with
  12880. // set_ca_cert_path behavior). When a custom cert store is set, only those certs
  12881. // should be trusted - system certs should NOT be loaded.
  12882. TEST(SSLClientTest, SetCaCertStoreSkipsSystemCerts_Online) {
  12883. // Load a specific cert that is NOT a system CA cert
  12884. std::string cert;
  12885. read_file(SERVER_CERT2_FILE, cert);
  12886. SSLClient cli("google.com");
  12887. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12888. cli.enable_server_certificate_verification(true);
  12889. // This should FAIL because:
  12890. // 1. We loaded only SERVER_CERT2 (a test cert, not a CA for google.com)
  12891. // 2. System certs should NOT be loaded when custom store is set
  12892. // If system certs WERE loaded, this would succeed
  12893. auto res = cli.Get("/");
  12894. ASSERT_FALSE(res);
  12895. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12896. }
  12897. // Same as above, but through the native store handle path. Regression test:
  12898. // set_ca_cert_store() used to leave no trace on the client, so load_certs()
  12899. // merged system certs into the user-provided store.
  12900. TEST(SSLClientTest, SetCaCertStoreNativeSkipsSystemCerts_Online) {
  12901. std::string cert;
  12902. read_file(SERVER_CERT2_FILE, cert);
  12903. SSLClient cli("google.com");
  12904. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12905. cli.enable_server_certificate_verification(true);
  12906. auto res = cli.Get("/");
  12907. ASSERT_FALSE(res);
  12908. EXPECT_EQ(Error::SSLServerVerification, res.error());
  12909. }
  12910. // A custom store set via the native handle must still verify a server whose
  12911. // cert it does contain.
  12912. TEST(SSLClientTest, SetCaCertStoreNativeVerifiesLocalServer) {
  12913. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12914. ASSERT_TRUE(svr.is_valid());
  12915. svr.Get("/test", [&](const Request &, Response &res) {
  12916. res.set_content("test", "text/plain");
  12917. });
  12918. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12919. auto se = detail::scope_exit([&] {
  12920. svr.stop();
  12921. t.join();
  12922. ASSERT_FALSE(svr.is_running());
  12923. });
  12924. svr.wait_until_ready();
  12925. SSLClient cli("127.0.0.1", PORT);
  12926. std::string cert;
  12927. read_file(SERVER_CERT2_FILE, cert);
  12928. cli.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  12929. cli.enable_server_certificate_verification(true);
  12930. cli.set_connection_timeout(30);
  12931. auto res = cli.Get("/test");
  12932. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12933. ASSERT_EQ(StatusCode::OK_200, res->status);
  12934. }
  12935. // CA certs loaded through the universal Client must be transferred to the
  12936. // client created internally for following an HTTPS redirect. Regression test:
  12937. // Client::load_ca_cert_store() used to bypass the PEM-based path that stores
  12938. // the CA data for redirect transfer.
  12939. TEST(UniversalClientRedirectTest, LoadCaCertStore) {
  12940. auto ssl_port = PORT + 1;
  12941. SSLServer ssl_svr1(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12942. ASSERT_TRUE(ssl_svr1.is_valid());
  12943. ssl_svr1.Get("/index", [&](const Request &, Response &res) {
  12944. res.set_redirect("https://127.0.0.1:" + std::to_string(ssl_port) +
  12945. "/index");
  12946. });
  12947. SSLServer ssl_svr2(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12948. ASSERT_TRUE(ssl_svr2.is_valid());
  12949. ssl_svr2.Get("/index", [&](const Request &, Response &res) {
  12950. res.set_content("test", "text/plain");
  12951. });
  12952. thread t = thread([&]() { ASSERT_TRUE(ssl_svr1.listen("127.0.0.1", PORT)); });
  12953. thread t2 =
  12954. thread([&]() { ASSERT_TRUE(ssl_svr2.listen("127.0.0.1", ssl_port)); });
  12955. auto se = detail::scope_exit([&] {
  12956. ssl_svr2.stop();
  12957. ssl_svr1.stop();
  12958. t2.join();
  12959. t.join();
  12960. ASSERT_FALSE(ssl_svr1.is_running());
  12961. });
  12962. ssl_svr1.wait_until_ready();
  12963. ssl_svr2.wait_until_ready();
  12964. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  12965. std::string cert;
  12966. read_file(SERVER_CERT2_FILE, cert);
  12967. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12968. cli.enable_server_certificate_verification(true);
  12969. cli.set_follow_location(true);
  12970. cli.set_connection_timeout(30);
  12971. auto res = cli.Get("/index");
  12972. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12973. ASSERT_EQ(StatusCode::OK_200, res->status);
  12974. }
  12975. // enable_system_ca(true) loads system CA certs in addition to a custom CA,
  12976. // so a host signed by a system CA verifies even though a custom CA is set
  12977. TEST(SSLClientTest, EnableSystemCaWithCustomCa_Online) {
  12978. std::string cert;
  12979. read_file(SERVER_CERT2_FILE, cert);
  12980. SSLClient cli("google.com");
  12981. cli.load_ca_cert_store(cert.c_str(), cert.size());
  12982. cli.enable_system_ca(true);
  12983. cli.enable_server_certificate_verification(true);
  12984. auto res = cli.Get("/");
  12985. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  12986. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  12987. }
  12988. // The custom CA remains effective when combined with the system CA
  12989. TEST(SSLClientTest, EnableSystemCaCustomCaVerifiesLocalServer) {
  12990. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  12991. ASSERT_TRUE(svr.is_valid());
  12992. svr.Get("/test", [&](const Request &, Response &res) {
  12993. res.set_content("test", "text/plain");
  12994. });
  12995. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  12996. auto se = detail::scope_exit([&] {
  12997. svr.stop();
  12998. t.join();
  12999. ASSERT_FALSE(svr.is_running());
  13000. });
  13001. svr.wait_until_ready();
  13002. SSLClient cli("127.0.0.1", PORT);
  13003. std::string cert;
  13004. read_file(SERVER_CERT2_FILE, cert);
  13005. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13006. cli.enable_system_ca(true);
  13007. cli.enable_server_certificate_verification(true);
  13008. cli.set_connection_timeout(30);
  13009. auto res = cli.Get("/test");
  13010. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13011. ASSERT_EQ(StatusCode::OK_200, res->status);
  13012. }
  13013. // Regression test: for IP hosts the Mbed TLS and wolfSSL backends used to
  13014. // skip chain verification entirely (only the certificate identity was
  13015. // checked), so a server presenting an untrusted certificate with a matching
  13016. // IP SAN was accepted. The chain must be validated for IP hosts too.
  13017. TEST(SSLClientTest, IpHostUntrustedChainFails) {
  13018. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13019. ASSERT_TRUE(svr.is_valid());
  13020. svr.Get("/test", [&](const Request &, Response &res) {
  13021. res.set_content("test", "text/plain");
  13022. });
  13023. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13024. auto se = detail::scope_exit([&] {
  13025. svr.stop();
  13026. t.join();
  13027. ASSERT_FALSE(svr.is_running());
  13028. });
  13029. svr.wait_until_ready();
  13030. SSLClient cli("127.0.0.1", PORT);
  13031. std::string cert;
  13032. // A trusted CA that did not sign the server certificate. The server cert
  13033. // (cert2) carries the matching IP SAN, so only chain validation can reject
  13034. // this connection.
  13035. read_file(CLIENT_CA_CERT_FILE, cert);
  13036. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13037. cli.enable_server_certificate_verification(true);
  13038. cli.set_connection_timeout(30);
  13039. auto res = cli.Get("/test");
  13040. ASSERT_FALSE(res);
  13041. }
  13042. // enable_system_ca(false) prevents system CA loading entirely
  13043. TEST(SSLClientTest, DisableSystemCa_Online) {
  13044. SSLClient cli("google.com");
  13045. cli.enable_system_ca(false);
  13046. cli.enable_server_certificate_verification(true);
  13047. auto res = cli.Get("/");
  13048. ASSERT_FALSE(res);
  13049. // OpenSSL reports a verification failure; Mbed TLS fails the handshake
  13050. // itself when the CA chain is empty
  13051. EXPECT_TRUE(res.error() == Error::SSLServerVerification ||
  13052. res.error() == Error::SSLConnection);
  13053. }
  13054. // The universal Client forwards enable_system_ca()
  13055. TEST(UniversalClientTest, EnableSystemCaWithCustomCa_Online) {
  13056. std::string cert;
  13057. read_file(SERVER_CERT2_FILE, cert);
  13058. Client cli("https://google.com");
  13059. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13060. cli.enable_system_ca(true);
  13061. cli.enable_server_certificate_verification(true);
  13062. auto res = cli.Get("/");
  13063. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13064. ASSERT_EQ(StatusCode::MovedPermanently_301, res->status);
  13065. }
  13066. // The system CA policy must carry over to the client created internally for
  13067. // following a cross-host HTTPS redirect
  13068. TEST(UniversalClientRedirectTest, EnableSystemCaCarriesOver_Online) {
  13069. SSLServer svr(SERVER_CERT2_FILE, SERVER_PRIVATE_KEY_FILE);
  13070. ASSERT_TRUE(svr.is_valid());
  13071. svr.Get("/index", [&](const Request &, Response &res) {
  13072. res.set_redirect("https://www.google.com/");
  13073. });
  13074. thread t = thread([&]() { ASSERT_TRUE(svr.listen("127.0.0.1", PORT)); });
  13075. auto se = detail::scope_exit([&] {
  13076. svr.stop();
  13077. t.join();
  13078. ASSERT_FALSE(svr.is_running());
  13079. });
  13080. svr.wait_until_ready();
  13081. Client cli("https://127.0.0.1:" + std::to_string(PORT));
  13082. std::string cert;
  13083. read_file(SERVER_CERT2_FILE, cert);
  13084. cli.load_ca_cert_store(cert.c_str(), cert.size());
  13085. cli.enable_system_ca(true);
  13086. cli.enable_server_certificate_verification(true);
  13087. cli.set_follow_location(true);
  13088. cli.set_connection_timeout(30);
  13089. // Receiving any response proves the redirect client completed the TLS
  13090. // handshake with a system-CA-signed host
  13091. auto res = cli.Get("/index");
  13092. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13093. }
  13094. TEST(MultipartFormDataTest, LargeData) {
  13095. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13096. svr.Post("/post", [&](const Request &req, Response & /*res*/,
  13097. const ContentReader &content_reader) {
  13098. if (req.is_multipart_form_data()) {
  13099. std::vector<FormData> items;
  13100. content_reader(
  13101. [&](const FormData &file) {
  13102. items.push_back(file);
  13103. return true;
  13104. },
  13105. [&](const char *data, size_t data_length) {
  13106. items.back().content.append(data, data_length);
  13107. return true;
  13108. });
  13109. EXPECT_TRUE(std::string(items[0].name) == "document");
  13110. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13111. EXPECT_TRUE(items[0].filename == "2MB_data");
  13112. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13113. EXPECT_TRUE(items[1].name == "hello");
  13114. EXPECT_TRUE(items[1].content == "world");
  13115. EXPECT_TRUE(items[1].filename == "");
  13116. EXPECT_TRUE(items[1].content_type == "");
  13117. } else {
  13118. std::string body;
  13119. content_reader([&](const char *data, size_t data_length) {
  13120. body.append(data, data_length);
  13121. return true;
  13122. });
  13123. }
  13124. });
  13125. auto port = svr.bind_to_any_port(HOST);
  13126. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13127. auto se = detail::scope_exit([&] {
  13128. svr.stop();
  13129. t.join();
  13130. ASSERT_FALSE(svr.is_running());
  13131. });
  13132. svr.wait_until_ready();
  13133. {
  13134. std::string data(1024 * 1024 * 2, '.');
  13135. std::stringstream buffer;
  13136. buffer << data;
  13137. SSLClient cli(HOST, port);
  13138. cli.enable_server_certificate_verification(false);
  13139. UploadFormDataItems items{
  13140. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13141. {"hello", "world", "", ""},
  13142. };
  13143. auto res = cli.Post("/post", items);
  13144. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13145. ASSERT_EQ(StatusCode::OK_200, res->status);
  13146. }
  13147. }
  13148. TEST(MultipartFormDataTest, DataProviderItems) {
  13149. std::random_device seed_gen;
  13150. std::mt19937 random(seed_gen());
  13151. std::string rand1;
  13152. rand1.resize(1000);
  13153. std::generate(rand1.begin(), rand1.end(), [&]() { return random(); });
  13154. std::string rand2;
  13155. rand2.resize(3000);
  13156. std::generate(rand2.begin(), rand2.end(), [&]() { return random(); });
  13157. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13158. svr.Post("/post-none", [&](const Request &req, Response & /*res*/,
  13159. const ContentReader &content_reader) {
  13160. ASSERT_FALSE(req.is_multipart_form_data());
  13161. std::string body;
  13162. content_reader([&](const char *data, size_t data_length) {
  13163. body.append(data, data_length);
  13164. return true;
  13165. });
  13166. EXPECT_EQ(body, "");
  13167. });
  13168. svr.Post("/post-items", [&](const Request &req, Response & /*res*/,
  13169. const ContentReader &content_reader) {
  13170. ASSERT_TRUE(req.is_multipart_form_data());
  13171. std::vector<FormData> items;
  13172. content_reader(
  13173. [&](const FormData &file) {
  13174. items.push_back(file);
  13175. return true;
  13176. },
  13177. [&](const char *data, size_t data_length) {
  13178. items.back().content.append(data, data_length);
  13179. return true;
  13180. });
  13181. ASSERT_TRUE(items.size() == 2);
  13182. EXPECT_EQ(std::string(items[0].name), "name1");
  13183. EXPECT_EQ(items[0].content, "Testing123");
  13184. EXPECT_EQ(items[0].filename, "filename1");
  13185. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13186. EXPECT_EQ(items[1].name, "name2");
  13187. EXPECT_EQ(items[1].content, "Testing456");
  13188. EXPECT_EQ(items[1].filename, "");
  13189. EXPECT_EQ(items[1].content_type, "");
  13190. });
  13191. svr.Post("/post-providers", [&](const Request &req, Response & /*res*/,
  13192. const ContentReader &content_reader) {
  13193. ASSERT_TRUE(req.is_multipart_form_data());
  13194. std::vector<FormData> items;
  13195. content_reader(
  13196. [&](const FormData &file) {
  13197. items.push_back(file);
  13198. return true;
  13199. },
  13200. [&](const char *data, size_t data_length) {
  13201. items.back().content.append(data, data_length);
  13202. return true;
  13203. });
  13204. ASSERT_TRUE(items.size() == 2);
  13205. EXPECT_EQ(items[0].name, "name3");
  13206. EXPECT_EQ(items[0].content, rand1);
  13207. EXPECT_EQ(items[0].filename, "filename3");
  13208. EXPECT_EQ(items[0].content_type, "");
  13209. EXPECT_EQ(items[1].name, "name4");
  13210. EXPECT_EQ(items[1].content, rand2);
  13211. EXPECT_EQ(items[1].filename, "filename4");
  13212. EXPECT_EQ(items[1].content_type, "");
  13213. });
  13214. svr.Post("/post-both", [&](const Request &req, Response & /*res*/,
  13215. const ContentReader &content_reader) {
  13216. ASSERT_TRUE(req.is_multipart_form_data());
  13217. std::vector<FormData> items;
  13218. content_reader(
  13219. [&](const FormData &file) {
  13220. items.push_back(file);
  13221. return true;
  13222. },
  13223. [&](const char *data, size_t data_length) {
  13224. items.back().content.append(data, data_length);
  13225. return true;
  13226. });
  13227. ASSERT_TRUE(items.size() == 4);
  13228. EXPECT_EQ(std::string(items[0].name), "name1");
  13229. EXPECT_EQ(items[0].content, "Testing123");
  13230. EXPECT_EQ(items[0].filename, "filename1");
  13231. EXPECT_EQ(items[0].content_type, "application/octet-stream");
  13232. EXPECT_EQ(items[1].name, "name2");
  13233. EXPECT_EQ(items[1].content, "Testing456");
  13234. EXPECT_EQ(items[1].filename, "");
  13235. EXPECT_EQ(items[1].content_type, "");
  13236. EXPECT_EQ(items[2].name, "name3");
  13237. EXPECT_EQ(items[2].content, rand1);
  13238. EXPECT_EQ(items[2].filename, "filename3");
  13239. EXPECT_EQ(items[2].content_type, "");
  13240. EXPECT_EQ(items[3].name, "name4");
  13241. EXPECT_EQ(items[3].content, rand2);
  13242. EXPECT_EQ(items[3].filename, "filename4");
  13243. EXPECT_EQ(items[3].content_type, "");
  13244. });
  13245. auto port = svr.bind_to_any_port("localhost");
  13246. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13247. auto se = detail::scope_exit([&] {
  13248. svr.stop();
  13249. t.join();
  13250. ASSERT_FALSE(svr.is_running());
  13251. });
  13252. svr.wait_until_ready();
  13253. {
  13254. SSLClient cli("localhost", port);
  13255. cli.enable_server_certificate_verification(false);
  13256. UploadFormDataItems items{
  13257. {"name1", "Testing123", "filename1", "application/octet-stream"},
  13258. {"name2", "Testing456", "", ""}, // not a file
  13259. };
  13260. {
  13261. auto res = cli.Post("/post-none", {}, {}, {});
  13262. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13263. ASSERT_EQ(StatusCode::OK_200, res->status);
  13264. }
  13265. FormDataProviderItems providers;
  13266. {
  13267. auto res =
  13268. cli.Post("/post-items", {}, items, providers); // empty providers
  13269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13270. ASSERT_EQ(StatusCode::OK_200, res->status);
  13271. }
  13272. providers.push_back({"name3",
  13273. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13274. // test the offset is given correctly at each step
  13275. if (!offset)
  13276. sink.os.write(rand1.data(), 30);
  13277. else if (offset == 30)
  13278. sink.os.write(rand1.data() + 30, 300);
  13279. else if (offset == 330)
  13280. sink.os.write(rand1.data() + 330, 670);
  13281. else if (offset == rand1.size())
  13282. sink.done();
  13283. return true;
  13284. },
  13285. "filename3",
  13286. {}});
  13287. providers.push_back({"name4",
  13288. [&](size_t offset, httplib::DataSink &sink) -> bool {
  13289. // test the offset is given correctly at each step
  13290. if (!offset)
  13291. sink.os.write(rand2.data(), 2000);
  13292. else if (offset == 2000)
  13293. sink.os.write(rand2.data() + 2000, 1);
  13294. else if (offset == 2001)
  13295. sink.os.write(rand2.data() + 2001, 999);
  13296. else if (offset == rand2.size())
  13297. sink.done();
  13298. return true;
  13299. },
  13300. "filename4",
  13301. {}});
  13302. {
  13303. auto res = cli.Post("/post-providers", {}, {}, providers);
  13304. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13305. ASSERT_EQ(StatusCode::OK_200, res->status);
  13306. }
  13307. {
  13308. auto res = cli.Post("/post-both", {}, items, providers);
  13309. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13310. ASSERT_EQ(StatusCode::OK_200, res->status);
  13311. }
  13312. }
  13313. }
  13314. TEST(MultipartFormDataTest, BadHeader) {
  13315. Server svr;
  13316. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13317. res.set_content("ok", "text/plain");
  13318. });
  13319. thread t = thread([&] { svr.listen(HOST, PORT); });
  13320. auto se = detail::scope_exit([&] {
  13321. svr.stop();
  13322. t.join();
  13323. ASSERT_FALSE(svr.is_running());
  13324. });
  13325. svr.wait_until_ready();
  13326. const std::string body =
  13327. "This is the preamble. It is to be ignored, though it\r\n"
  13328. "is a handy place for composition agents to include an\r\n"
  13329. "explanatory note to non-MIME conformant readers.\r\n"
  13330. "\r\n"
  13331. "\r\n"
  13332. "--simple boundary\r\n"
  13333. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13334. ": BAD...\r\n"
  13335. "\r\n"
  13336. "value1\r\n"
  13337. "--simple boundary\r\n"
  13338. "Content-Disposition: form-data; name=\"field2\"; "
  13339. "filename=\"example.txt\"\r\n"
  13340. "\r\n"
  13341. "value2\r\n"
  13342. "--simple boundary--\r\n"
  13343. "This is the epilogue. It is also to be ignored.\r\n";
  13344. std::string content_type =
  13345. R"(multipart/form-data; boundary="simple boundary")";
  13346. Client cli(HOST, PORT);
  13347. auto res = cli.Post("/post", body, content_type.c_str());
  13348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13349. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  13350. }
  13351. TEST(MultipartFormDataTest, WithPreamble) {
  13352. Server svr;
  13353. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  13354. res.set_content("ok", "text/plain");
  13355. });
  13356. thread t = thread([&] { svr.listen(HOST, PORT); });
  13357. auto se = detail::scope_exit([&] {
  13358. svr.stop();
  13359. t.join();
  13360. ASSERT_FALSE(svr.is_running());
  13361. });
  13362. svr.wait_until_ready();
  13363. const std::string body =
  13364. "This is the preamble. It is to be ignored, though it\r\n"
  13365. "is a handy place for composition agents to include an\r\n"
  13366. "explanatory note to non-MIME conformant readers.\r\n"
  13367. "\r\n"
  13368. "\r\n"
  13369. "--simple boundary\r\n"
  13370. "Content-Disposition: form-data; name=\"field1\"\r\n"
  13371. "\r\n"
  13372. "value1\r\n"
  13373. "--simple boundary\r\n"
  13374. "Content-Disposition: form-data; name=\"field2\"; "
  13375. "filename=\"example.txt\"\r\n"
  13376. "\r\n"
  13377. "value2\r\n"
  13378. "--simple boundary--\r\n"
  13379. "This is the epilogue. It is also to be ignored.\r\n";
  13380. std::string content_type =
  13381. R"(multipart/form-data; boundary="simple boundary")";
  13382. Client cli(HOST, PORT);
  13383. auto res = cli.Post("/post", body, content_type.c_str());
  13384. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13385. EXPECT_EQ(StatusCode::OK_200, res->status);
  13386. }
  13387. TEST(MultipartFormDataTest, PostCustomBoundary) {
  13388. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13389. svr.Post("/post_customboundary", [&](const Request &req, Response & /*res*/,
  13390. const ContentReader &content_reader) {
  13391. if (req.is_multipart_form_data()) {
  13392. std::vector<FormData> items;
  13393. content_reader(
  13394. [&](const FormData &file) {
  13395. items.push_back(file);
  13396. return true;
  13397. },
  13398. [&](const char *data, size_t data_length) {
  13399. items.back().content.append(data, data_length);
  13400. return true;
  13401. });
  13402. EXPECT_TRUE(std::string(items[0].name) == "document");
  13403. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13404. EXPECT_TRUE(items[0].filename == "2MB_data");
  13405. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13406. EXPECT_TRUE(items[1].name == "hello");
  13407. EXPECT_TRUE(items[1].content == "world");
  13408. EXPECT_TRUE(items[1].filename == "");
  13409. EXPECT_TRUE(items[1].content_type == "");
  13410. } else {
  13411. std::string body;
  13412. content_reader([&](const char *data, size_t data_length) {
  13413. body.append(data, data_length);
  13414. return true;
  13415. });
  13416. }
  13417. });
  13418. auto port = svr.bind_to_any_port("localhost");
  13419. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13420. auto se = detail::scope_exit([&] {
  13421. svr.stop();
  13422. t.join();
  13423. ASSERT_FALSE(svr.is_running());
  13424. });
  13425. svr.wait_until_ready();
  13426. {
  13427. std::string data(1024 * 1024 * 2, '.');
  13428. std::stringstream buffer;
  13429. buffer << data;
  13430. SSLClient cli("localhost", port);
  13431. cli.enable_server_certificate_verification(false);
  13432. UploadFormDataItems items{
  13433. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13434. {"hello", "world", "", ""},
  13435. };
  13436. auto res = cli.Post("/post_customboundary", {}, items, "abc-abc");
  13437. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13438. ASSERT_EQ(StatusCode::OK_200, res->status);
  13439. }
  13440. }
  13441. TEST(MultipartFormDataTest, PostInvalidBoundaryChars) {
  13442. std::string data(1024 * 1024 * 2, '&');
  13443. std::stringstream buffer;
  13444. buffer << data;
  13445. Client cli("https://localhost:8080");
  13446. UploadFormDataItems items{
  13447. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13448. {"hello", "world", "", ""},
  13449. };
  13450. for (const char &c : " \t\r\n") {
  13451. auto res =
  13452. cli.Post("/invalid_boundary", {}, items, string("abc123").append(1, c));
  13453. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13454. ASSERT_FALSE(res);
  13455. }
  13456. }
  13457. TEST(MultipartFormDataTest, PutFormData) {
  13458. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13459. svr.Put("/put", [&](const Request &req, const Response & /*res*/,
  13460. const ContentReader &content_reader) {
  13461. if (req.is_multipart_form_data()) {
  13462. std::vector<FormData> items;
  13463. content_reader(
  13464. [&](const FormData &file) {
  13465. items.push_back(file);
  13466. return true;
  13467. },
  13468. [&](const char *data, size_t data_length) {
  13469. items.back().content.append(data, data_length);
  13470. return true;
  13471. });
  13472. EXPECT_TRUE(std::string(items[0].name) == "document");
  13473. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13474. EXPECT_TRUE(items[0].filename == "2MB_data");
  13475. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13476. EXPECT_TRUE(items[1].name == "hello");
  13477. EXPECT_TRUE(items[1].content == "world");
  13478. EXPECT_TRUE(items[1].filename == "");
  13479. EXPECT_TRUE(items[1].content_type == "");
  13480. } else {
  13481. std::string body;
  13482. content_reader([&](const char *data, size_t data_length) {
  13483. body.append(data, data_length);
  13484. return true;
  13485. });
  13486. }
  13487. });
  13488. auto port = svr.bind_to_any_port("localhost");
  13489. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13490. auto se = detail::scope_exit([&] {
  13491. svr.stop();
  13492. t.join();
  13493. ASSERT_FALSE(svr.is_running());
  13494. });
  13495. svr.wait_until_ready();
  13496. {
  13497. std::string data(1024 * 1024 * 2, '&');
  13498. std::stringstream buffer;
  13499. buffer << data;
  13500. SSLClient cli("localhost", port);
  13501. cli.enable_server_certificate_verification(false);
  13502. UploadFormDataItems items{
  13503. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13504. {"hello", "world", "", ""},
  13505. };
  13506. auto res = cli.Put("/put", items);
  13507. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13508. ASSERT_EQ(StatusCode::OK_200, res->status);
  13509. }
  13510. }
  13511. TEST(MultipartFormDataTest, PutFormDataCustomBoundary) {
  13512. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  13513. svr.Put("/put_customboundary",
  13514. [&](const Request &req, const Response & /*res*/,
  13515. const ContentReader &content_reader) {
  13516. if (req.is_multipart_form_data()) {
  13517. std::vector<FormData> items;
  13518. content_reader(
  13519. [&](const FormData &file) {
  13520. items.push_back(file);
  13521. return true;
  13522. },
  13523. [&](const char *data, size_t data_length) {
  13524. items.back().content.append(data, data_length);
  13525. return true;
  13526. });
  13527. EXPECT_TRUE(std::string(items[0].name) == "document");
  13528. EXPECT_EQ(size_t(1024 * 1024 * 2), items[0].content.size());
  13529. EXPECT_TRUE(items[0].filename == "2MB_data");
  13530. EXPECT_TRUE(items[0].content_type == "application/octet-stream");
  13531. EXPECT_TRUE(items[1].name == "hello");
  13532. EXPECT_TRUE(items[1].content == "world");
  13533. EXPECT_TRUE(items[1].filename == "");
  13534. EXPECT_TRUE(items[1].content_type == "");
  13535. } else {
  13536. std::string body;
  13537. content_reader([&](const char *data, size_t data_length) {
  13538. body.append(data, data_length);
  13539. return true;
  13540. });
  13541. }
  13542. });
  13543. auto port = svr.bind_to_any_port("localhost");
  13544. auto t = std::thread([&]() { svr.listen_after_bind(); });
  13545. auto se = detail::scope_exit([&] {
  13546. svr.stop();
  13547. t.join();
  13548. ASSERT_FALSE(svr.is_running());
  13549. });
  13550. svr.wait_until_ready();
  13551. {
  13552. std::string data(1024 * 1024 * 2, '&');
  13553. std::stringstream buffer;
  13554. buffer << data;
  13555. SSLClient cli("localhost", port);
  13556. cli.enable_server_certificate_verification(false);
  13557. UploadFormDataItems items{
  13558. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13559. {"hello", "world", "", ""},
  13560. };
  13561. auto res = cli.Put("/put_customboundary", {}, items, "abc-abc_");
  13562. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13563. ASSERT_EQ(StatusCode::OK_200, res->status);
  13564. }
  13565. }
  13566. TEST(MultipartFormDataTest, PutInvalidBoundaryChars) {
  13567. std::string data(1024 * 1024 * 2, '&');
  13568. std::stringstream buffer;
  13569. buffer << data;
  13570. Client cli("https://localhost:8080");
  13571. cli.enable_server_certificate_verification(false);
  13572. UploadFormDataItems items{
  13573. {"document", buffer.str(), "2MB_data", "application/octet-stream"},
  13574. {"hello", "world", "", ""},
  13575. };
  13576. for (const char &c : " \t\r\n") {
  13577. auto res = cli.Put("/put", {}, items, string("abc123").append(1, c));
  13578. ASSERT_EQ(Error::UnsupportedMultipartBoundaryChars, res.error());
  13579. ASSERT_FALSE(res);
  13580. }
  13581. }
  13582. TEST(MultipartFormDataTest, AlternateFilename) {
  13583. auto handled = false;
  13584. Server svr;
  13585. svr.Post("/test", [&](const Request &req, Response &res) {
  13586. ASSERT_EQ(2u, req.form.files.size());
  13587. ASSERT_EQ(1u, req.form.fields.size());
  13588. // Test files
  13589. const auto &file1 = req.form.get_file("file1");
  13590. ASSERT_EQ("file1", file1.name);
  13591. ASSERT_EQ("A.txt", file1.filename);
  13592. ASSERT_EQ("text/plain", file1.content_type);
  13593. ASSERT_EQ("Content of a.txt.\r\n", file1.content);
  13594. const auto &file2 = req.form.get_file("file2");
  13595. ASSERT_EQ("file2", file2.name);
  13596. ASSERT_EQ("a.html", file2.filename);
  13597. ASSERT_EQ("text/html", file2.content_type);
  13598. ASSERT_EQ("<!DOCTYPE html><title>Content of a.html.</title>\r\n",
  13599. file2.content);
  13600. // Test text field
  13601. const auto &text = req.form.get_field("text");
  13602. ASSERT_EQ("text default", text);
  13603. res.set_content("ok", "text/plain");
  13604. handled = true;
  13605. });
  13606. thread t = thread([&] { svr.listen(HOST, PORT); });
  13607. auto se = detail::scope_exit([&] {
  13608. svr.stop();
  13609. t.join();
  13610. ASSERT_FALSE(svr.is_running());
  13611. ASSERT_TRUE(handled);
  13612. });
  13613. svr.wait_until_ready();
  13614. auto req = "POST /test HTTP/1.1\r\n"
  13615. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13616. "Content-Length: 399\r\n"
  13617. "\r\n"
  13618. "----------\r\n"
  13619. "Content-Disposition: form-data; name=\"text\"\r\n"
  13620. "\r\n"
  13621. "text default\r\n"
  13622. "----------\r\n"
  13623. "Content-Disposition: form-data; filename*=\"UTF-8''%41.txt\"; "
  13624. "filename=\"a.txt\"; name=\"file1\"\r\n"
  13625. "Content-Type: text/plain\r\n"
  13626. "\r\n"
  13627. "Content of a.txt.\r\n"
  13628. "\r\n"
  13629. "----------\r\n"
  13630. "Content-Disposition: form-data; name=\"file2\" ;filename = "
  13631. "\"a.html\"\r\n"
  13632. "Content-Type: text/html\r\n"
  13633. "\r\n"
  13634. "<!DOCTYPE html><title>Content of a.html.</title>\r\n"
  13635. "\r\n"
  13636. "------------\r\n";
  13637. ASSERT_TRUE(send_request(1, req));
  13638. }
  13639. TEST(MultipartFormDataTest, AlternateFilenameLongValueAndCaseInsensitive) {
  13640. auto handled = false;
  13641. Server svr;
  13642. svr.Post("/test", [&](const Request &req, Response &res) {
  13643. // Case-insensitive "utf-8''" prefix with a long value
  13644. const auto &file = req.form.get_file("file1");
  13645. ASSERT_EQ("file1", file.name);
  13646. // 8000 chars exercises both the Content-Disposition parser and the
  13647. // filename* parser near the CPPHTTPLIB_HEADER_MAX_LENGTH limit (8192).
  13648. // Prior to the fix, std::regex_match on this header would cause O(N)
  13649. // stack recursion in libstdc++, leading to SIGSEGV.
  13650. std::string expected_filename(8000, 'A');
  13651. ASSERT_EQ(expected_filename, file.filename);
  13652. res.set_content("ok", "text/plain");
  13653. handled = true;
  13654. });
  13655. thread t = thread([&] { svr.listen(HOST, PORT); });
  13656. auto se = detail::scope_exit([&] {
  13657. svr.stop();
  13658. t.join();
  13659. ASSERT_FALSE(svr.is_running());
  13660. ASSERT_TRUE(handled);
  13661. });
  13662. svr.wait_until_ready();
  13663. // Build body with a long filename* value using mixed-case prefix "Utf-8''"
  13664. // Regression test for GHSA-qq6v-r583-3h69
  13665. std::string long_filename(8000, 'A');
  13666. std::string body = "----------\r\n"
  13667. "Content-Disposition: form-data; name=\"file1\"; "
  13668. "filename*=\"Utf-8''" +
  13669. long_filename +
  13670. "\"\r\n"
  13671. "\r\n"
  13672. "hello\r\n"
  13673. "------------\r\n";
  13674. auto req = "POST /test HTTP/1.1\r\n"
  13675. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13676. "Content-Length: " +
  13677. std::to_string(body.size()) + "\r\n\r\n" + body;
  13678. ASSERT_TRUE(send_request(1, req));
  13679. }
  13680. TEST(MultipartFormDataTest, CloseDelimiterWithoutCRLF) {
  13681. auto handled = false;
  13682. Server svr;
  13683. svr.Post("/test", [&](const Request &req, Response &) {
  13684. ASSERT_EQ(2u, req.form.fields.size());
  13685. const auto &text1 = req.form.get_field("text1");
  13686. ASSERT_EQ("text1", text1);
  13687. const auto &text2 = req.form.get_field("text2");
  13688. ASSERT_EQ("text2", text2);
  13689. handled = true;
  13690. });
  13691. thread t = thread([&] { svr.listen(HOST, PORT); });
  13692. auto se = detail::scope_exit([&] {
  13693. svr.stop();
  13694. t.join();
  13695. ASSERT_FALSE(svr.is_running());
  13696. ASSERT_TRUE(handled);
  13697. });
  13698. svr.wait_until_ready();
  13699. auto req = "POST /test HTTP/1.1\r\n"
  13700. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13701. "Content-Length: 146\r\n"
  13702. "\r\n----------\r\n"
  13703. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13704. "\r\n"
  13705. "text1"
  13706. "\r\n----------\r\n"
  13707. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13708. "\r\n"
  13709. "text2"
  13710. "\r\n------------";
  13711. std::string response;
  13712. ASSERT_TRUE(send_request(1, req, &response));
  13713. ASSERT_EQ("200", response.substr(9, 3));
  13714. }
  13715. TEST(MultipartFormDataTest, ContentLength) {
  13716. auto handled = false;
  13717. Server svr;
  13718. svr.Post("/test", [&](const Request &req, Response &) {
  13719. ASSERT_EQ(2u, req.form.fields.size());
  13720. const auto &text1 = req.form.get_field("text1");
  13721. ASSERT_EQ("text1", text1);
  13722. const auto &text2 = req.form.get_field("text2");
  13723. ASSERT_EQ("text2", text2);
  13724. handled = true;
  13725. });
  13726. thread t = thread([&] { svr.listen(HOST, PORT); });
  13727. auto se = detail::scope_exit([&] {
  13728. svr.stop();
  13729. t.join();
  13730. ASSERT_FALSE(svr.is_running());
  13731. ASSERT_TRUE(handled);
  13732. });
  13733. svr.wait_until_ready();
  13734. auto req = "POST /test HTTP/1.1\r\n"
  13735. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13736. "Content-Length: 167\r\n"
  13737. "\r\n----------\r\n"
  13738. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13739. "Content-Length: 5\r\n"
  13740. "\r\n"
  13741. "text1"
  13742. "\r\n----------\r\n"
  13743. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13744. "\r\n"
  13745. "text2"
  13746. "\r\n------------\r\n";
  13747. std::string response;
  13748. ASSERT_TRUE(send_request(1, req, &response));
  13749. ASSERT_EQ("200", response.substr(9, 3));
  13750. }
  13751. TEST(MultipartFormDataTest, AccessPartHeaders) {
  13752. auto handled = false;
  13753. Server svr;
  13754. svr.Post("/test", [&](const Request &req, Response &) {
  13755. ASSERT_EQ(2u, req.form.fields.size());
  13756. const auto &text1 = req.form.get_field("text1");
  13757. ASSERT_EQ("text1", text1);
  13758. // TODO: Add header access for text fields if needed
  13759. const auto &text2 = req.form.get_field("text2");
  13760. ASSERT_EQ("text2", text2);
  13761. // TODO: Header access for text fields needs to be implemented
  13762. // auto &headers = it->second.headers;
  13763. // ASSERT_EQ(3U, headers.size());
  13764. // auto custom_header = headers.find("x-whatever");
  13765. // ASSERT_TRUE(custom_header != headers.end());
  13766. // ASSERT_NE("customvalue", custom_header->second);
  13767. // ASSERT_EQ("CustomValue", custom_header->second);
  13768. // ASSERT_TRUE(headers.find("X-Test") == headers.end()); // text1 header
  13769. handled = true;
  13770. });
  13771. thread t = thread([&] { svr.listen(HOST, PORT); });
  13772. auto se = detail::scope_exit([&] {
  13773. svr.stop();
  13774. t.join();
  13775. ASSERT_FALSE(svr.is_running());
  13776. ASSERT_TRUE(handled);
  13777. });
  13778. svr.wait_until_ready();
  13779. auto req = "POST /test HTTP/1.1\r\n"
  13780. "Content-Type: multipart/form-data;boundary=--------\r\n"
  13781. "Content-Length: 232\r\n"
  13782. "\r\n----------\r\n"
  13783. "Content-Disposition: form-data; name=\"text1\"\r\n"
  13784. "Content-Length: 5\r\n"
  13785. "X-Test: 1\r\n"
  13786. "\r\n"
  13787. "text1"
  13788. "\r\n----------\r\n"
  13789. "Content-Disposition: form-data; name=\"text2\"\r\n"
  13790. "Content-Type: text/plain\r\n"
  13791. "X-Whatever: CustomValue\r\n"
  13792. "\r\n"
  13793. "text2"
  13794. "\r\n------------\r\n"
  13795. "That should be disregarded. Not even read";
  13796. std::string response;
  13797. ASSERT_TRUE(send_request(1, req, &response));
  13798. ASSERT_EQ("200", response.substr(9, 3));
  13799. }
  13800. TEST(MultipartFormDataTest, LargeHeader) {
  13801. auto handled = false;
  13802. Server svr;
  13803. svr.Post("/test", [&](const Request &req, Response &) {
  13804. ASSERT_EQ(1u, req.form.fields.size());
  13805. const auto &text = req.form.get_field("name1");
  13806. ASSERT_EQ("text1", text);
  13807. handled = true;
  13808. });
  13809. thread t = thread([&] { svr.listen(HOST, PORT); });
  13810. auto se = detail::scope_exit([&] {
  13811. svr.stop();
  13812. t.join();
  13813. ASSERT_FALSE(svr.is_running());
  13814. ASSERT_TRUE(handled);
  13815. });
  13816. svr.wait_until_ready();
  13817. auto boundary = std::string("cpp-httplib-multipart-data");
  13818. std::string content = "--" + boundary +
  13819. "\r\n"
  13820. "Content-Disposition: form-data; name=\"name1\"\r\n"
  13821. "\r\n"
  13822. "text1\r\n"
  13823. "--" +
  13824. boundary + "--\r\n";
  13825. std::string header_prefix = "POST /test HTTP/1.1\r\n"
  13826. "Content-Type: multipart/form-data;boundary=" +
  13827. boundary +
  13828. "\r\n"
  13829. "Content-Length: " +
  13830. std::to_string(content.size()) +
  13831. "\r\n"
  13832. "Dummy-Header: ";
  13833. std::string header_suffix = "\r\n"
  13834. "\r\n";
  13835. size_t read_buff_size = 1024u * 4; // SocketStream::read_buff_size_
  13836. size_t header_dummy_size =
  13837. read_buff_size -
  13838. (header_prefix.size() + header_suffix.size() + boundary.size() / 2);
  13839. auto header_dummy = std::string(header_dummy_size, '@');
  13840. auto req = header_prefix + header_dummy + header_suffix + content;
  13841. std::string response;
  13842. ASSERT_TRUE(send_request(1, req, &response));
  13843. ASSERT_EQ("200", response.substr(9, 3));
  13844. }
  13845. TEST(MultipartFormDataTest, UploadItemsHasContentLength) {
  13846. // Verify that Post(path, headers, UploadFormDataItems) sends Content-Length
  13847. // (not chunked Transfer-Encoding) after the streaming refactor.
  13848. auto handled = false;
  13849. Server svr;
  13850. svr.Post("/upload", [&](const Request &req, Response &res) {
  13851. auto cl_it = req.headers.find("Content-Length");
  13852. EXPECT_TRUE(cl_it != req.headers.end());
  13853. auto te_it = req.headers.find("Transfer-Encoding");
  13854. EXPECT_TRUE(te_it == req.headers.end());
  13855. EXPECT_EQ(2u, req.form.fields.size() + req.form.files.size());
  13856. res.set_content("ok", "text/plain");
  13857. handled = true;
  13858. });
  13859. auto port = svr.bind_to_any_port(HOST);
  13860. auto t = thread([&] { svr.listen_after_bind(); });
  13861. auto se = detail::scope_exit([&] {
  13862. svr.stop();
  13863. t.join();
  13864. ASSERT_FALSE(svr.is_running());
  13865. ASSERT_TRUE(handled);
  13866. });
  13867. svr.wait_until_ready();
  13868. UploadFormDataItems items = {
  13869. {"field1", "hello", "", "text/plain"},
  13870. {"file1", "world", "test.txt", "application/octet-stream"},
  13871. };
  13872. Client cli(HOST, port);
  13873. auto res = cli.Post("/upload", {}, items);
  13874. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13875. EXPECT_EQ(StatusCode::OK_200, res->status);
  13876. }
  13877. TEST(MultipartFormDataTest, ContentProviderCoalescesWrites) {
  13878. // Verify that make_multipart_content_provider coalesces many small segments
  13879. // into fewer sink.write() calls to avoid TCP packet fragmentation (#2410).
  13880. constexpr size_t kItemCount = 1000;
  13881. UploadFormDataItems items;
  13882. items.reserve(kItemCount);
  13883. for (size_t i = 0; i < kItemCount; i++) {
  13884. items.push_back(
  13885. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13886. }
  13887. const std::string boundary = "----test-boundary";
  13888. auto content_length = detail::get_multipart_content_length(items, boundary);
  13889. auto provider = detail::make_multipart_content_provider(items, boundary);
  13890. // Drive the provider the same way write_content_with_progress does
  13891. size_t write_count = 0;
  13892. size_t total_bytes = 0;
  13893. DataSink sink;
  13894. size_t offset = 0;
  13895. sink.write = [&](const char *d, size_t l) -> bool {
  13896. (void)d;
  13897. write_count++;
  13898. total_bytes += l;
  13899. offset += l;
  13900. return true;
  13901. };
  13902. sink.is_writable = []() -> bool { return true; };
  13903. while (offset < content_length) {
  13904. ASSERT_TRUE(provider(offset, content_length - offset, sink));
  13905. }
  13906. EXPECT_EQ(content_length, total_bytes);
  13907. // The total number of segments is 3 * kItemCount + 1 = 3001.
  13908. // With buffering into 64KB blocks, write_count should be much smaller.
  13909. auto segment_count = 3 * kItemCount + 1;
  13910. EXPECT_LT(write_count, segment_count / 10);
  13911. }
  13912. TEST(MultipartFormDataTest, ManyItemsEndToEnd) {
  13913. // Integration test: send many UploadFormDataItems and verify the server
  13914. // receives all of them correctly (#2410).
  13915. constexpr size_t kItemCount = 500;
  13916. auto handled = false;
  13917. Server svr;
  13918. svr.Post("/upload", [&](const Request &req, Response &res) {
  13919. EXPECT_EQ(kItemCount, req.form.fields.size());
  13920. for (size_t i = 0; i < kItemCount; i++) {
  13921. auto key = "field" + std::to_string(i);
  13922. auto val = "value" + std::to_string(i);
  13923. auto it = req.form.fields.find(key);
  13924. if (it != req.form.fields.end()) {
  13925. EXPECT_EQ(val, it->second.content);
  13926. } else {
  13927. ADD_FAILURE() << "Missing field: " << key;
  13928. }
  13929. }
  13930. res.set_content("ok", "text/plain");
  13931. handled = true;
  13932. });
  13933. auto port = svr.bind_to_any_port(HOST);
  13934. auto t = thread([&] { svr.listen_after_bind(); });
  13935. auto se = detail::scope_exit([&] {
  13936. svr.stop();
  13937. t.join();
  13938. ASSERT_FALSE(svr.is_running());
  13939. ASSERT_TRUE(handled);
  13940. });
  13941. svr.wait_until_ready();
  13942. UploadFormDataItems items;
  13943. items.reserve(kItemCount);
  13944. for (size_t i = 0; i < kItemCount; i++) {
  13945. items.push_back(
  13946. {"field" + std::to_string(i), "value" + std::to_string(i), "", ""});
  13947. }
  13948. Client cli(HOST, port);
  13949. auto res = cli.Post("/upload", items);
  13950. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  13951. EXPECT_EQ(StatusCode::OK_200, res->status);
  13952. }
  13953. TEST(MultipartFormDataTest, MakeFileProvider) {
  13954. // Verify make_file_provider sends a file's contents correctly.
  13955. const std::string file_content(4096, 'Z');
  13956. const std::string tmp_path = "./httplib_test_make_file_provider.bin";
  13957. {
  13958. std::ofstream ofs(tmp_path, std::ios::binary);
  13959. ofs.write(file_content.data(),
  13960. static_cast<std::streamsize>(file_content.size()));
  13961. }
  13962. auto handled = false;
  13963. Server svr;
  13964. svr.Post("/upload", [&](const Request &req, Response & /*res*/,
  13965. const ContentReader &content_reader) {
  13966. ASSERT_TRUE(req.is_multipart_form_data());
  13967. std::vector<FormData> items;
  13968. content_reader(
  13969. [&](const FormData &file) {
  13970. items.push_back(file);
  13971. return true;
  13972. },
  13973. [&](const char *data, size_t data_length) {
  13974. items.back().content.append(data, data_length);
  13975. return true;
  13976. });
  13977. ASSERT_EQ(1u, items.size());
  13978. EXPECT_EQ("myfile", items[0].name);
  13979. EXPECT_EQ("data.bin", items[0].filename);
  13980. EXPECT_EQ("application/octet-stream", items[0].content_type);
  13981. EXPECT_EQ(file_content, items[0].content);
  13982. handled = true;
  13983. });
  13984. auto port = svr.bind_to_any_port(HOST);
  13985. auto t = thread([&] { svr.listen_after_bind(); });
  13986. auto se = detail::scope_exit([&] {
  13987. svr.stop();
  13988. t.join();
  13989. ASSERT_FALSE(svr.is_running());
  13990. ASSERT_TRUE(handled);
  13991. std::remove(tmp_path.c_str());
  13992. });
  13993. svr.wait_until_ready();
  13994. FormDataProviderItems providers;
  13995. providers.push_back(make_file_provider("myfile", tmp_path, "data.bin",
  13996. "application/octet-stream"));
  13997. Client cli(HOST, port);
  13998. auto res = cli.Post("/upload", {}, {}, providers);
  13999. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14000. EXPECT_EQ(StatusCode::OK_200, res->status);
  14001. }
  14002. TEST(MultipartFormDataTest, ExcessivePartHeaders) {
  14003. // Verify that a multipart part with more than CPPHTTPLIB_HEADER_MAX_COUNT
  14004. // (100) headers is rejected with a 400 Bad Request response.
  14005. Server svr;
  14006. svr.Post("/post", [&](const Request & /*req*/, Response &res) {
  14007. res.set_content("ok", "text/plain");
  14008. });
  14009. thread t = thread([&] { svr.listen(HOST, PORT); });
  14010. auto se = detail::scope_exit([&] {
  14011. svr.stop();
  14012. t.join();
  14013. ASSERT_FALSE(svr.is_running());
  14014. });
  14015. svr.wait_until_ready();
  14016. // Build a multipart part with 101 custom headers (exceeding
  14017. // CPPHTTPLIB_HEADER_MAX_COUNT=100)
  14018. std::stringstream body;
  14019. body << "--simpleboundary\r\n"
  14020. << "Content-Disposition: form-data; name=\"field1\"\r\n";
  14021. for (int i = 0; i < 101; i++) {
  14022. body << "X-Custom-Header-" << i << ": value\r\n";
  14023. }
  14024. body << "\r\n"
  14025. << "value1\r\n"
  14026. << "--simpleboundary--\r\n";
  14027. std::string content_type = "multipart/form-data; boundary=simpleboundary";
  14028. Client cli(HOST, PORT);
  14029. auto res = cli.Post("/post", body.str(), content_type.c_str());
  14030. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14031. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14032. }
  14033. TEST(MultipartFormDataTest, NoInitialBoundaryParsingIsNotQuadratic) {
  14034. // A body that never contains the declared boundary must not be accumulated
  14035. // while the parser waits for it. Buffering it would also make every read
  14036. // rescan everything seen so far, which is quadratic in the body size.
  14037. Server svr;
  14038. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14039. res.set_content("ok", "text/plain");
  14040. });
  14041. auto port = svr.bind_to_any_port(HOST);
  14042. thread t = thread([&] { svr.listen_after_bind(); });
  14043. auto se = detail::scope_exit([&] {
  14044. svr.stop();
  14045. t.join();
  14046. ASSERT_FALSE(svr.is_running());
  14047. });
  14048. svr.wait_until_ready();
  14049. Client cli(HOST, port);
  14050. cli.set_read_timeout(60, 0);
  14051. cli.set_write_timeout(60, 0);
  14052. // '-' is the worst case: it matches the first character of the boundary, so
  14053. // every position has to be checked against it.
  14054. auto post_dashes = [&](size_t size) {
  14055. const std::string body(size, '-');
  14056. auto start = std::chrono::steady_clock::now();
  14057. auto res =
  14058. cli.Post("/post", body, "multipart/form-data; boundary=simpleboundary");
  14059. auto ms = std::chrono::duration_cast<std::chrono::milliseconds>(
  14060. std::chrono::steady_clock::now() - start)
  14061. .count();
  14062. EXPECT_TRUE(res) << "Error: " << to_string(res.error());
  14063. if (res) { EXPECT_EQ(StatusCode::BadRequest_400, res->status); }
  14064. return ms;
  14065. };
  14066. // Not named `small`/`large`: <rpcndr.h> defines `small` as a macro on
  14067. // Windows.
  14068. auto ms_4mb = post_dashes(4u * 1024 * 1024);
  14069. auto ms_16mb = post_dashes(16u * 1024 * 1024);
  14070. // Comparing the two sizes rather than checking an absolute duration keeps
  14071. // this meaningful across build types and CI load, both of which move the
  14072. // absolute numbers by more than an order of magnitude. Four times the bytes
  14073. // costs about four times the time when parsing is linear, and about sixteen
  14074. // times when the body is buffered and rescanned.
  14075. ASSERT_GT(ms_4mb, 0) << "timer resolution too coarse to compare";
  14076. EXPECT_LT(ms_16mb, ms_4mb * 10)
  14077. << "4MB took " << ms_4mb << "ms but 16MB took " << ms_16mb
  14078. << "ms, which suggests the body is being buffered and rescanned";
  14079. }
  14080. TEST(MultipartFormDataTest, BoundaryNotFollowedByDelimiterFailsFast) {
  14081. // A boundary can only be followed by CRLF or by "--", so anything else is
  14082. // malformed no matter what comes next. The parser must say so right away
  14083. // instead of buffering the rest of the declared body.
  14084. Server svr;
  14085. svr.Post("/post", [](const Request & /*req*/, Response &res) {
  14086. res.set_content("ok", "text/plain");
  14087. });
  14088. auto port = svr.bind_to_any_port(HOST);
  14089. thread t = thread([&] { svr.listen_after_bind(); });
  14090. auto se = detail::scope_exit([&] {
  14091. svr.stop();
  14092. t.join();
  14093. ASSERT_FALSE(svr.is_running());
  14094. });
  14095. svr.wait_until_ready();
  14096. // Announce a 1 MB body but send only the malformed prefix. A parser that
  14097. // buffers instead of failing would still be waiting for the remaining bytes.
  14098. const std::string body = "--zzzz\r\n"
  14099. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14100. "\r\n"
  14101. "text1"
  14102. "\r\n--zzzzXX";
  14103. const std::string req = "POST /post HTTP/1.1\r\n"
  14104. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14105. "Content-Length: 1048576\r\n"
  14106. "\r\n" +
  14107. body;
  14108. std::string response;
  14109. ASSERT_TRUE(send_request(3, req, &response, port));
  14110. ASSERT_GE(response.size(), 12u) << "no response before the read timeout";
  14111. EXPECT_EQ("400", response.substr(9, 3));
  14112. }
  14113. // Posts a multipart body split into two writes, so that the server sees the
  14114. // split at whatever offset the caller chose, and expects the single "text1"
  14115. // field to come through.
  14116. static void expect_split_multipart_ok(const std::string &body1,
  14117. const std::string &body2) {
  14118. auto handled = false;
  14119. Server svr;
  14120. svr.Post("/post", [&](const Request &req, Response &) {
  14121. EXPECT_EQ(1u, req.form.fields.size());
  14122. EXPECT_EQ("text1", req.form.get_field("text1"));
  14123. handled = true;
  14124. });
  14125. auto port = svr.bind_to_any_port(HOST);
  14126. thread t = thread([&] { svr.listen_after_bind(); });
  14127. auto se = detail::scope_exit([&] {
  14128. svr.stop();
  14129. t.join();
  14130. ASSERT_FALSE(svr.is_running());
  14131. ASSERT_TRUE(handled);
  14132. });
  14133. svr.wait_until_ready();
  14134. // "Connection: close" makes the server close once it has answered, so the
  14135. // response drain ends immediately instead of idling until the read timeout.
  14136. const std::string head =
  14137. "POST /post HTTP/1.1\r\n"
  14138. "Content-Type: multipart/form-data; boundary=zzzz\r\n"
  14139. "Connection: close\r\n"
  14140. "Content-Length: " +
  14141. std::to_string(body1.size() + body2.size()) + "\r\n\r\n";
  14142. std::string response;
  14143. ASSERT_TRUE(send_request_in_parts(3, {head + body1, body2}, &response, port));
  14144. ASSERT_GE(response.size(), 12u) << "no response";
  14145. EXPECT_EQ("200", response.substr(9, 3));
  14146. }
  14147. TEST(MultipartFormDataTest, EpilogueSplitAcrossReadsIsIgnored) {
  14148. // RFC 2046: everything after the close-delimiter is an epilogue and is to be
  14149. // ignored, including when it does not arrive in the same read as the
  14150. // close-delimiter itself.
  14151. expect_split_multipart_ok("--zzzz\r\n"
  14152. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14153. "\r\n"
  14154. "text1"
  14155. "\r\n--zzzz--",
  14156. "\r\nthis epilogue must be ignored\r\n");
  14157. }
  14158. TEST(MultipartFormDataTest, InitialBoundarySplitAfterLongPreamble) {
  14159. // The initial boundary may be preceded by a preamble of any length and may
  14160. // straddle a read boundary. Discarding data while waiting for it must not
  14161. // throw away a partial boundary sitting at the end of the buffer.
  14162. expect_split_multipart_ok(std::string(64u * 1024, 'p') + "--zz",
  14163. "zz\r\n"
  14164. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14165. "\r\n"
  14166. "text1"
  14167. "\r\n--zzzz--\r\n");
  14168. }
  14169. TEST(MultipartFormDataTest, BoundaryLengthLimitIsEnforced) {
  14170. // The received boundary was only checked for being non-empty, so it could be
  14171. // as long as a header is allowed to be. The parser scans the body for
  14172. // "--" + boundary, so a body crafted to repeat that delimiter's leading bytes
  14173. // costs a nearly full comparison at nearly every position, making the
  14174. // boundary's length a multiplier on the worst-case parsing cost. RFC 2046
  14175. // 5.1.1 caps a boundary at 70 characters; honoring that caps the multiplier.
  14176. Server svr;
  14177. svr.Post("/post", [](const Request &req, Response &res) {
  14178. EXPECT_EQ(1u, req.form.fields.size());
  14179. EXPECT_EQ("text1", req.form.get_field("text1"));
  14180. res.set_content("ok", "text/plain");
  14181. });
  14182. auto port = svr.bind_to_any_port(HOST);
  14183. thread t = thread([&] { svr.listen_after_bind(); });
  14184. auto se = detail::scope_exit([&] {
  14185. svr.stop();
  14186. t.join();
  14187. ASSERT_FALSE(svr.is_running());
  14188. });
  14189. svr.wait_until_ready();
  14190. Client cli(HOST, port);
  14191. auto post_with_boundary_of_length = [&](size_t len) {
  14192. const std::string boundary(len, 'a');
  14193. const std::string body =
  14194. "--" + boundary +
  14195. "\r\n"
  14196. "Content-Disposition: form-data; name=\"text1\"\r\n"
  14197. "\r\n"
  14198. "text1"
  14199. "\r\n--" +
  14200. boundary + "--\r\n";
  14201. return cli.Post("/post", body, "multipart/form-data; boundary=" + boundary);
  14202. };
  14203. auto res = post_with_boundary_of_length(70);
  14204. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14205. EXPECT_EQ(StatusCode::OK_200, res->status);
  14206. res = post_with_boundary_of_length(71);
  14207. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14208. EXPECT_EQ(StatusCode::BadRequest_400, res->status);
  14209. }
  14210. TEST(MakeFileBodyTest, Basic) {
  14211. const std::string file_content(4096, 'Z');
  14212. const std::string tmp_path = "./httplib_test_make_file_body.bin";
  14213. {
  14214. std::ofstream ofs(tmp_path, std::ios::binary);
  14215. ofs.write(file_content.data(),
  14216. static_cast<std::streamsize>(file_content.size()));
  14217. }
  14218. auto handled = false;
  14219. Server svr;
  14220. svr.Post("/upload", [&](const Request &req, Response &res) {
  14221. EXPECT_EQ(file_content, req.body);
  14222. handled = true;
  14223. res.status = StatusCode::OK_200;
  14224. });
  14225. auto port = svr.bind_to_any_port(HOST);
  14226. auto t = thread([&] { svr.listen_after_bind(); });
  14227. auto se = detail::scope_exit([&] {
  14228. svr.stop();
  14229. t.join();
  14230. ASSERT_FALSE(svr.is_running());
  14231. ASSERT_TRUE(handled);
  14232. std::remove(tmp_path.c_str());
  14233. });
  14234. svr.wait_until_ready();
  14235. auto fb = make_file_body(tmp_path);
  14236. ASSERT_GT(fb.first, 0u);
  14237. Client cli(HOST, port);
  14238. auto res =
  14239. cli.Post("/upload", fb.first, fb.second, "application/octet-stream");
  14240. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14241. EXPECT_EQ(StatusCode::OK_200, res->status);
  14242. }
  14243. TEST(MakeFileBodyTest, TruncatedFileMakesTheProviderFail) {
  14244. const std::string path = "./httplib_test_make_file_body_truncated.bin";
  14245. {
  14246. std::ofstream ofs(path, std::ios::binary);
  14247. const std::string content(100, 'A');
  14248. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14249. }
  14250. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14251. auto body = make_file_body(path);
  14252. ASSERT_EQ(100u, body.first);
  14253. ASSERT_TRUE(static_cast<bool>(body.second));
  14254. // Rewritten shorter after its length was measured - and, on a server, after
  14255. // that length has already gone out as Content-Length.
  14256. {
  14257. std::ofstream ofs(path, std::ios::binary | std::ios::trunc);
  14258. const std::string content(10, 'A');
  14259. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14260. }
  14261. std::string written;
  14262. DataSink sink;
  14263. sink.write = [&](const char *d, size_t l) {
  14264. written.append(d, l);
  14265. return true;
  14266. };
  14267. // The provider has to report failure. write_content_with_progress() advances
  14268. // its offset only by what was written, so a provider that returns true
  14269. // without completing the length it promised is called again straight away,
  14270. // and again.
  14271. EXPECT_FALSE(body.second(0, body.first, sink));
  14272. EXPECT_EQ(std::string(10, 'A'), written);
  14273. }
  14274. TEST(MakeFileBodyTest, WholeFileIsSent) {
  14275. const std::string path = "./httplib_test_make_file_body_whole.bin";
  14276. const std::string content(9000, 'Z'); // spans more than one 8 KiB read
  14277. {
  14278. std::ofstream ofs(path, std::ios::binary);
  14279. ofs.write(content.data(), static_cast<std::streamsize>(content.size()));
  14280. }
  14281. auto cleanup = detail::scope_exit([&] { std::remove(path.c_str()); });
  14282. auto body = make_file_body(path);
  14283. ASSERT_EQ(content.size(), body.first);
  14284. ASSERT_TRUE(static_cast<bool>(body.second));
  14285. std::string written;
  14286. DataSink sink;
  14287. sink.write = [&](const char *d, size_t l) {
  14288. written.append(d, l);
  14289. return true;
  14290. };
  14291. EXPECT_TRUE(body.second(0, body.first, sink));
  14292. EXPECT_EQ(content, written);
  14293. }
  14294. TEST(TaskQueueTest, IncreaseAtomicInteger) {
  14295. static constexpr unsigned int number_of_tasks{1000000};
  14296. std::atomic_uint count{0};
  14297. std::unique_ptr<TaskQueue> task_queue{
  14298. new ThreadPool{CPPHTTPLIB_THREAD_POOL_COUNT}};
  14299. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14300. auto queued = task_queue->enqueue(
  14301. [&count] { count.fetch_add(1, std::memory_order_relaxed); });
  14302. EXPECT_TRUE(queued);
  14303. }
  14304. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14305. task_queue->shutdown();
  14306. #else
  14307. EXPECT_NO_THROW(task_queue->shutdown());
  14308. #endif
  14309. EXPECT_EQ(number_of_tasks, count.load());
  14310. }
  14311. TEST(TaskQueueTest, IncreaseAtomicIntegerWithQueueLimit) {
  14312. static constexpr unsigned int number_of_tasks{1000000};
  14313. static constexpr unsigned int qlimit{2};
  14314. unsigned int queued_count{0};
  14315. std::atomic_uint count{0};
  14316. std::unique_ptr<TaskQueue> task_queue{
  14317. new ThreadPool{/*num_threads=*/1, /*max_threads=*/1, qlimit}};
  14318. for (unsigned int i = 0; i < number_of_tasks; ++i) {
  14319. if (task_queue->enqueue(
  14320. [&count] { count.fetch_add(1, std::memory_order_relaxed); })) {
  14321. queued_count++;
  14322. }
  14323. }
  14324. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14325. task_queue->shutdown();
  14326. #else
  14327. EXPECT_NO_THROW(task_queue->shutdown());
  14328. #endif
  14329. EXPECT_EQ(queued_count, count.load());
  14330. EXPECT_TRUE(queued_count <= number_of_tasks);
  14331. EXPECT_TRUE(queued_count >= qlimit);
  14332. }
  14333. TEST(TaskQueueTest, IdleTimeoutAtRuntime) {
  14334. // Use a short idle timeout so a dynamic thread spawns, times out and
  14335. // exits during the test, and the pool keeps working afterwards.
  14336. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{
  14337. /*num_threads=*/1, /*max_threads=*/2, /*max_queued_requests=*/0,
  14338. /*idle_timeout_sec=*/1}};
  14339. std::atomic_uint count{0};
  14340. std::condition_variable cv;
  14341. std::mutex mtx;
  14342. bool release = false;
  14343. // Block the base thread so the second task spawns a dynamic thread.
  14344. EXPECT_TRUE(task_queue->enqueue([&] {
  14345. std::unique_lock<std::mutex> lock(mtx);
  14346. while (!release) {
  14347. cv.wait(lock);
  14348. }
  14349. count++;
  14350. }));
  14351. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14352. // Let the dynamic thread finish its task and exceed the idle timeout.
  14353. std::this_thread::sleep_for(std::chrono::milliseconds(1500));
  14354. {
  14355. std::unique_lock<std::mutex> lock(mtx);
  14356. release = true;
  14357. }
  14358. cv.notify_all();
  14359. // The pool must still accept and run tasks after the dynamic thread exited.
  14360. EXPECT_TRUE(task_queue->enqueue([&] { count++; }));
  14361. task_queue->shutdown();
  14362. EXPECT_EQ(3u, count.load());
  14363. }
  14364. TEST(TaskQueueTest, MaxQueuedRequests) {
  14365. static constexpr unsigned int qlimit{3};
  14366. std::unique_ptr<TaskQueue> task_queue{new ThreadPool{1, 1, qlimit}};
  14367. std::condition_variable sem_cv;
  14368. std::mutex sem_mtx;
  14369. int credits = 0;
  14370. bool queued;
  14371. /* Fill up the queue with tasks that will block until we give them credits to
  14372. * complete. */
  14373. for (unsigned int n = 0; n <= qlimit;) {
  14374. queued = task_queue->enqueue([&sem_mtx, &sem_cv, &credits] {
  14375. std::unique_lock<std::mutex> lock(sem_mtx);
  14376. while (credits <= 0) {
  14377. sem_cv.wait(lock);
  14378. }
  14379. /* Consume the credit and signal the test code if they are all gone. */
  14380. if (--credits == 0) { sem_cv.notify_one(); }
  14381. });
  14382. if (n < qlimit) {
  14383. /* The first qlimit enqueues must succeed. */
  14384. EXPECT_TRUE(queued);
  14385. } else {
  14386. /* The last one will succeed only when the worker thread
  14387. * starts and dequeues the first blocking task. Although
  14388. * not necessary for the correctness of this test, we sleep for
  14389. * a short while to avoid busy waiting. */
  14390. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  14391. }
  14392. if (queued) { n++; }
  14393. }
  14394. /* Further enqueues must fail since the queue is full. */
  14395. for (auto i = 0; i < 4; i++) {
  14396. queued = task_queue->enqueue([] {});
  14397. EXPECT_FALSE(queued);
  14398. }
  14399. /* Give the credits to allow the previous tasks to complete. */
  14400. {
  14401. std::unique_lock<std::mutex> lock(sem_mtx);
  14402. credits += qlimit + 1;
  14403. }
  14404. sem_cv.notify_all();
  14405. /* Wait for all the credits to be consumed. */
  14406. {
  14407. std::unique_lock<std::mutex> lock(sem_mtx);
  14408. while (credits > 0) {
  14409. sem_cv.wait(lock);
  14410. }
  14411. }
  14412. /* Check that we are able again to enqueue at least qlimit tasks. */
  14413. for (unsigned int i = 0; i < qlimit; i++) {
  14414. queued = task_queue->enqueue([] {});
  14415. EXPECT_TRUE(queued);
  14416. }
  14417. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  14418. task_queue->shutdown();
  14419. #else
  14420. EXPECT_NO_THROW(task_queue->shutdown());
  14421. #endif
  14422. }
  14423. TEST(RedirectTest, RedirectToUrlWithQueryParameters) {
  14424. Server svr;
  14425. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14426. res.set_redirect(R"(/hello?key=val%26key2%3Dval2)");
  14427. });
  14428. svr.Get("/hello", [](const Request &req, Response &res) {
  14429. res.set_content(req.get_param_value("key"), "text/plain");
  14430. });
  14431. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14432. auto se = detail::scope_exit([&] {
  14433. svr.stop();
  14434. thread.join();
  14435. ASSERT_FALSE(svr.is_running());
  14436. });
  14437. svr.wait_until_ready();
  14438. {
  14439. Client cli(HOST, PORT);
  14440. cli.set_follow_location(true);
  14441. auto res = cli.Get("/");
  14442. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14443. EXPECT_EQ(StatusCode::OK_200, res->status);
  14444. EXPECT_EQ("val&key2=val2", res->body);
  14445. }
  14446. }
  14447. #endif
  14448. TEST(RedirectTest, RedirectToUrlWithPlusInQueryParameters) {
  14449. Server svr;
  14450. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14451. res.set_redirect(R"(/hello?key=AByz09+~-._%20%26%3F%C3%BC%2B)");
  14452. });
  14453. svr.Get("/hello", [](const Request &req, Response &res) {
  14454. res.set_content(req.get_param_value("key"), "text/plain");
  14455. });
  14456. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14457. auto se = detail::scope_exit([&] {
  14458. svr.stop();
  14459. thread.join();
  14460. ASSERT_FALSE(svr.is_running());
  14461. });
  14462. svr.wait_until_ready();
  14463. {
  14464. Client cli(HOST, PORT);
  14465. cli.set_follow_location(true);
  14466. auto res = cli.Get("/");
  14467. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14468. EXPECT_EQ(StatusCode::OK_200, res->status);
  14469. EXPECT_EQ("AByz09 ~-._ &?ü+", res->body);
  14470. }
  14471. }
  14472. TEST(RedirectTest, RedirectWithPlusInPath) {
  14473. Server svr;
  14474. svr.Get("/", [](const Request & /*req*/, Response &res) {
  14475. res.set_redirect("/a+b");
  14476. });
  14477. // Route pattern uses regex; escape + as \\+
  14478. svr.Get(R"(/a\+b)", [](const Request &req, Response &res) {
  14479. res.set_content(req.path, "text/plain");
  14480. });
  14481. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14482. auto se = detail::scope_exit([&] {
  14483. svr.stop();
  14484. thread.join();
  14485. ASSERT_FALSE(svr.is_running());
  14486. });
  14487. svr.wait_until_ready();
  14488. {
  14489. Client cli(HOST, PORT);
  14490. cli.set_follow_location(true);
  14491. auto res = cli.Get("/");
  14492. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14493. EXPECT_EQ(StatusCode::OK_200, res->status);
  14494. EXPECT_EQ("/a+b", res->body);
  14495. }
  14496. }
  14497. TEST(RedirectTest, ResolveRelativeLocation) {
  14498. // Examples from RFC 3986 section 5.4, base "http://a/b/c/d;p?q".
  14499. const std::vector<std::pair<std::string, std::string>> cases = {
  14500. {"g", "/b/c/g"},
  14501. {"./g", "/b/c/g"},
  14502. {"g/", "/b/c/g/"},
  14503. {"?y", "/b/c/d;p?y"},
  14504. {"g?y", "/b/c/g?y"},
  14505. {"#s", "/b/c/d;p?q#s"},
  14506. {"g#s", "/b/c/g#s"},
  14507. {"g?y#s", "/b/c/g?y#s"},
  14508. {";x", "/b/c/;x"},
  14509. {"g;x", "/b/c/g;x"},
  14510. {".", "/b/c/"},
  14511. {"./", "/b/c/"},
  14512. {"..", "/b/"},
  14513. {"../", "/b/"},
  14514. {"../g", "/b/g"},
  14515. {"../..", "/"},
  14516. {"../../", "/"},
  14517. {"../../g", "/g"},
  14518. {"../../../g", "/g"},
  14519. {"g.", "/b/c/g."},
  14520. {".g", "/b/c/.g"},
  14521. {"g..", "/b/c/g.."},
  14522. {"..g", "/b/c/..g"},
  14523. {"./../g", "/b/g"},
  14524. {"./g/.", "/b/c/g/"},
  14525. {"g/./h", "/b/c/g/h"},
  14526. {"g/../h", "/b/c/h"},
  14527. {"g;x=1/./y", "/b/c/g;x=1/y"},
  14528. {"g;x=1/../y", "/b/c/y"},
  14529. {"g?y/./x", "/b/c/g?y/./x"},
  14530. {"g#s/../x", "/b/c/g#s/../x"},
  14531. // Not relative-path references, so left for parse_url.
  14532. {"/g", "/g"},
  14533. {"//g", "//g"},
  14534. {"http://g/x", "http://g/x"},
  14535. {"g:h", "g:h"},
  14536. };
  14537. for (const auto &c : cases) {
  14538. EXPECT_EQ(c.second,
  14539. detail::resolve_relative_location(c.first, "/b/c/d;p?q"))
  14540. << c.first;
  14541. }
  14542. }
  14543. TEST(RedirectTest, RelativeLocationWithoutLeadingSlash) {
  14544. Server svr;
  14545. svr.Get("/dir/page", [](const Request &req, Response &res) {
  14546. res.set_redirect(req.get_param_value("to"));
  14547. });
  14548. svr.Get("/dir/next", [](const Request &req, Response &res) {
  14549. res.set_content(req.target, "text/plain");
  14550. });
  14551. svr.Get("/other", [](const Request &req, Response &res) {
  14552. res.set_content(req.target, "text/plain");
  14553. });
  14554. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14555. auto se = detail::scope_exit([&] {
  14556. svr.stop();
  14557. thread.join();
  14558. ASSERT_FALSE(svr.is_running());
  14559. });
  14560. svr.wait_until_ready();
  14561. const std::vector<std::pair<std::string, std::string>> cases = {
  14562. {"next", "/dir/next"},
  14563. {"./next?x=1", "/dir/next?x=1"},
  14564. {"../other", "/other"},
  14565. };
  14566. for (const auto &c : cases) {
  14567. Client cli(HOST, PORT);
  14568. cli.set_follow_location(true);
  14569. auto res = cli.Get("/dir/page?to=" + encode_query_component(c.first));
  14570. ASSERT_TRUE(res) << c.first << ": " << to_string(res.error());
  14571. EXPECT_EQ(StatusCode::OK_200, res->status) << c.first;
  14572. EXPECT_EQ(c.second, res->body) << c.first;
  14573. }
  14574. }
  14575. #ifdef CPPHTTPLIB_SSL_ENABLED
  14576. TEST(RedirectTest, Issue2185_Online) {
  14577. SSLClient client("github.com");
  14578. client.set_follow_location(true);
  14579. auto res = client.Get("/Coollab-Art/Coollab/releases/download/1.1.1_UI-Scale/"
  14580. "Coollab-Windows.zip");
  14581. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  14582. EXPECT_EQ(StatusCode::OK_200, res->status);
  14583. EXPECT_EQ(9920427U, res->body.size());
  14584. }
  14585. #endif
  14586. TEST(VulnerabilityTest, CRLFInjection) {
  14587. Server svr;
  14588. svr.Post("/test1", [](const Request & /*req*/, Response &res) {
  14589. res.set_content("Hello 1", "text/plain");
  14590. });
  14591. svr.Delete("/test2", [](const Request & /*req*/, Response &res) {
  14592. res.set_content("Hello 2", "text/plain");
  14593. });
  14594. svr.Put("/test3", [](const Request & /*req*/, Response &res) {
  14595. res.set_content("Hello 3", "text/plain");
  14596. });
  14597. svr.Patch("/test4", [](const Request & /*req*/, Response &res) {
  14598. res.set_content("Hello 4", "text/plain");
  14599. });
  14600. svr.set_logger([](const Request &req, const Response & /*res*/) {
  14601. for (const auto &x : req.headers) {
  14602. auto key = x.first;
  14603. EXPECT_STRNE("evil", key.c_str());
  14604. }
  14605. });
  14606. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  14607. auto se = detail::scope_exit([&] {
  14608. svr.stop();
  14609. thread.join();
  14610. ASSERT_FALSE(svr.is_running());
  14611. });
  14612. svr.wait_until_ready();
  14613. {
  14614. Client cli(HOST, PORT);
  14615. cli.Post("/test1", "A=B",
  14616. "application/x-www-form-urlencoded\r\nevil: hello1");
  14617. cli.Delete("/test2", "A=B", "text/plain\r\nevil: hello2");
  14618. cli.Put("/test3", "text", "text/plain\r\nevil: hello3");
  14619. cli.Patch("/test4", "content", "text/plain\r\nevil: hello4");
  14620. }
  14621. }
  14622. TEST(VulnerabilityTest, CRLFInjectionInHeaders) {
  14623. auto server_thread = std::thread([] {
  14624. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14625. default_socket_options(srv);
  14626. sockaddr_in addr{};
  14627. addr.sin_family = AF_INET;
  14628. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14629. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14630. ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr));
  14631. ::listen(srv, 1);
  14632. sockaddr_in cli_addr{};
  14633. socklen_t cli_len = sizeof(cli_addr);
  14634. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  14635. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 1, 0);
  14636. std::string buf_all;
  14637. char buf[2048];
  14638. ssize_t n;
  14639. while ((n = ::recv(cli, buf, sizeof(buf), 0)) > 0) {
  14640. buf_all.append(buf, static_cast<size_t>(n));
  14641. size_t pos;
  14642. while ((pos = buf_all.find("\r\n\r\n")) != std::string::npos) {
  14643. auto request_block = buf_all.substr(0, pos + 4); // include separator
  14644. auto e = request_block.find("\r\n");
  14645. if (e != std::string::npos) {
  14646. auto request_line = request_block.substr(0, e);
  14647. std::string msg =
  14648. "CRLF injection detected in request line: '" + request_line + "'";
  14649. EXPECT_FALSE(true) << msg;
  14650. }
  14651. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 5\r\n\r\nHello";
  14652. ::send(cli,
  14653. #ifdef _WIN32
  14654. static_cast<const char *>(resp.c_str()),
  14655. static_cast<int>(resp.size()),
  14656. #else
  14657. resp.c_str(), resp.size(),
  14658. #endif
  14659. 0);
  14660. buf_all.erase(0, pos + 4);
  14661. }
  14662. }
  14663. detail::close_socket(cli);
  14664. detail::close_socket(srv);
  14665. });
  14666. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  14667. auto cli = Client("127.0.0.1", PORT + 1);
  14668. auto headers = Headers{
  14669. {"A", "B\r\n\r\nGET /pwned HTTP/1.1\r\nHost: 127.0.0.1:1234\r\n\r\n"},
  14670. {"Connection", "keep-alive"}};
  14671. auto res = cli.Get("/hi", headers);
  14672. EXPECT_FALSE(res);
  14673. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14674. server_thread.join();
  14675. }
  14676. // A request rejected before any byte reaches the socket must fail right away
  14677. // instead of waiting for a response the server will never send.
  14678. TEST(ClientRejectedRequestTest, DoesNotWaitForResponse) {
  14679. // The kernel completes the TCP handshake from the listen backlog, so the
  14680. // client connects, but nothing ever reads, responds or closes.
  14681. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14682. default_socket_options(srv);
  14683. sockaddr_in addr{};
  14684. addr.sin_family = AF_INET;
  14685. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14686. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14687. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14688. ASSERT_EQ(0, ::listen(srv, 8));
  14689. auto cli = Client("127.0.0.1", PORT + 1);
  14690. cli.set_read_timeout(10, 0);
  14691. auto elapsed_ms = [](std::chrono::steady_clock::time_point start) {
  14692. return std::chrono::duration_cast<std::chrono::milliseconds>(
  14693. std::chrono::steady_clock::now() - start)
  14694. .count();
  14695. };
  14696. {
  14697. Request req;
  14698. req.method = "GE T";
  14699. req.path = "/";
  14700. auto start = std::chrono::steady_clock::now();
  14701. auto res = cli.send(req);
  14702. EXPECT_FALSE(res);
  14703. EXPECT_EQ(Error::Write, res.error());
  14704. EXPECT_LT(elapsed_ms(start), 1000);
  14705. }
  14706. {
  14707. auto start = std::chrono::steady_clock::now();
  14708. auto res = cli.Get("/", Headers{{"A", "B\r\nEvil: 1"}});
  14709. EXPECT_FALSE(res);
  14710. EXPECT_EQ(Error::InvalidHeaders, res.error());
  14711. EXPECT_LT(elapsed_ms(start), 1000);
  14712. }
  14713. EXPECT_FALSE(cli.is_socket_open());
  14714. detail::close_socket(srv);
  14715. }
  14716. TEST(ClientRejectedRequestTest, OpenStreamSendsNothingOnInvalidHeader) {
  14717. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  14718. default_socket_options(srv);
  14719. sockaddr_in addr{};
  14720. addr.sin_family = AF_INET;
  14721. addr.sin_port = htons(static_cast<uint16_t>(PORT + 1));
  14722. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  14723. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  14724. ASSERT_EQ(0, ::listen(srv, 1));
  14725. std::string received;
  14726. auto server_thread = std::thread([&] {
  14727. auto sock = ::accept(srv, nullptr, nullptr);
  14728. if (sock == INVALID_SOCKET) { return; }
  14729. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 2, 0);
  14730. char buf[2048];
  14731. ssize_t n;
  14732. while ((n = ::recv(sock, buf, sizeof(buf), 0)) > 0) {
  14733. received.append(buf, static_cast<size_t>(n));
  14734. }
  14735. detail::close_socket(sock);
  14736. });
  14737. {
  14738. auto cli = Client("127.0.0.1", PORT + 1);
  14739. // "Z" sorts after the default headers, so writing straight to the socket
  14740. // would have sent the request line and those headers before the rejection.
  14741. auto handle =
  14742. cli.open_stream("GET", "/", Params{}, Headers{{"Z", "B\r\nEvil: 1"}});
  14743. EXPECT_FALSE(handle.is_valid());
  14744. EXPECT_EQ(Error::InvalidHeaders, handle.error);
  14745. }
  14746. server_thread.join();
  14747. detail::close_socket(srv);
  14748. EXPECT_TRUE(received.empty()) << received;
  14749. }
  14750. TEST(PathParamsTest, StaticMatch) {
  14751. const auto pattern = "/users/all";
  14752. detail::PathParamsMatcher matcher(pattern);
  14753. Request request;
  14754. request.path = "/users/all";
  14755. ASSERT_TRUE(matcher.match(request));
  14756. std::unordered_map<std::string, std::string> expected_params = {};
  14757. EXPECT_EQ(request.path_params, expected_params);
  14758. }
  14759. TEST(PathParamsTest, StaticMismatch) {
  14760. const auto pattern = "/users/all";
  14761. detail::PathParamsMatcher matcher(pattern);
  14762. Request request;
  14763. request.path = "/users/1";
  14764. ASSERT_FALSE(matcher.match(request));
  14765. }
  14766. TEST(PathParamsTest, SingleParamInTheMiddle) {
  14767. const auto pattern = "/users/:id/subscriptions";
  14768. detail::PathParamsMatcher matcher(pattern);
  14769. Request request;
  14770. request.path = "/users/42/subscriptions";
  14771. ASSERT_TRUE(matcher.match(request));
  14772. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14773. EXPECT_EQ(request.path_params, expected_params);
  14774. }
  14775. TEST(PathParamsTest, SingleParamInTheEnd) {
  14776. const auto pattern = "/users/:id";
  14777. detail::PathParamsMatcher matcher(pattern);
  14778. Request request;
  14779. request.path = "/users/24";
  14780. ASSERT_TRUE(matcher.match(request));
  14781. std::unordered_map<std::string, std::string> expected_params = {{"id", "24"}};
  14782. EXPECT_EQ(request.path_params, expected_params);
  14783. }
  14784. TEST(PathParamsTest, SingleParamInTheEndTrailingSlash) {
  14785. const auto pattern = "/users/:id/";
  14786. detail::PathParamsMatcher matcher(pattern);
  14787. Request request;
  14788. request.path = "/users/42/";
  14789. ASSERT_TRUE(matcher.match(request));
  14790. std::unordered_map<std::string, std::string> expected_params = {{"id", "42"}};
  14791. EXPECT_EQ(request.path_params, expected_params);
  14792. }
  14793. TEST(PathParamsTest, EmptyParam) {
  14794. const auto pattern = "/users/:id/";
  14795. detail::PathParamsMatcher matcher(pattern);
  14796. Request request;
  14797. request.path = "/users//";
  14798. ASSERT_TRUE(matcher.match(request));
  14799. std::unordered_map<std::string, std::string> expected_params = {{"id", ""}};
  14800. EXPECT_EQ(request.path_params, expected_params);
  14801. }
  14802. TEST(PathParamsTest, FragmentMismatch) {
  14803. const auto pattern = "/users/:id/";
  14804. detail::PathParamsMatcher matcher(pattern);
  14805. Request request;
  14806. request.path = "/admins/24/";
  14807. ASSERT_FALSE(matcher.match(request));
  14808. }
  14809. TEST(PathParamsTest, ExtraFragments) {
  14810. const auto pattern = "/users/:id";
  14811. detail::PathParamsMatcher matcher(pattern);
  14812. Request request;
  14813. request.path = "/users/42/subscriptions";
  14814. ASSERT_FALSE(matcher.match(request));
  14815. }
  14816. TEST(PathParamsTest, MissingTrailingParam) {
  14817. const auto pattern = "/users/:id";
  14818. detail::PathParamsMatcher matcher(pattern);
  14819. Request request;
  14820. request.path = "/users";
  14821. ASSERT_FALSE(matcher.match(request));
  14822. }
  14823. TEST(PathParamsTest, MissingParamInTheMiddle) {
  14824. const auto pattern = "/users/:id/subscriptions";
  14825. detail::PathParamsMatcher matcher(pattern);
  14826. Request request;
  14827. request.path = "/users/subscriptions";
  14828. ASSERT_FALSE(matcher.match(request));
  14829. }
  14830. TEST(PathParamsTest, MultipleParams) {
  14831. const auto pattern = "/users/:userid/subscriptions/:subid";
  14832. detail::PathParamsMatcher matcher(pattern);
  14833. Request request;
  14834. request.path = "/users/42/subscriptions/2";
  14835. ASSERT_TRUE(matcher.match(request));
  14836. std::unordered_map<std::string, std::string> expected_params = {
  14837. {"userid", "42"}, {"subid", "2"}};
  14838. EXPECT_EQ(request.path_params, expected_params);
  14839. }
  14840. TEST(PathParamsTest, SequenceOfParams) {
  14841. const auto pattern = "/values/:x/:y/:z";
  14842. detail::PathParamsMatcher matcher(pattern);
  14843. Request request;
  14844. request.path = "/values/1/2/3";
  14845. ASSERT_TRUE(matcher.match(request));
  14846. std::unordered_map<std::string, std::string> expected_params = {
  14847. {"x", "1"}, {"y", "2"}, {"z", "3"}};
  14848. EXPECT_EQ(request.path_params, expected_params);
  14849. }
  14850. TEST(PathParamsTest, SemicolonInTheMiddleIsNotAParam) {
  14851. const auto pattern = "/prefix:suffix";
  14852. detail::PathParamsMatcher matcher(pattern);
  14853. Request request;
  14854. request.path = "/prefix:suffix";
  14855. ASSERT_TRUE(matcher.match(request));
  14856. const std::unordered_map<std::string, std::string> expected_params = {};
  14857. EXPECT_EQ(request.path_params, expected_params);
  14858. }
  14859. TEST(RegexMatcherTest, OverlongPathIsRejectedBeforeRegexMatch) {
  14860. // std::regex_match's backtracking (most acute on libstdc++) can exhaust the
  14861. // calling thread's stack on a long enough path for a quantified pattern;
  14862. // RegexMatcher must refuse to run regex matching on paths beyond
  14863. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH instead of invoking it.
  14864. detail::RegexMatcher matcher("/files/(.*)");
  14865. Request within_limit;
  14866. within_limit.path = "/files/" + std::string(10, 'A');
  14867. EXPECT_TRUE(matcher.match(within_limit));
  14868. Request over_limit;
  14869. over_limit.path =
  14870. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, 'A');
  14871. EXPECT_FALSE(matcher.match(over_limit));
  14872. }
  14873. TEST(RegexMatcherTest, ServerSurvivesOverlongPathOnRegexRoute) {
  14874. Server svr;
  14875. svr.Get(R"(/files/(.*))", [](const Request & /*req*/, Response &res) {
  14876. res.set_content("ok", "text/plain");
  14877. });
  14878. auto port = svr.bind_to_any_port(HOST);
  14879. auto thread = std::thread([&]() { svr.listen_after_bind(); });
  14880. auto se = detail::scope_exit([&] {
  14881. svr.stop();
  14882. thread.join();
  14883. ASSERT_FALSE(svr.is_running());
  14884. });
  14885. svr.wait_until_ready();
  14886. // Comfortably past CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH, well within the
  14887. // request URI limit; this used to be able to crash the process.
  14888. std::string path =
  14889. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 4, 'A');
  14890. std::string req = "GET " + path +
  14891. " HTTP/1.1\r\n"
  14892. "Host: " +
  14893. std::string(HOST) + ":" + std::to_string(port) +
  14894. "\r\n"
  14895. "Connection: close\r\n"
  14896. "\r\n";
  14897. std::string response;
  14898. ASSERT_TRUE(send_request(5, req, &response, port));
  14899. EXPECT_NE(std::string::npos, response.find("404"));
  14900. }
  14901. TEST(RouteMatcherTest, LiteralPatternsAndRegexPatterns) {
  14902. Server svr;
  14903. auto handler = [](const Request & /*req*/, Response &res) {
  14904. res.set_content("hit", "text/plain");
  14905. };
  14906. // No regex metacharacter, so this one is compared literally
  14907. svr.Get("/literal/route", handler);
  14908. // '.' is a regex metacharacter, so this one must keep regex semantics
  14909. svr.Get("/a.c", handler);
  14910. auto port = svr.bind_to_any_port(HOST);
  14911. std::thread t([&]() { svr.listen_after_bind(); });
  14912. auto se = detail::scope_exit([&] {
  14913. svr.stop();
  14914. t.join();
  14915. ASSERT_FALSE(svr.is_running());
  14916. });
  14917. svr.wait_until_ready();
  14918. Client cli(HOST, port);
  14919. struct {
  14920. const char *path;
  14921. int status;
  14922. } cases[] = {
  14923. {"/literal/route", StatusCode::OK_200},
  14924. {"/literal/routes", StatusCode::NotFound_404},
  14925. {"/literal/rout", StatusCode::NotFound_404},
  14926. {"/abc", StatusCode::OK_200},
  14927. {"/a.c", StatusCode::OK_200},
  14928. };
  14929. for (const auto &x : cases) {
  14930. auto res = cli.Get(x.path);
  14931. ASSERT_TRUE(res) << x.path;
  14932. EXPECT_EQ(x.status, res->status) << x.path;
  14933. }
  14934. }
  14935. TEST(RouteMatcherTest, LongLiteralPatternIsNotSubjectToTheRegexPathLimit) {
  14936. // CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH exists to keep std::regex_match
  14937. // from exhausting the stack, so it must only constrain routes that actually
  14938. // run a regular expression. A literal route is matched by comparison and
  14939. // stays usable at any length.
  14940. Server svr;
  14941. const std::string pattern =
  14942. "/files/" + std::string(CPPHTTPLIB_REGEX_ROUTE_PATH_MAX_LENGTH * 2, 'a');
  14943. svr.Get(pattern, [](const Request & /*req*/, Response &res) {
  14944. res.set_content("hit", "text/plain");
  14945. });
  14946. auto port = svr.bind_to_any_port(HOST);
  14947. std::thread t([&]() { svr.listen_after_bind(); });
  14948. auto se = detail::scope_exit([&] {
  14949. svr.stop();
  14950. t.join();
  14951. ASSERT_FALSE(svr.is_running());
  14952. });
  14953. svr.wait_until_ready();
  14954. Client cli(HOST, port);
  14955. auto res = cli.Get(pattern);
  14956. ASSERT_TRUE(res);
  14957. EXPECT_EQ(StatusCode::OK_200, res->status);
  14958. }
  14959. TEST(ParseUrlTest, VariousPatterns) {
  14960. {
  14961. detail::UrlComponents uc;
  14962. ASSERT_TRUE(detail::parse_url("http://example.com:8080/path?q=1#frag", uc));
  14963. EXPECT_EQ("http", uc.scheme);
  14964. EXPECT_EQ("example.com", uc.host);
  14965. EXPECT_EQ("8080", uc.port);
  14966. EXPECT_EQ("/path", uc.path);
  14967. EXPECT_EQ("?q=1", uc.query);
  14968. }
  14969. {
  14970. detail::UrlComponents uc;
  14971. ASSERT_TRUE(detail::parse_url("https://example.com/path", uc));
  14972. EXPECT_EQ("https", uc.scheme);
  14973. EXPECT_EQ("example.com", uc.host);
  14974. EXPECT_TRUE(uc.port.empty());
  14975. EXPECT_EQ("/path", uc.path);
  14976. }
  14977. {
  14978. detail::UrlComponents uc;
  14979. ASSERT_TRUE(detail::parse_url("http://[::1]:8080/path", uc));
  14980. EXPECT_EQ("::1", uc.host);
  14981. EXPECT_EQ("8080", uc.port);
  14982. EXPECT_EQ("/path", uc.path);
  14983. }
  14984. {
  14985. detail::UrlComponents uc;
  14986. ASSERT_FALSE(detail::parse_url("http://[::1/path", uc));
  14987. }
  14988. {
  14989. // Bytes after the IPv6 literal must be a delimiter, not folded into
  14990. // the path while the connection still targets the bracketed host.
  14991. detail::UrlComponents uc;
  14992. ASSERT_FALSE(detail::parse_url("http://[::1]evil.com/", uc));
  14993. }
  14994. {
  14995. detail::UrlComponents uc;
  14996. ASSERT_FALSE(detail::parse_url("http://[::1]evil", uc));
  14997. }
  14998. {
  14999. detail::UrlComponents uc;
  15000. ASSERT_TRUE(detail::parse_url("http://[::1]/path", uc));
  15001. EXPECT_EQ("::1", uc.host);
  15002. EXPECT_TRUE(uc.port.empty());
  15003. EXPECT_EQ("/path", uc.path);
  15004. }
  15005. {
  15006. detail::UrlComponents uc;
  15007. ASSERT_TRUE(detail::parse_url("//example.com/path?q=1", uc));
  15008. EXPECT_TRUE(uc.scheme.empty());
  15009. EXPECT_EQ("example.com", uc.host);
  15010. EXPECT_EQ("/path", uc.path);
  15011. EXPECT_EQ("?q=1", uc.query);
  15012. }
  15013. {
  15014. detail::UrlComponents uc;
  15015. ASSERT_TRUE(detail::parse_url("/path?q=1", uc));
  15016. EXPECT_TRUE(uc.host.empty());
  15017. EXPECT_EQ("/path", uc.path);
  15018. EXPECT_EQ("?q=1", uc.query);
  15019. }
  15020. {
  15021. detail::UrlComponents uc;
  15022. ASSERT_TRUE(detail::parse_url("example.com:8080", uc));
  15023. EXPECT_EQ("example.com", uc.host);
  15024. EXPECT_EQ("8080", uc.port);
  15025. }
  15026. {
  15027. // Unix socket path — must not be parsed as host
  15028. detail::UrlComponents uc;
  15029. ASSERT_TRUE(detail::parse_url("./httplib-server.sock", uc));
  15030. EXPECT_TRUE(uc.host.empty());
  15031. }
  15032. {
  15033. detail::UrlComponents uc;
  15034. ASSERT_TRUE(detail::parse_url("", uc));
  15035. EXPECT_TRUE(uc.host.empty());
  15036. EXPECT_TRUE(uc.path.empty());
  15037. }
  15038. {
  15039. detail::UrlComponents uc;
  15040. ASSERT_FALSE(detail::parse_url("HTTP://example.com/path", uc));
  15041. }
  15042. {
  15043. detail::UrlComponents uc;
  15044. ASSERT_FALSE(detail::parse_url("h2://example.com/path", uc));
  15045. }
  15046. {
  15047. // Accepted by parse_url; callers restrict to http/https
  15048. detail::UrlComponents uc;
  15049. ASSERT_TRUE(detail::parse_url("ftp://example.com/", uc));
  15050. EXPECT_EQ("ftp", uc.scheme);
  15051. }
  15052. {
  15053. detail::UrlComponents uc;
  15054. ASSERT_FALSE(detail::parse_url("http://[::1<script>]/path", uc));
  15055. }
  15056. {
  15057. detail::UrlComponents uc;
  15058. ASSERT_FALSE(detail::parse_url("http://[]/path", uc));
  15059. }
  15060. }
  15061. TEST(ParseUrlTest, FragmentHandling) {
  15062. {
  15063. detail::UrlComponents uc;
  15064. ASSERT_TRUE(detail::parse_url("http://example.com/path#frag", uc));
  15065. EXPECT_EQ("/path", uc.path);
  15066. EXPECT_TRUE(uc.query.empty());
  15067. }
  15068. {
  15069. detail::UrlComponents uc;
  15070. ASSERT_TRUE(detail::parse_url("#frag", uc));
  15071. EXPECT_TRUE(uc.path.empty());
  15072. EXPECT_TRUE(uc.query.empty());
  15073. }
  15074. }
  15075. TEST(ParseUrlTest, UserinfoHandling) {
  15076. // Userinfo with @ but no colon — host includes @
  15077. detail::UrlComponents uc;
  15078. ASSERT_TRUE(detail::parse_url("http://user@host.com/path", uc));
  15079. EXPECT_EQ("user@host.com", uc.host);
  15080. EXPECT_EQ("/path", uc.path);
  15081. }
  15082. TEST(ParseUrlTest, IPv6EdgeCases) {
  15083. {
  15084. detail::UrlComponents uc;
  15085. ASSERT_TRUE(detail::parse_url("[::1]:8080", uc));
  15086. EXPECT_TRUE(uc.scheme.empty());
  15087. EXPECT_EQ("::1", uc.host);
  15088. EXPECT_EQ("8080", uc.port);
  15089. }
  15090. {
  15091. // Zone ID '%25' is not in [a-fA-F0-9:]
  15092. detail::UrlComponents uc;
  15093. ASSERT_FALSE(detail::parse_url("http://[fe80::1%25eth0]:443/path", uc));
  15094. }
  15095. }
  15096. TEST(ParseUrlTest, SchemeEdgeCases) {
  15097. {
  15098. detail::UrlComponents uc;
  15099. ASSERT_FALSE(detail::parse_url("://evil.com/path", uc));
  15100. }
  15101. {
  15102. detail::UrlComponents uc;
  15103. ASSERT_FALSE(detail::parse_url("ht-tp://evil.com/path", uc));
  15104. }
  15105. {
  15106. detail::UrlComponents uc;
  15107. ASSERT_FALSE(detail::parse_url("h.t://evil.com/path", uc));
  15108. }
  15109. }
  15110. TEST(ParseUrlTest, PortEdgeCases) {
  15111. {
  15112. detail::UrlComponents uc;
  15113. ASSERT_TRUE(detail::parse_url("http://example.com:/path", uc));
  15114. EXPECT_TRUE(uc.port.empty());
  15115. EXPECT_EQ("/path", uc.path);
  15116. }
  15117. {
  15118. // parse_url accepts any port string; validation is done by parse_port
  15119. detail::UrlComponents uc;
  15120. ASSERT_TRUE(detail::parse_url("http://example.com:abc/path", uc));
  15121. EXPECT_EQ("abc", uc.port);
  15122. }
  15123. }
  15124. TEST(ParseUrlTest, WebSocketPatterns) {
  15125. {
  15126. detail::UrlComponents uc;
  15127. ASSERT_TRUE(detail::parse_url("ws://echo.example.com:8080/ws", uc));
  15128. EXPECT_EQ("ws", uc.scheme);
  15129. EXPECT_EQ("echo.example.com", uc.host);
  15130. EXPECT_EQ("8080", uc.port);
  15131. EXPECT_EQ("/ws", uc.path);
  15132. }
  15133. {
  15134. detail::UrlComponents uc;
  15135. ASSERT_TRUE(detail::parse_url("wss://echo.example.com/ws", uc));
  15136. EXPECT_EQ("wss", uc.scheme);
  15137. EXPECT_EQ("echo.example.com", uc.host);
  15138. EXPECT_TRUE(uc.port.empty());
  15139. EXPECT_EQ("/ws", uc.path);
  15140. }
  15141. }
  15142. TEST(ParseUrlTest, QueryOnly) {
  15143. detail::UrlComponents uc;
  15144. ASSERT_TRUE(detail::parse_url("?q=1&r=2", uc));
  15145. EXPECT_TRUE(uc.host.empty());
  15146. EXPECT_TRUE(uc.path.empty());
  15147. EXPECT_EQ("?q=1&r=2", uc.query);
  15148. }
  15149. TEST(ParseUrlTest, SchemeRelativeWithPort) {
  15150. detail::UrlComponents uc;
  15151. ASSERT_TRUE(detail::parse_url("//example.com:443/path", uc));
  15152. EXPECT_TRUE(uc.scheme.empty());
  15153. EXPECT_EQ("example.com", uc.host);
  15154. EXPECT_EQ("443", uc.port);
  15155. EXPECT_EQ("/path", uc.path);
  15156. }
  15157. TEST(UniversalClientImplTest, Ipv6LiteralAddress) {
  15158. // If ipv6 regex working, regex match codepath is taken.
  15159. // else port will default to 80 in Client impl
  15160. int clientImplMagicPort = 80;
  15161. int port = 4321;
  15162. // above ports must be different to avoid false negative
  15163. EXPECT_NE(clientImplMagicPort, port);
  15164. std::string ipV6TestURL = "http://[ff06::c3]";
  15165. Client cli(ipV6TestURL + ":" + std::to_string(port), CLIENT_CERT_FILE,
  15166. CLIENT_PRIVATE_KEY_FILE);
  15167. EXPECT_EQ(cli.port(), port);
  15168. }
  15169. TEST(FileSystemTest, FileAndDirExistenceCheck) {
  15170. auto file_path = "./www/dir/index.html";
  15171. auto dir_path = "./www/dir";
  15172. detail::FileStat stat_file(file_path);
  15173. EXPECT_TRUE(stat_file.is_file());
  15174. EXPECT_FALSE(stat_file.is_dir());
  15175. detail::FileStat stat_dir(dir_path);
  15176. EXPECT_FALSE(stat_dir.is_file());
  15177. EXPECT_TRUE(stat_dir.is_dir());
  15178. }
  15179. TEST(MakeHostAndPortStringTest, VariousPatterns) {
  15180. // IPv4 with default HTTP port (80)
  15181. EXPECT_EQ("example.com",
  15182. detail::make_host_and_port_string("example.com", 80, false));
  15183. // IPv4 with default HTTPS port (443)
  15184. EXPECT_EQ("example.com",
  15185. detail::make_host_and_port_string("example.com", 443, true));
  15186. // IPv4 with non-default HTTP port
  15187. EXPECT_EQ("example.com:8080",
  15188. detail::make_host_and_port_string("example.com", 8080, false));
  15189. // IPv4 with non-default HTTPS port
  15190. EXPECT_EQ("example.com:8443",
  15191. detail::make_host_and_port_string("example.com", 8443, true));
  15192. // IPv6 with default HTTP port (80)
  15193. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 80, false));
  15194. // IPv6 with default HTTPS port (443)
  15195. EXPECT_EQ("[::1]", detail::make_host_and_port_string("::1", 443, true));
  15196. // IPv6 with non-default HTTP port
  15197. EXPECT_EQ("[::1]:8080",
  15198. detail::make_host_and_port_string("::1", 8080, false));
  15199. // IPv6 with non-default HTTPS port
  15200. EXPECT_EQ("[::1]:8443", detail::make_host_and_port_string("::1", 8443, true));
  15201. // IPv6 full address with default port
  15202. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
  15203. detail::make_host_and_port_string(
  15204. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 443, true));
  15205. // IPv6 full address with non-default port
  15206. EXPECT_EQ("[2001:0db8:85a3:0000:0000:8a2e:0370:7334]:9000",
  15207. detail::make_host_and_port_string(
  15208. "2001:0db8:85a3:0000:0000:8a2e:0370:7334", 9000, false));
  15209. // IPv6 localhost with non-default port
  15210. EXPECT_EQ("[::1]:3000",
  15211. detail::make_host_and_port_string("::1", 3000, false));
  15212. // IPv6 with zone ID (link-local address) with default port
  15213. EXPECT_EQ("[fe80::1%eth0]",
  15214. detail::make_host_and_port_string("fe80::1%eth0", 80, false));
  15215. // IPv6 with zone ID (link-local address) with non-default port
  15216. EXPECT_EQ("[fe80::1%eth0]:8080",
  15217. detail::make_host_and_port_string("fe80::1%eth0", 8080, false));
  15218. // Edge case: Port 443 with is_ssl=false (should add port)
  15219. EXPECT_EQ("example.com:443",
  15220. detail::make_host_and_port_string("example.com", 443, false));
  15221. // Edge case: Port 80 with is_ssl=true (should add port)
  15222. EXPECT_EQ("example.com:80",
  15223. detail::make_host_and_port_string("example.com", 80, true));
  15224. // IPv6 edge case: Port 443 with is_ssl=false (should add port)
  15225. EXPECT_EQ("[::1]:443", detail::make_host_and_port_string("::1", 443, false));
  15226. // IPv6 edge case: Port 80 with is_ssl=true (should add port)
  15227. EXPECT_EQ("[::1]:80", detail::make_host_and_port_string("::1", 80, true));
  15228. // Security fix: Already bracketed IPv6 should not get double brackets
  15229. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 80, false));
  15230. EXPECT_EQ("[::1]", detail::make_host_and_port_string("[::1]", 443, true));
  15231. EXPECT_EQ("[::1]:8080",
  15232. detail::make_host_and_port_string("[::1]", 8080, false));
  15233. EXPECT_EQ("[2001:db8::1]:8080",
  15234. detail::make_host_and_port_string("[2001:db8::1]", 8080, false));
  15235. EXPECT_EQ("[fe80::1%eth0]",
  15236. detail::make_host_and_port_string("[fe80::1%eth0]", 80, false));
  15237. EXPECT_EQ("[fe80::1%eth0]:8080",
  15238. detail::make_host_and_port_string("[fe80::1%eth0]", 8080, false));
  15239. // Edge case: Empty host (should return as-is)
  15240. EXPECT_EQ("", detail::make_host_and_port_string("", 80, false));
  15241. // Edge case: Colon in hostname (non-IPv6) - will be treated as IPv6
  15242. // This is a known limitation but shouldn't crash
  15243. EXPECT_EQ("[host:name]",
  15244. detail::make_host_and_port_string("host:name", 80, false));
  15245. // Port number edge cases (no validation, but should not crash)
  15246. EXPECT_EQ("example.com:0",
  15247. detail::make_host_and_port_string("example.com", 0, false));
  15248. EXPECT_EQ("example.com:-1",
  15249. detail::make_host_and_port_string("example.com", -1, false));
  15250. EXPECT_EQ("example.com:65535",
  15251. detail::make_host_and_port_string("example.com", 65535, false));
  15252. EXPECT_EQ("example.com:65536",
  15253. detail::make_host_and_port_string("example.com", 65536, false));
  15254. }
  15255. #ifdef CPPHTTPLIB_SSL_ENABLED
  15256. TEST(SSLClientHostHeaderTest, Issue2301_Online) {
  15257. httplib::SSLClient cli("roblox.com", 443);
  15258. cli.set_follow_location(true);
  15259. auto res = cli.Get("/");
  15260. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15261. EXPECT_EQ(StatusCode::OK_200, res->status);
  15262. }
  15263. #endif
  15264. TEST(DirtyDataRequestTest, HeadFieldValueContains_CR_LF_NUL) {
  15265. Server svr;
  15266. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  15267. EXPECT_EQ(res.status, 400);
  15268. });
  15269. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15270. auto se = detail::scope_exit([&] {
  15271. svr.stop();
  15272. thread.join();
  15273. ASSERT_FALSE(svr.is_running());
  15274. });
  15275. svr.wait_until_ready();
  15276. Client cli(HOST, PORT);
  15277. cli.Get("/test", Headers{{"Test", "_\n\r_\n\r_"}});
  15278. }
  15279. TEST(InvalidHeaderCharsTest, is_field_name) {
  15280. EXPECT_TRUE(detail::fields::is_field_name("exampleToken"));
  15281. EXPECT_TRUE(detail::fields::is_field_name("token123"));
  15282. EXPECT_TRUE(detail::fields::is_field_name("!#$%&'*+-.^_`|~"));
  15283. EXPECT_FALSE(detail::fields::is_field_name("example token"));
  15284. EXPECT_FALSE(detail::fields::is_field_name(" example_token"));
  15285. EXPECT_FALSE(detail::fields::is_field_name("example_token "));
  15286. EXPECT_FALSE(detail::fields::is_field_name("token@123"));
  15287. EXPECT_FALSE(detail::fields::is_field_name(""));
  15288. EXPECT_FALSE(detail::fields::is_field_name("example\rtoken"));
  15289. EXPECT_FALSE(detail::fields::is_field_name("example\ntoken"));
  15290. EXPECT_FALSE(detail::fields::is_field_name(std::string("\0", 1)));
  15291. EXPECT_FALSE(detail::fields::is_field_name("example\ttoken"));
  15292. }
  15293. TEST(InvalidHeaderCharsTest, is_field_value) {
  15294. EXPECT_TRUE(detail::fields::is_field_value("exampleToken"));
  15295. EXPECT_TRUE(detail::fields::is_field_value("token123"));
  15296. EXPECT_TRUE(detail::fields::is_field_value("!#$%&'*+-.^_`|~"));
  15297. EXPECT_TRUE(detail::fields::is_field_value("example token"));
  15298. EXPECT_FALSE(detail::fields::is_field_value(" example_token"));
  15299. EXPECT_FALSE(detail::fields::is_field_value("example_token "));
  15300. EXPECT_TRUE(detail::fields::is_field_value("token@123"));
  15301. EXPECT_TRUE(detail::fields::is_field_value(""));
  15302. EXPECT_FALSE(detail::fields::is_field_value("example\rtoken"));
  15303. EXPECT_FALSE(detail::fields::is_field_value("example\ntoken"));
  15304. EXPECT_FALSE(detail::fields::is_field_value(std::string("\0", 1)));
  15305. EXPECT_TRUE(detail::fields::is_field_value("example\ttoken"));
  15306. EXPECT_TRUE(detail::fields::is_field_value("0"));
  15307. }
  15308. TEST(InvalidHeaderCharsTest, OnServer) {
  15309. Server svr;
  15310. svr.Get("/test_name", [&](const Request &req, Response &res) {
  15311. std::string header = "Not Set";
  15312. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15313. res.set_header(header, "value");
  15314. res.set_content("Page Content Page Content", "text/plain");
  15315. });
  15316. svr.Get("/test_value", [&](const Request &req, Response &res) {
  15317. std::string header = "Not Set";
  15318. if (req.has_param("header")) { header = req.get_param_value("header"); }
  15319. res.set_header("X-Test", header);
  15320. res.set_content("Page Content Page Content", "text/plain");
  15321. });
  15322. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15323. auto se = detail::scope_exit([&] {
  15324. svr.stop();
  15325. thread.join();
  15326. ASSERT_FALSE(svr.is_running());
  15327. });
  15328. svr.wait_until_ready();
  15329. Client cli(HOST, PORT);
  15330. {
  15331. auto res = cli.Get(
  15332. R"(/test_name?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15333. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15334. EXPECT_EQ("Page Content Page Content", res->body);
  15335. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15336. }
  15337. {
  15338. auto res = cli.Get(
  15339. R"(/test_value?header=Value%00%0d%0aHEADER_KEY%3aHEADER_VALUE%0d%0a%0d%0aBODY_BODY_BODY)");
  15340. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  15341. EXPECT_EQ("Page Content Page Content", res->body);
  15342. EXPECT_FALSE(res->has_header("HEADER_KEY"));
  15343. }
  15344. }
  15345. TEST(InvalidHeaderValueTest, InvalidContentLength) {
  15346. auto handled = false;
  15347. Server svr;
  15348. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15349. thread t = thread([&] { svr.listen(HOST, PORT); });
  15350. auto se = detail::scope_exit([&] {
  15351. svr.stop();
  15352. t.join();
  15353. ASSERT_FALSE(svr.is_running());
  15354. ASSERT_FALSE(handled);
  15355. });
  15356. svr.wait_until_ready();
  15357. auto req = "POST /test HTTP/1.1\r\n"
  15358. "Content-Length: x\r\n"
  15359. "\r\n";
  15360. std::string response;
  15361. ASSERT_TRUE(send_request(1, req, &response));
  15362. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15363. response.substr(0, response.find("\r\n")));
  15364. }
  15365. // RFC 9110 Section 10.1.1: Expect is a comma-separated list, its value is
  15366. // case-insensitive, and a server that receives a 100-continue expectation in
  15367. // an HTTP/1.0 request MUST ignore it.
  15368. static void probe_expect(int port, const std::string &req, bool *got_100) {
  15369. std::string response;
  15370. ASSERT_TRUE(send_request(1, req, &response, port));
  15371. *got_100 = response.find("100 Continue") != std::string::npos;
  15372. }
  15373. class ExpectTokenTest : public ::testing::Test {
  15374. protected:
  15375. void SetUp() override {
  15376. svr_.Post("/p", [](const Request &, Response &res) {
  15377. res.set_content("ok", "text/plain");
  15378. });
  15379. port_ = svr_.bind_to_any_port(HOST);
  15380. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15381. svr_.wait_until_ready();
  15382. }
  15383. void TearDown() override {
  15384. svr_.stop();
  15385. if (thread_.joinable()) { thread_.join(); }
  15386. }
  15387. std::string request(const char *version, const char *expect_value) const {
  15388. return std::string("POST /p ") + version +
  15389. "\r\n"
  15390. "Host: localhost\r\n"
  15391. "Content-Length: 2\r\n"
  15392. "Connection: close\r\n"
  15393. "Expect: " +
  15394. expect_value +
  15395. "\r\n"
  15396. "\r\n"
  15397. "hi";
  15398. }
  15399. Server svr_;
  15400. int port_ = 0;
  15401. thread thread_;
  15402. };
  15403. TEST_F(ExpectTokenTest, Http11GetsTheInterimResponse) {
  15404. bool got_100 = false;
  15405. probe_expect(port_, request("HTTP/1.1", "100-continue"), &got_100);
  15406. EXPECT_TRUE(got_100);
  15407. }
  15408. TEST_F(ExpectTokenTest, Http10ExpectationIsIgnored) {
  15409. bool got_100 = true;
  15410. probe_expect(port_, request("HTTP/1.0", "100-continue"), &got_100);
  15411. EXPECT_FALSE(got_100);
  15412. }
  15413. TEST_F(ExpectTokenTest, ExpectationIsCaseInsensitive) {
  15414. bool got_100 = false;
  15415. probe_expect(port_, request("HTTP/1.1", "100-Continue"), &got_100);
  15416. EXPECT_TRUE(got_100);
  15417. }
  15418. TEST_F(ExpectTokenTest, ExpectationAmongOthersIsRecognized) {
  15419. bool got_100 = false;
  15420. probe_expect(port_, request("HTTP/1.1", "100-continue, foo"), &got_100);
  15421. EXPECT_TRUE(got_100);
  15422. }
  15423. // `100 Continue` is sent only when the server starts reading the body, so a
  15424. // request rejected before that never invites the client to send it. The
  15425. // requests below carry the expectation but withhold the body, as a client
  15426. // waiting for `100 Continue` would.
  15427. // A POST that expects `100 Continue` and withholds its two-byte body.
  15428. static std::string expect_headers_only(const std::string &path) {
  15429. return "POST " + path +
  15430. " HTTP/1.1\r\n"
  15431. "Host: localhost\r\n"
  15432. "Content-Length: 2\r\n"
  15433. "Expect: 100-continue\r\n"
  15434. "\r\n";
  15435. }
  15436. class ExpectLazyContinueTest : public ::testing::Test {
  15437. protected:
  15438. void SetUp() override {
  15439. svr_.set_pre_routing_handler([](const Request &req, Response &res) {
  15440. if (req.path == "/pre-routing") {
  15441. res.status = StatusCode::Unauthorized_401;
  15442. return Server::HandlerResponse::Handled;
  15443. }
  15444. return Server::HandlerResponse::Unhandled;
  15445. });
  15446. svr_.set_pre_request_handler([](const Request &req, Response &res) {
  15447. if (req.matched_route == "/pre-request") {
  15448. res.status = StatusCode::Forbidden_403;
  15449. return Server::HandlerResponse::Handled;
  15450. }
  15451. return Server::HandlerResponse::Unhandled;
  15452. });
  15453. svr_.Post("/pre-routing", [](const Request &, Response &res) {
  15454. res.set_content("ok", "text/plain");
  15455. });
  15456. svr_.Post("/pre-request", [](const Request &, Response &res) {
  15457. res.set_content("ok", "text/plain");
  15458. });
  15459. svr_.Post("/reader-used", [](const Request &, Response &res,
  15460. const ContentReader &content_reader) {
  15461. std::string body;
  15462. content_reader([&](const char *data, size_t len) {
  15463. body.append(data, len);
  15464. return true;
  15465. });
  15466. res.set_content(body, "text/plain");
  15467. });
  15468. svr_.Post("/reader-unused",
  15469. [](const Request &, Response &res, const ContentReader &) {
  15470. res.set_content("ignored", "text/plain");
  15471. });
  15472. port_ = svr_.bind_to_any_port(HOST);
  15473. thread_ = thread([&]() { svr_.listen_after_bind(); });
  15474. svr_.wait_until_ready();
  15475. }
  15476. void TearDown() override {
  15477. svr_.stop();
  15478. if (thread_.joinable()) { thread_.join(); }
  15479. }
  15480. // Sends `req` and reads until the server closes the connection. Returns
  15481. // false if the read had to wait for the client-side timeout instead.
  15482. bool send_until_closed(const std::string &req, std::string *resp) const {
  15483. auto start = std::chrono::steady_clock::now();
  15484. if (!send_request(3, req, resp, port_)) { return false; }
  15485. auto elapsed = std::chrono::steady_clock::now() - start;
  15486. return elapsed < std::chrono::seconds(2);
  15487. }
  15488. // The final response comes without `100 Continue`, and the server closes
  15489. // the connection since the body may or may not follow.
  15490. void expect_final_without_interim(const std::string &path,
  15491. const char *status_line) const {
  15492. std::string resp;
  15493. ASSERT_TRUE(send_until_closed(expect_headers_only(path), &resp));
  15494. EXPECT_EQ(std::string::npos, resp.find("100 Continue"));
  15495. EXPECT_EQ(0u, resp.find(status_line));
  15496. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15497. }
  15498. Server svr_;
  15499. int port_ = 0;
  15500. thread thread_;
  15501. };
  15502. TEST_F(ExpectLazyContinueTest, PreRoutingRejectsWithoutInterimResponse) {
  15503. expect_final_without_interim("/pre-routing", "HTTP/1.1 401");
  15504. }
  15505. TEST_F(ExpectLazyContinueTest, PreRequestRejectsWithoutInterimResponse) {
  15506. expect_final_without_interim("/pre-request", "HTTP/1.1 403");
  15507. }
  15508. TEST_F(ExpectLazyContinueTest, UnknownRouteRejectsWithoutInterimResponse) {
  15509. expect_final_without_interim("/nowhere", "HTTP/1.1 404");
  15510. }
  15511. TEST_F(ExpectLazyContinueTest, UnreadContentReaderClosesWithoutInterim) {
  15512. expect_final_without_interim("/reader-unused", "HTTP/1.1 200");
  15513. }
  15514. TEST_F(ExpectLazyContinueTest, ContentReaderGetsInterimResponse) {
  15515. // The body follows once `100 Continue` has had time to arrive.
  15516. auto req = expect_headers_only("/reader-used");
  15517. req.insert(req.size() - 2, "Connection: close\r\n");
  15518. std::string resp;
  15519. ASSERT_TRUE(send_request_in_parts(3, {req, "hi"}, &resp, port_));
  15520. EXPECT_EQ(0u, resp.find("HTTP/1.1 100 Continue"));
  15521. EXPECT_NE(std::string::npos, resp.find("HTTP/1.1 200"));
  15522. EXPECT_NE(std::string::npos, resp.find("hi"));
  15523. }
  15524. TEST_F(ExpectLazyContinueTest, ClientWithholdsBodyWhenRejected) {
  15525. // Large enough for the client to add `Expect: 100-continue` itself.
  15526. const size_t length = CPPHTTPLIB_EXPECT_100_THRESHOLD * 4;
  15527. std::atomic<bool> body_sent{false};
  15528. Client cli(HOST, port_);
  15529. auto res = cli.Post(
  15530. "/pre-request", length,
  15531. [&](size_t /*offset*/, size_t len, DataSink &sink) {
  15532. body_sent = true;
  15533. std::string chunk(len, 'x');
  15534. sink.write(chunk.data(), chunk.size());
  15535. return true;
  15536. },
  15537. "application/octet-stream");
  15538. ASSERT_TRUE(res);
  15539. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  15540. EXPECT_FALSE(body_sent);
  15541. }
  15542. TEST(Expect100ContinueHandlerTest, ExpectationFailedIsFinalResponse) {
  15543. Server svr;
  15544. svr.set_expect_100_continue_handler([](const Request &, Response &) {
  15545. return StatusCode::ExpectationFailed_417;
  15546. });
  15547. svr.Post("/p", [](const Request &, Response &res) {
  15548. res.set_content("ok", "text/plain");
  15549. });
  15550. auto port = svr.bind_to_any_port(HOST);
  15551. thread t = thread([&] { svr.listen_after_bind(); });
  15552. auto se = detail::scope_exit([&] {
  15553. svr.stop();
  15554. t.join();
  15555. });
  15556. svr.wait_until_ready();
  15557. std::string resp;
  15558. ASSERT_TRUE(send_request(3, expect_headers_only("/p"), &resp, port));
  15559. EXPECT_EQ(0u, resp.find("HTTP/1.1 417"));
  15560. EXPECT_NE(std::string::npos, resp.find("Connection: close"));
  15561. // Exactly one response: the route handler must not run after the 417.
  15562. EXPECT_EQ(std::string::npos, resp.find("HTTP/1.1", 1));
  15563. }
  15564. #ifndef _WIN32
  15565. TEST(Expect100ContinueTest, ServerClosesConnection) {
  15566. static constexpr char reject[] = "Unauthorized";
  15567. static constexpr char accept[] = "Upload accepted";
  15568. constexpr size_t total_size = 10 * 1024 * 1024 * 1024ULL;
  15569. Server svr;
  15570. svr.set_expect_100_continue_handler(
  15571. [](const Request & /*req*/, Response &res) {
  15572. res.status = StatusCode::Unauthorized_401;
  15573. res.set_content(reject, "text/plain");
  15574. return res.status;
  15575. });
  15576. svr.Post("/", [&](const Request & /*req*/, Response &res) {
  15577. res.set_content(accept, "text/plain");
  15578. });
  15579. auto thread = std::thread([&]() { svr.listen(HOST, PORT); });
  15580. auto se = detail::scope_exit([&] {
  15581. svr.stop();
  15582. thread.join();
  15583. ASSERT_FALSE(svr.is_running());
  15584. });
  15585. svr.wait_until_ready();
  15586. {
  15587. const auto curl = std::unique_ptr<CURL, decltype(&curl_easy_cleanup)>{
  15588. curl_easy_init(), &curl_easy_cleanup};
  15589. ASSERT_NE(curl, nullptr);
  15590. curl_easy_setopt(curl.get(), CURLOPT_URL, HOST);
  15591. curl_easy_setopt(curl.get(), CURLOPT_PORT, PORT);
  15592. curl_easy_setopt(curl.get(), CURLOPT_POST, 1L);
  15593. auto list = std::unique_ptr<curl_slist, decltype(&curl_slist_free_all)>{
  15594. curl_slist_append(nullptr, "Content-Type: application/octet-stream"),
  15595. &curl_slist_free_all};
  15596. ASSERT_NE(list, nullptr);
  15597. curl_easy_setopt(curl.get(), CURLOPT_HTTPHEADER, list.get());
  15598. struct read_data {
  15599. size_t read_size;
  15600. size_t total_size;
  15601. } data = {0, total_size};
  15602. using read_callback_t =
  15603. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15604. read_callback_t read_callback = [](char *ptr, size_t size, size_t nmemb,
  15605. void *userdata) -> size_t {
  15606. read_data *d = (read_data *)userdata;
  15607. if (!userdata || d->read_size >= d->total_size) { return 0; }
  15608. std::fill_n(ptr, size * nmemb, 'A');
  15609. d->read_size += size * nmemb;
  15610. return size * nmemb;
  15611. };
  15612. curl_easy_setopt(curl.get(), CURLOPT_READDATA, data);
  15613. curl_easy_setopt(curl.get(), CURLOPT_READFUNCTION, read_callback);
  15614. std::vector<char> buffer;
  15615. curl_easy_setopt(curl.get(), CURLOPT_WRITEDATA, &buffer);
  15616. using write_callback_t =
  15617. size_t (*)(char *ptr, size_t size, size_t nmemb, void *userdata);
  15618. write_callback_t write_callback = [](char *ptr, size_t size, size_t nmemb,
  15619. void *userdata) -> size_t {
  15620. std::vector<char> *buf = (std::vector<char> *)userdata;
  15621. buf->reserve(buf->size() + size * nmemb + 1);
  15622. buf->insert(buf->end(), (char *)ptr, (char *)ptr + size * nmemb);
  15623. return size * nmemb;
  15624. };
  15625. curl_easy_setopt(curl.get(), CURLOPT_WRITEFUNCTION, write_callback);
  15626. {
  15627. const auto res = curl_easy_perform(curl.get());
  15628. ASSERT_EQ(res, CURLE_OK);
  15629. }
  15630. {
  15631. auto response_code = long{};
  15632. const auto res =
  15633. curl_easy_getinfo(curl.get(), CURLINFO_RESPONSE_CODE, &response_code);
  15634. ASSERT_EQ(res, CURLE_OK);
  15635. ASSERT_EQ(response_code, StatusCode::Unauthorized_401);
  15636. }
  15637. {
  15638. auto dl = curl_off_t{};
  15639. const auto res =
  15640. curl_easy_getinfo(curl.get(), CURLINFO_SIZE_DOWNLOAD_T, &dl);
  15641. ASSERT_EQ(res, CURLE_OK);
  15642. ASSERT_EQ(dl, (curl_off_t)sizeof reject - 1);
  15643. }
  15644. {
  15645. buffer.push_back('\0');
  15646. ASSERT_STRCASEEQ(buffer.data(), reject);
  15647. }
  15648. }
  15649. }
  15650. #endif
  15651. #if defined(CPPHTTPLIB_OPENSSL_SUPPORT) && !defined(_WIN32)
  15652. // Regression test for #2458.
  15653. //
  15654. // A large request body (>= CPPHTTPLIB_EXPECT_100_THRESHOLD) makes the client
  15655. // auto-add `Expect: 100-continue`. Over TLS, the server's TLS 1.3 session
  15656. // ticket can make the client socket spuriously readable during the
  15657. // 100-continue wait. If the readiness is mistaken for an incoming response,
  15658. // the client withholds the body and then blocks reading a response that never
  15659. // comes, failing with `Failed to read connection`.
  15660. //
  15661. // A correct client (like curl) sends the body once no `100 Continue` arrives
  15662. // within the timeout. This raw OpenSSL server deliberately never sends
  15663. // `100 Continue`; the client must still deliver the body and receive 200.
  15664. TEST(Expect100ContinueTest, TLSServerOmits100Continue) {
  15665. signal(SIGPIPE, SIG_IGN);
  15666. const auto port = PORT + 4;
  15667. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  15668. ASSERT_NE(srv, INVALID_SOCKET);
  15669. int opt = 1;
  15670. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR, &opt, sizeof(opt));
  15671. sockaddr_in addr{};
  15672. addr.sin_family = AF_INET;
  15673. addr.sin_port = htons(static_cast<uint16_t>(port));
  15674. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  15675. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  15676. ASSERT_EQ(0, ::listen(srv, 1));
  15677. std::atomic<size_t> server_body_bytes{0};
  15678. auto server_thread = std::thread([&] {
  15679. sockaddr_in cli_addr{};
  15680. socklen_t cli_len = sizeof(cli_addr);
  15681. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  15682. if (cli == INVALID_SOCKET) { return; }
  15683. // Bound the lifetime of the server side so a buggy client (which never
  15684. // sends the body) cannot make this thread block forever on join.
  15685. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 4, 0);
  15686. SSL_CTX *ctx = SSL_CTX_new(TLS_server_method());
  15687. SSL_CTX_set_min_proto_version(ctx, TLS1_3_VERSION);
  15688. SSL_CTX_use_certificate_file(ctx, SERVER_CERT_FILE, SSL_FILETYPE_PEM);
  15689. SSL_CTX_use_PrivateKey_file(ctx, SERVER_PRIVATE_KEY_FILE, SSL_FILETYPE_PEM);
  15690. SSL *ssl = SSL_new(ctx);
  15691. SSL_set_fd(ssl, static_cast<int>(cli));
  15692. if (SSL_accept(ssl) > 0) {
  15693. // Read the request headers. Reading here also flushes the TLS 1.3
  15694. // session tickets to the client. Deliberately do NOT send
  15695. // `100 Continue`.
  15696. std::string buf;
  15697. char tmp[1024];
  15698. while (buf.find("\r\n\r\n") == std::string::npos) {
  15699. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15700. if (n <= 0) { break; }
  15701. buf.append(tmp, static_cast<size_t>(n));
  15702. }
  15703. // A correct client sends the body now; count what arrives.
  15704. auto pos = buf.find("\r\n\r\n");
  15705. size_t body = (pos == std::string::npos) ? 0 : buf.size() - (pos + 4);
  15706. while (body < 4096) {
  15707. auto n = SSL_read(ssl, tmp, sizeof(tmp));
  15708. if (n <= 0) { break; }
  15709. body += static_cast<size_t>(n);
  15710. }
  15711. server_body_bytes = body;
  15712. std::string resp = "HTTP/1.1 200 OK\r\nContent-Length: 2\r\n\r\nok";
  15713. SSL_write(ssl, resp.data(), static_cast<int>(resp.size()));
  15714. SSL_shutdown(ssl);
  15715. }
  15716. SSL_free(ssl);
  15717. detail::close_socket(cli);
  15718. SSL_CTX_free(ctx);
  15719. });
  15720. auto se = detail::scope_exit([&] {
  15721. server_thread.join();
  15722. detail::close_socket(srv);
  15723. });
  15724. SSLClient cli("127.0.0.1", port);
  15725. cli.enable_server_certificate_verification(false);
  15726. cli.set_connection_timeout(5, 0);
  15727. cli.set_read_timeout(3, 0); // short, so a hang surfaces quickly
  15728. // Body larger than CPPHTTPLIB_EXPECT_100_THRESHOLD (1024) -> auto Expect.
  15729. std::string body(4096, 'A');
  15730. auto res = cli.Put("/api/test", body, "application/json");
  15731. ASSERT_TRUE(res) << "request failed: " << to_string(res.error());
  15732. EXPECT_EQ(StatusCode::OK_200, res->status);
  15733. EXPECT_EQ(body.size(), server_body_bytes.load());
  15734. }
  15735. #endif
  15736. template <typename S, typename C>
  15737. inline void max_timeout_test(S &svr, C &cli, time_t timeout, time_t threshold) {
  15738. svr.Get("/stream", [&](const Request &, Response &res) {
  15739. auto data = new std::string("01234567890123456789");
  15740. res.set_content_provider(
  15741. data->size(), "text/plain",
  15742. [&, data](size_t offset, size_t length, DataSink &sink) {
  15743. const size_t DATA_CHUNK_SIZE = 4;
  15744. const auto &d = *data;
  15745. std::this_thread::sleep_for(std::chrono::seconds(1));
  15746. sink.write(&d[offset], std::min(length, DATA_CHUNK_SIZE));
  15747. return true;
  15748. },
  15749. [data](bool success) {
  15750. EXPECT_FALSE(success);
  15751. delete data;
  15752. });
  15753. });
  15754. svr.Get("/stream_without_length", [&](const Request &, Response &res) {
  15755. auto i = new size_t(0);
  15756. res.set_content_provider(
  15757. "text/plain",
  15758. [i](size_t, DataSink &sink) {
  15759. if (*i < 5) {
  15760. std::this_thread::sleep_for(std::chrono::seconds(1));
  15761. sink.write("abcd", 4);
  15762. (*i)++;
  15763. } else {
  15764. sink.done();
  15765. }
  15766. return true;
  15767. },
  15768. [i](bool success) {
  15769. EXPECT_FALSE(success);
  15770. delete i;
  15771. });
  15772. });
  15773. svr.Get("/chunked", [&](const Request &, Response &res) {
  15774. auto i = new size_t(0);
  15775. res.set_chunked_content_provider(
  15776. "text/plain",
  15777. [i](size_t, DataSink &sink) {
  15778. if (*i < 5) {
  15779. std::this_thread::sleep_for(std::chrono::seconds(1));
  15780. sink.os << "abcd";
  15781. (*i)++;
  15782. } else {
  15783. sink.done();
  15784. }
  15785. return true;
  15786. },
  15787. [i](bool success) {
  15788. EXPECT_FALSE(success);
  15789. delete i;
  15790. });
  15791. });
  15792. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  15793. auto se = detail::scope_exit([&] {
  15794. svr.stop();
  15795. listen_thread.join();
  15796. ASSERT_FALSE(svr.is_running());
  15797. });
  15798. svr.wait_until_ready();
  15799. cli.set_max_timeout(std::chrono::milliseconds(timeout));
  15800. {
  15801. auto start = std::chrono::steady_clock::now();
  15802. auto res = cli.Get("/stream");
  15803. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15804. std::chrono::steady_clock::now() - start)
  15805. .count();
  15806. ASSERT_FALSE(res);
  15807. EXPECT_EQ(Error::Read, res.error());
  15808. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15809. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15810. }
  15811. {
  15812. auto start = std::chrono::steady_clock::now();
  15813. auto res = cli.Get("/stream_without_length");
  15814. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15815. std::chrono::steady_clock::now() - start)
  15816. .count();
  15817. ASSERT_FALSE(res);
  15818. EXPECT_EQ(Error::Read, res.error());
  15819. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15820. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15821. }
  15822. {
  15823. auto start = std::chrono::steady_clock::now();
  15824. auto res = cli.Get("/chunked", [&](const char *data, size_t data_length) {
  15825. EXPECT_EQ("abcd", string(data, data_length));
  15826. return true;
  15827. });
  15828. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  15829. std::chrono::steady_clock::now() - start)
  15830. .count();
  15831. ASSERT_FALSE(res);
  15832. EXPECT_EQ(Error::Read, res.error());
  15833. EXPECT_TRUE(timeout <= elapsed && elapsed < timeout + threshold)
  15834. << "Timeout exceeded by " << (elapsed - timeout) << "ms";
  15835. }
  15836. }
  15837. TEST(MaxTimeoutTest, ContentStream) {
  15838. time_t timeout = 2000;
  15839. time_t threshold = 200;
  15840. Server svr;
  15841. Client cli("localhost", PORT);
  15842. max_timeout_test(svr, cli, timeout, threshold);
  15843. }
  15844. #ifdef CPPHTTPLIB_SSL_ENABLED
  15845. TEST(MaxTimeoutTest, ContentStreamSSL) {
  15846. time_t timeout = 2000;
  15847. time_t threshold = 1200; // SSL_shutdown is slow on some operating systems.
  15848. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  15849. SSLClient cli("localhost", PORT);
  15850. cli.enable_server_certificate_verification(false);
  15851. max_timeout_test(svr, cli, timeout, threshold);
  15852. }
  15853. #endif
  15854. class EventDispatcher {
  15855. public:
  15856. EventDispatcher() {}
  15857. bool wait_event(DataSink *sink) {
  15858. unique_lock<mutex> lk(m_);
  15859. int id = id_;
  15860. // Wait with timeout to prevent hanging if client disconnects
  15861. if (!cv_.wait_for(lk, std::chrono::seconds(5),
  15862. [&] { return cid_ == id; })) {
  15863. return false; // Timeout occurred
  15864. }
  15865. sink->write(message_.data(), message_.size());
  15866. return true;
  15867. }
  15868. void send_event(const string &message) {
  15869. lock_guard<mutex> lk(m_);
  15870. cid_ = id_++;
  15871. message_ = message;
  15872. cv_.notify_all();
  15873. }
  15874. private:
  15875. mutex m_;
  15876. condition_variable cv_;
  15877. atomic_int id_{0};
  15878. atomic_int cid_{-1};
  15879. string message_;
  15880. };
  15881. TEST(ClientInThreadTest, Issue2068) {
  15882. EventDispatcher ed;
  15883. Server svr;
  15884. svr.Get("/event1", [&](const Request & /*req*/, Response &res) {
  15885. res.set_chunked_content_provider("text/event-stream",
  15886. [&](size_t /*offset*/, DataSink &sink) {
  15887. return ed.wait_event(&sink);
  15888. });
  15889. });
  15890. auto listen_thread = std::thread([&svr]() { svr.listen(HOST, PORT); });
  15891. svr.wait_until_ready();
  15892. thread event_thread([&] {
  15893. int id = 0;
  15894. while (svr.is_running()) {
  15895. this_thread::sleep_for(chrono::milliseconds(500));
  15896. std::stringstream ss;
  15897. ss << "data: " << id << "\n\n";
  15898. ed.send_event(ss.str());
  15899. id++;
  15900. }
  15901. });
  15902. auto se = detail::scope_exit([&] {
  15903. svr.stop();
  15904. listen_thread.join();
  15905. event_thread.join();
  15906. ASSERT_FALSE(svr.is_running());
  15907. });
  15908. {
  15909. auto client = detail::make_unique<Client>(HOST, PORT);
  15910. client->set_read_timeout(std::chrono::minutes(10));
  15911. std::atomic<bool> stop{false};
  15912. std::thread t([&] {
  15913. client->Get("/event1",
  15914. [&](const char *, size_t) -> bool { return !stop; });
  15915. });
  15916. std::this_thread::sleep_for(std::chrono::seconds(2));
  15917. stop = true;
  15918. client->stop();
  15919. t.join();
  15920. // Reset client after thread has finished
  15921. client.reset();
  15922. }
  15923. }
  15924. TEST(RequestSmugglingTest, DuplicateContentLengthDifferentValues) {
  15925. auto handled = false;
  15926. Server svr;
  15927. svr.Post("/test", [&](const Request &, Response &) { handled = true; });
  15928. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15929. auto se = detail::scope_exit([&] {
  15930. svr.stop();
  15931. t.join();
  15932. ASSERT_FALSE(svr.is_running());
  15933. ASSERT_FALSE(handled);
  15934. });
  15935. svr.wait_until_ready();
  15936. // Two Content-Length headers with different values — must be rejected
  15937. auto req = "POST /test HTTP/1.1\r\n"
  15938. "Content-Length: 5\r\n"
  15939. "Content-Length: 10\r\n"
  15940. "\r\n"
  15941. "hello";
  15942. std::string response;
  15943. ASSERT_TRUE(send_request(1, req, &response));
  15944. ASSERT_EQ("HTTP/1.1 400 Bad Request",
  15945. response.substr(0, response.find("\r\n")));
  15946. }
  15947. TEST(RequestSmugglingTest, DuplicateContentLengthSameValues) {
  15948. auto handled = false;
  15949. Server svr;
  15950. svr.Post("/test", [&](const Request &, Response &res) {
  15951. handled = true;
  15952. res.set_content("ok", "text/plain");
  15953. });
  15954. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15955. auto se = detail::scope_exit([&] {
  15956. svr.stop();
  15957. t.join();
  15958. ASSERT_FALSE(svr.is_running());
  15959. ASSERT_TRUE(handled);
  15960. });
  15961. svr.wait_until_ready();
  15962. // Two Content-Length headers with same value — should be accepted (RFC 9110)
  15963. auto req = "POST /test HTTP/1.1\r\n"
  15964. "Content-Length: 5\r\n"
  15965. "Content-Length: 5\r\n"
  15966. "\r\n"
  15967. "hello";
  15968. std::string response;
  15969. ASSERT_TRUE(send_request(1, req, &response));
  15970. ASSERT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  15971. }
  15972. TEST(HeaderSmugglingTest, ChunkedTrailerHeadersMerged) {
  15973. Server svr;
  15974. svr.Get("/", [](const Request &req, Response &res) {
  15975. EXPECT_EQ(2U, req.trailers.size());
  15976. EXPECT_FALSE(req.has_trailer("[invalid key...]"));
  15977. // Denied
  15978. EXPECT_FALSE(req.has_trailer("Content-Length"));
  15979. EXPECT_FALSE(req.has_trailer("X-Forwarded-For"));
  15980. // Accepted
  15981. EXPECT_TRUE(req.has_trailer("X-Hello"));
  15982. EXPECT_EQ(req.get_trailer_value("X-Hello"), "hello");
  15983. EXPECT_TRUE(req.has_trailer("X-World"));
  15984. EXPECT_EQ(req.get_trailer_value("X-World"), "world");
  15985. res.set_content("ok", "text/plain");
  15986. });
  15987. thread t = thread([&]() { svr.listen(HOST, PORT); });
  15988. auto se = detail::scope_exit([&] {
  15989. svr.stop();
  15990. t.join();
  15991. ASSERT_FALSE(svr.is_running());
  15992. });
  15993. svr.wait_until_ready();
  15994. const std::string req = "GET / HTTP/1.1\r\n"
  15995. "Transfer-Encoding: chunked\r\n"
  15996. "Trailer: X-Hello, X-World, X-AAA, X-BBB\r\n"
  15997. "\r\n"
  15998. "0\r\n"
  15999. "Content-Length: 10\r\n"
  16000. "Host: internal.local\r\n"
  16001. "Content-Type: malicious/content\r\n"
  16002. "Cookie: any\r\n"
  16003. "Set-Cookie: any\r\n"
  16004. "X-Forwarded-For: attacker.com\r\n"
  16005. "X-Real-Ip: 1.1.1.1\r\n"
  16006. "X-Hello: hello\r\n"
  16007. "X-World: world\r\n"
  16008. "\r\n";
  16009. std::string res;
  16010. ASSERT_TRUE(send_request(1, req, &res));
  16011. }
  16012. // RFC 9110 Section 5.2 and 5.3: a comma-separated list field may be sent as
  16013. // several field lines, and the combined value is what has to be parsed. A
  16014. // Trailer field split across lines therefore declares every name it lists;
  16015. // reading only the first line silently drops the trailers the later lines
  16016. // declare. The prohibited-trailer filter still applies to every line.
  16017. TEST(HeaderSmugglingTest, DuplicateTrailerFieldLinesDeclareAllTrailers) {
  16018. Server svr;
  16019. size_t observed_trailer_count = 0;
  16020. std::string observed_hello;
  16021. std::string observed_world;
  16022. bool observed_content_length = true;
  16023. svr.Get("/", [&](const Request &req, Response &res) {
  16024. observed_trailer_count = req.trailers.size();
  16025. observed_hello = req.get_trailer_value("X-Hello");
  16026. observed_world = req.get_trailer_value("X-World");
  16027. observed_content_length = req.has_trailer("Content-Length");
  16028. res.set_content("ok", "text/plain");
  16029. });
  16030. auto port = svr.bind_to_any_port(HOST);
  16031. thread t = thread([&]() { svr.listen_after_bind(); });
  16032. auto se = detail::scope_exit([&] {
  16033. svr.stop();
  16034. t.join();
  16035. ASSERT_FALSE(svr.is_running());
  16036. });
  16037. svr.wait_until_ready();
  16038. const std::string req = "GET / HTTP/1.1\r\n"
  16039. "Transfer-Encoding: chunked\r\n"
  16040. "Trailer: X-Hello\r\n"
  16041. "Trailer: X-World, Content-Length\r\n"
  16042. "\r\n"
  16043. "0\r\n"
  16044. "X-Hello: hello\r\n"
  16045. "X-World: world\r\n"
  16046. "Content-Length: 10\r\n"
  16047. "\r\n";
  16048. std::string res;
  16049. ASSERT_TRUE(send_request(1, req, &res, port));
  16050. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, 15));
  16051. // Accepted: both field lines contribute to the declared set
  16052. EXPECT_EQ(2U, observed_trailer_count);
  16053. EXPECT_EQ(observed_hello, "hello");
  16054. EXPECT_EQ(observed_world, "world");
  16055. // Denied: a prohibited name stays prohibited on a later field line
  16056. EXPECT_FALSE(observed_content_length);
  16057. }
  16058. // Undeclared trailer fields must count toward the trailer limit too. Otherwise
  16059. // a peer can keep the trailer-parsing loop running indefinitely by sending an
  16060. // unbounded run of fields that are never declared, because the counter would
  16061. // only advance for declared fields.
  16062. TEST(HeaderSmugglingTest, UndeclaredTrailerFieldsCountTowardLimit) {
  16063. Server svr;
  16064. bool handler_called = false;
  16065. svr.Get("/", [&](const Request & /*req*/, Response &res) {
  16066. handler_called = true;
  16067. res.set_content("ok", "text/plain");
  16068. });
  16069. auto port = svr.bind_to_any_port(HOST);
  16070. thread t = thread([&]() { svr.listen_after_bind(); });
  16071. auto se = detail::scope_exit([&] {
  16072. svr.stop();
  16073. t.join();
  16074. ASSERT_FALSE(svr.is_running());
  16075. });
  16076. svr.wait_until_ready();
  16077. // Declare nothing, then send far more undeclared trailer fields than the
  16078. // header-count limit. Parsing must stop and reject the request rather than
  16079. // read every line.
  16080. std::string req = "GET / HTTP/1.1\r\n"
  16081. "Transfer-Encoding: chunked\r\n"
  16082. "\r\n"
  16083. "0\r\n";
  16084. for (int i = 0; i < CPPHTTPLIB_HEADER_MAX_COUNT + 10; i++) {
  16085. req += "X-Undeclared-" + std::to_string(i) + ": v\r\n";
  16086. }
  16087. req += "\r\n";
  16088. std::string res;
  16089. ASSERT_TRUE(send_request(1, req, &res, port));
  16090. // The request is rejected before the handler runs.
  16091. EXPECT_FALSE(handler_called);
  16092. EXPECT_EQ("HTTP/1.1 400 Bad Request", res.substr(0, res.find("\r\n")));
  16093. }
  16094. // The set of declared trailer names is capped so a peer cannot grow it without
  16095. // bound (an unkeyed hash set would otherwise be a hash-flooding target). A name
  16096. // declared past the cap is not honored, even if the field is actually sent.
  16097. TEST(HeaderSmugglingTest, DeclaredTrailerNamesAreCappedAtHeaderMaxCount) {
  16098. Server svr;
  16099. // One name inside the cap and one past it, so the test tracks the cap rather
  16100. // than a fixed count.
  16101. constexpr int declared_count = CPPHTTPLIB_HEADER_MAX_COUNT + 50;
  16102. const std::string within_cap_name = "X-T-0";
  16103. const std::string past_cap_name = "X-T-" + std::to_string(declared_count - 1);
  16104. bool observed_within_cap = false;
  16105. bool observed_past_cap = false;
  16106. svr.Get("/", [&](const Request &req, Response &res) {
  16107. observed_within_cap = req.has_trailer(within_cap_name);
  16108. observed_past_cap = req.has_trailer(past_cap_name);
  16109. res.set_content("ok", "text/plain");
  16110. });
  16111. auto port = svr.bind_to_any_port(HOST);
  16112. thread t = thread([&]() { svr.listen_after_bind(); });
  16113. auto se = detail::scope_exit([&] {
  16114. svr.stop();
  16115. t.join();
  16116. ASSERT_FALSE(svr.is_running());
  16117. });
  16118. svr.wait_until_ready();
  16119. // Declare more trailer names than the cap in a single Trailer field, then
  16120. // actually send the first (within the cap) and the last (past it).
  16121. std::string trailer_decl = "Trailer: ";
  16122. for (int i = 0; i < declared_count; i++) {
  16123. if (i != 0) { trailer_decl += ", "; }
  16124. trailer_decl += "X-T-" + std::to_string(i);
  16125. }
  16126. trailer_decl += "\r\n";
  16127. const std::string req = "GET / HTTP/1.1\r\n"
  16128. "Transfer-Encoding: chunked\r\n" +
  16129. trailer_decl +
  16130. "\r\n"
  16131. "0\r\n" +
  16132. within_cap_name + ": a\r\n" + past_cap_name +
  16133. ": b\r\n"
  16134. "\r\n";
  16135. std::string res;
  16136. ASSERT_TRUE(send_request(1, req, &res, port));
  16137. EXPECT_EQ("HTTP/1.1 200 OK", res.substr(0, res.find("\r\n")));
  16138. // A name within the cap is honored; one declared past the cap is dropped.
  16139. EXPECT_TRUE(observed_within_cap);
  16140. EXPECT_FALSE(observed_past_cap);
  16141. }
  16142. // A direct client that is not listed in trusted_proxies must not be able to
  16143. // spoof req.remote_addr by sending an arbitrary X-Forwarded-For header. Only
  16144. // the peer address on the actual TCP connection determines whether the
  16145. // header is honored.
  16146. TEST(ForwardedHeadersTest, UntrustedDirectClientCannotSpoofXFF) {
  16147. Server svr;
  16148. // Deliberately does NOT include the loopback address the test client
  16149. // actually connects from, so the direct connection is not a trusted proxy.
  16150. svr.set_trusted_proxies({"203.0.113.66"});
  16151. std::string observed_remote_addr;
  16152. svr.Get("/ip", [&](const Request &req, Response &res) {
  16153. observed_remote_addr = req.remote_addr;
  16154. res.set_content("ok", "text/plain");
  16155. });
  16156. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16157. auto se = detail::scope_exit([&] {
  16158. svr.stop();
  16159. t.join();
  16160. ASSERT_FALSE(svr.is_running());
  16161. });
  16162. svr.wait_until_ready();
  16163. Client cli(HOST, PORT);
  16164. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "9.9.9.9"}});
  16165. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16166. EXPECT_EQ(StatusCode::OK_200, res->status);
  16167. // The connecting peer is not a trusted proxy, so the spoofed header must be
  16168. // ignored entirely and the real connection-level address retained.
  16169. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16170. observed_remote_addr == "127.0.0.1");
  16171. }
  16172. TEST(ForwardedHeadersTest, NoProxiesSetting) {
  16173. Server svr;
  16174. std::string observed_remote_addr;
  16175. std::string observed_xff;
  16176. svr.Get("/ip", [&](const Request &req, Response &res) {
  16177. observed_remote_addr = req.remote_addr;
  16178. observed_xff = req.get_header_value("X-Forwarded-For");
  16179. res.set_content("ok", "text/plain");
  16180. });
  16181. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16182. auto se = detail::scope_exit([&] {
  16183. svr.stop();
  16184. t.join();
  16185. ASSERT_FALSE(svr.is_running());
  16186. });
  16187. svr.wait_until_ready();
  16188. Client cli(HOST, PORT);
  16189. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", "203.0.113.66"}});
  16190. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16191. EXPECT_EQ(StatusCode::OK_200, res->status);
  16192. EXPECT_EQ(observed_xff, "203.0.113.66");
  16193. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16194. observed_remote_addr == "127.0.0.1");
  16195. }
  16196. TEST(ForwardedHeadersTest, NoForwardedHeaders) {
  16197. Server svr;
  16198. svr.set_trusted_proxies({"203.0.113.66"});
  16199. std::string observed_remote_addr;
  16200. std::string observed_xff;
  16201. svr.Get("/ip", [&](const Request &req, Response &res) {
  16202. observed_remote_addr = req.remote_addr;
  16203. observed_xff = req.get_header_value("X-Forwarded-For");
  16204. res.set_content("ok", "text/plain");
  16205. });
  16206. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16207. auto se = detail::scope_exit([&] {
  16208. svr.stop();
  16209. t.join();
  16210. ASSERT_FALSE(svr.is_running());
  16211. });
  16212. svr.wait_until_ready();
  16213. Client cli(HOST, PORT);
  16214. auto res = cli.Get("/ip");
  16215. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16216. EXPECT_EQ(StatusCode::OK_200, res->status);
  16217. EXPECT_EQ(observed_xff, "");
  16218. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16219. observed_remote_addr == "127.0.0.1");
  16220. }
  16221. TEST(ForwardedHeadersTest, SingleTrustedProxy_UsesIPBeforeTrusted) {
  16222. Server svr;
  16223. // Include the loopback address the test client actually connects from, so
  16224. // the direct connection itself is recognized as the trusted proxy hop.
  16225. svr.set_trusted_proxies({"203.0.113.66", "::1", "127.0.0.1"});
  16226. std::string observed_remote_addr;
  16227. std::string observed_xff;
  16228. svr.Get("/ip", [&](const Request &req, Response &res) {
  16229. observed_remote_addr = req.remote_addr;
  16230. observed_xff = req.get_header_value("X-Forwarded-For");
  16231. res.set_content("ok", "text/plain");
  16232. });
  16233. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16234. auto se = detail::scope_exit([&] {
  16235. svr.stop();
  16236. t.join();
  16237. ASSERT_FALSE(svr.is_running());
  16238. });
  16239. svr.wait_until_ready();
  16240. Client cli(HOST, PORT);
  16241. auto res = cli.Get(
  16242. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66"}});
  16243. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16244. EXPECT_EQ(StatusCode::OK_200, res->status);
  16245. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66");
  16246. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16247. }
  16248. TEST(ForwardedHeadersTest, MultipleTrustedProxies_UsesClientIP) {
  16249. Server svr;
  16250. svr.set_trusted_proxies({"203.0.113.66", "192.0.2.45", "::1", "127.0.0.1"});
  16251. std::string observed_remote_addr;
  16252. std::string observed_xff;
  16253. svr.Get("/ip", [&](const Request &req, Response &res) {
  16254. observed_remote_addr = req.remote_addr;
  16255. observed_xff = req.get_header_value("X-Forwarded-For");
  16256. res.set_content("ok", "text/plain");
  16257. });
  16258. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16259. auto se = detail::scope_exit([&] {
  16260. svr.stop();
  16261. t.join();
  16262. ASSERT_FALSE(svr.is_running());
  16263. });
  16264. svr.wait_until_ready();
  16265. Client cli(HOST, PORT);
  16266. auto res = cli.Get(
  16267. "/ip",
  16268. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16269. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16270. EXPECT_EQ(StatusCode::OK_200, res->status);
  16271. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16272. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16273. }
  16274. TEST(ForwardedHeadersTest, TrustedProxyNotInHeader_UsesRightmostIP) {
  16275. Server svr;
  16276. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16277. std::string observed_remote_addr;
  16278. std::string observed_xff;
  16279. svr.Get("/ip", [&](const Request &req, Response &res) {
  16280. observed_remote_addr = req.remote_addr;
  16281. observed_xff = req.get_header_value("X-Forwarded-For");
  16282. res.set_content("ok", "text/plain");
  16283. });
  16284. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16285. auto se = detail::scope_exit([&] {
  16286. svr.stop();
  16287. t.join();
  16288. ASSERT_FALSE(svr.is_running());
  16289. });
  16290. svr.wait_until_ready();
  16291. Client cli(HOST, PORT);
  16292. auto res = cli.Get(
  16293. "/ip", Headers{{"X-Forwarded-For", "198.51.100.23, 198.51.100.24"}});
  16294. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16295. EXPECT_EQ(StatusCode::OK_200, res->status);
  16296. // No listed hop is a trusted proxy, so the rightmost entry (the one written
  16297. // by the closest hop) is used. The leftmost entry is fully client-controlled
  16298. // and must not be selected.
  16299. EXPECT_EQ(observed_xff, "198.51.100.23, 198.51.100.24");
  16300. EXPECT_EQ(observed_remote_addr, "198.51.100.24");
  16301. }
  16302. TEST(ForwardedHeadersTest, SpoofedIPBeforeTrustedProxyIsIgnored) {
  16303. Server svr;
  16304. svr.set_trusted_proxies({"10.0.0.1", "::1", "127.0.0.1"});
  16305. std::string observed_remote_addr;
  16306. svr.Get("/ip", [&](const Request &req, Response &res) {
  16307. observed_remote_addr = req.remote_addr;
  16308. res.set_content("ok", "text/plain");
  16309. });
  16310. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16311. auto se = detail::scope_exit([&] {
  16312. svr.stop();
  16313. t.join();
  16314. ASSERT_FALSE(svr.is_running());
  16315. });
  16316. svr.wait_until_ready();
  16317. // The trusted proxy appends the address it saw (5.6.7.8). The client prepends
  16318. // a forged address and the trusted proxy's own address; the forged value must
  16319. // not win over the address the trusted proxy actually recorded.
  16320. Client cli(HOST, PORT);
  16321. auto res = cli.Get(
  16322. "/ip", Headers{{"X-Forwarded-For", "1.2.3.4, 10.0.0.1, 5.6.7.8"}});
  16323. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16324. EXPECT_EQ(StatusCode::OK_200, res->status);
  16325. EXPECT_EQ(observed_remote_addr, "5.6.7.8");
  16326. }
  16327. TEST(ForwardedHeadersTest, LastHopTrusted_SelectsImmediateLeftIP) {
  16328. Server svr;
  16329. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16330. std::string observed_remote_addr;
  16331. std::string observed_xff;
  16332. svr.Get("/ip", [&](const Request &req, Response &res) {
  16333. observed_remote_addr = req.remote_addr;
  16334. observed_xff = req.get_header_value("X-Forwarded-For");
  16335. res.set_content("ok", "text/plain");
  16336. });
  16337. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16338. auto se = detail::scope_exit([&] {
  16339. svr.stop();
  16340. t.join();
  16341. ASSERT_FALSE(svr.is_running());
  16342. });
  16343. svr.wait_until_ready();
  16344. Client cli(HOST, PORT);
  16345. auto res = cli.Get(
  16346. "/ip",
  16347. Headers{{"X-Forwarded-For", "198.51.100.23, 203.0.113.66, 192.0.2.45"}});
  16348. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16349. EXPECT_EQ(StatusCode::OK_200, res->status);
  16350. EXPECT_EQ(observed_xff, "198.51.100.23, 203.0.113.66, 192.0.2.45");
  16351. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16352. }
  16353. TEST(ForwardedHeadersTest, HandlesWhitespaceAroundIPs) {
  16354. Server svr;
  16355. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16356. std::string observed_remote_addr;
  16357. std::string observed_xff;
  16358. svr.Get("/ip", [&](const Request &req, Response &res) {
  16359. observed_remote_addr = req.remote_addr;
  16360. observed_xff = req.get_header_value("X-Forwarded-For");
  16361. res.set_content("ok", "text/plain");
  16362. });
  16363. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16364. auto se = detail::scope_exit([&] {
  16365. svr.stop();
  16366. t.join();
  16367. ASSERT_FALSE(svr.is_running());
  16368. });
  16369. svr.wait_until_ready();
  16370. std::string raw_req =
  16371. "GET /ip HTTP/1.1\r\n"
  16372. "Host: localhost\r\n"
  16373. "X-Forwarded-For: 198.51.100.23 , 203.0.113.66 , 192.0.2.45 \r\n"
  16374. "Connection: close\r\n"
  16375. "\r\n";
  16376. std::string out;
  16377. ASSERT_TRUE(send_request(5, raw_req, &out));
  16378. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16379. // Header parser trims surrounding whitespace of the header value
  16380. EXPECT_EQ(observed_xff, "198.51.100.23 , 203.0.113.66 , 192.0.2.45");
  16381. EXPECT_EQ(observed_remote_addr, "203.0.113.66");
  16382. }
  16383. // RFC 9110 Section 5.2 and 5.3: repeated field lines carry the same meaning as
  16384. // one comma-joined value, in the order received. Proxies such as HAProxy append
  16385. // their own X-Forwarded-For as a separate field line rather than extending the
  16386. // one the client sent, so every occurrence has to be taken into account.
  16387. // Reading only the first one hands back the address the client chose.
  16388. TEST(ForwardedHeadersTest, DuplicateFieldLines_JoinsAllOccurrences) {
  16389. Server svr;
  16390. svr.set_trusted_proxies({"192.0.2.45", "::1", "127.0.0.1"});
  16391. std::string observed_remote_addr;
  16392. size_t observed_xff_count = 0;
  16393. svr.Get("/ip", [&](const Request &req, Response &res) {
  16394. observed_remote_addr = req.remote_addr;
  16395. observed_xff_count = req.get_header_value_count("X-Forwarded-For");
  16396. res.set_content("ok", "text/plain");
  16397. });
  16398. auto port = svr.bind_to_any_port(HOST);
  16399. thread t = thread([&]() { svr.listen_after_bind(); });
  16400. auto se = detail::scope_exit([&] {
  16401. svr.stop();
  16402. t.join();
  16403. ASSERT_FALSE(svr.is_running());
  16404. });
  16405. svr.wait_until_ready();
  16406. // The client supplies the first field line; the trusted proxy appends the
  16407. // address it observed as a second one.
  16408. std::string raw_req = "GET /ip HTTP/1.1\r\n"
  16409. "Host: localhost\r\n"
  16410. "X-Forwarded-For: 1.2.3.4\r\n"
  16411. "X-Forwarded-For: 198.51.100.23, 192.0.2.45\r\n"
  16412. "Connection: close\r\n"
  16413. "\r\n";
  16414. std::string out;
  16415. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16416. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16417. EXPECT_EQ(observed_xff_count, 2U);
  16418. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16419. // The same chain spread over one field line per hop derives the same client
  16420. // address, i.e. the split and the comma-joined representations agree.
  16421. std::string per_hop_req = "GET /ip HTTP/1.1\r\n"
  16422. "Host: localhost\r\n"
  16423. "X-Forwarded-For: 1.2.3.4\r\n"
  16424. "X-Forwarded-For: 198.51.100.23\r\n"
  16425. "X-Forwarded-For: 192.0.2.45\r\n"
  16426. "Connection: close\r\n"
  16427. "\r\n";
  16428. out.clear();
  16429. ASSERT_TRUE(send_request(5, per_hop_req, &out, port));
  16430. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16431. EXPECT_EQ(observed_xff_count, 3U);
  16432. EXPECT_EQ(observed_remote_addr, "198.51.100.23");
  16433. }
  16434. // An X-Forwarded-For header whose value parses to zero IP segments must not
  16435. // crash the server (it used to call front() on an empty vector inside
  16436. // get_client_ip). The connection-level remote address must be retained instead.
  16437. static void run_malformed_xff_test(const std::string &xff_value) {
  16438. Server svr;
  16439. svr.set_trusted_proxies({"192.0.2.45"});
  16440. std::string observed_remote_addr;
  16441. svr.Get("/ip", [&](const Request &req, Response &res) {
  16442. observed_remote_addr = req.remote_addr;
  16443. res.set_content("ok", "text/plain");
  16444. });
  16445. int port = 0;
  16446. thread t = thread([&]() {
  16447. port = svr.bind_to_any_port(HOST);
  16448. svr.listen_after_bind();
  16449. });
  16450. auto se = detail::scope_exit([&] {
  16451. svr.stop();
  16452. t.join();
  16453. ASSERT_FALSE(svr.is_running());
  16454. });
  16455. svr.wait_until_ready();
  16456. Client cli(HOST, port);
  16457. auto res = cli.Get("/ip", Headers{{"X-Forwarded-For", xff_value}});
  16458. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16459. EXPECT_EQ(StatusCode::OK_200, res->status);
  16460. EXPECT_TRUE(observed_remote_addr == "::1" ||
  16461. observed_remote_addr == "127.0.0.1");
  16462. }
  16463. TEST(ForwardedHeadersTest, EmptyXForwardedFor_DoesNotCrash) {
  16464. run_malformed_xff_test("");
  16465. }
  16466. TEST(ForwardedHeadersTest, CommaOnlyXForwardedFor_DoesNotCrash) {
  16467. run_malformed_xff_test(",");
  16468. }
  16469. TEST(ForwardedHeadersTest, MultipleCommasXForwardedFor_DoesNotCrash) {
  16470. run_malformed_xff_test(", , ,");
  16471. }
  16472. // The same rule applies to Accept: a request whose acceptable types are spread
  16473. // over several field lines must be negotiated against all of them.
  16474. // RFC 9110 Section 7.6.1: Connection carries a comma-separated list of
  16475. // case-insensitive connection options. Comparing the whole field value against
  16476. // one option misses a client that sends several of them, and misses every
  16477. // casing but the one written in the comparison.
  16478. //
  16479. // Sends req, reads the response, then reuses the same socket for a second
  16480. // request to find out whether the server kept the connection.
  16481. static void probe_connection_reuse(int port, const std::string &req,
  16482. bool *announced_close, bool *reusable) {
  16483. auto error = Error::Success;
  16484. auto sock = detail::create_client_socket(
  16485. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  16486. /*connection_timeout_sec=*/5, 0,
  16487. /*read_timeout_sec=*/1, 0,
  16488. /*write_timeout_sec=*/5, 0, std::string(), error);
  16489. ASSERT_NE(sock, INVALID_SOCKET);
  16490. auto se = detail::scope_exit([&] { detail::close_socket(sock); });
  16491. const std::string second = "GET /keepalive HTTP/1.1\r\n"
  16492. "Host: localhost\r\n"
  16493. "Connection: close\r\n"
  16494. "\r\n";
  16495. std::string first_response;
  16496. std::string second_response;
  16497. detail::process_client_socket(
  16498. sock, 1, 0, 5, 0, 0, std::chrono::steady_clock::time_point::min(),
  16499. [&](Stream &strm) {
  16500. if (strm.write(req.data(), req.size()) !=
  16501. static_cast<ssize_t>(req.size())) {
  16502. return false;
  16503. }
  16504. char buf[512];
  16505. detail::stream_line_reader reader(strm, buf, sizeof(buf));
  16506. // Headers plus the two-byte body of the handler below
  16507. while (reader.getline()) {
  16508. first_response += reader.ptr();
  16509. if (first_response.find("ok") != std::string::npos) { break; }
  16510. }
  16511. if (strm.write(second.data(), second.size()) !=
  16512. static_cast<ssize_t>(second.size())) {
  16513. return true;
  16514. }
  16515. detail::stream_line_reader reader2(strm, buf, sizeof(buf));
  16516. while (reader2.getline()) {
  16517. second_response += reader2.ptr();
  16518. if (second_response.find("ok") != std::string::npos) { break; }
  16519. }
  16520. return true;
  16521. });
  16522. *announced_close =
  16523. first_response.find("Connection: close") != std::string::npos;
  16524. *reusable = second_response.find("HTTP/1.1 200") != std::string::npos;
  16525. }
  16526. class ConnectionTokenTest : public ::testing::Test {
  16527. protected:
  16528. void SetUp() override {
  16529. svr_.Get("/keepalive", [](const Request &, Response &res) {
  16530. res.set_content("ok", "text/plain");
  16531. });
  16532. port_ = svr_.bind_to_any_port(HOST);
  16533. thread_ = thread([&]() { svr_.listen_after_bind(); });
  16534. svr_.wait_until_ready();
  16535. }
  16536. void TearDown() override {
  16537. svr_.stop();
  16538. if (thread_.joinable()) { thread_.join(); }
  16539. }
  16540. Server svr_;
  16541. int port_ = 0;
  16542. thread thread_;
  16543. };
  16544. // "close" alongside another option still closes the connection, and the
  16545. // response says so rather than leaving the peer to discover it.
  16546. TEST_F(ConnectionTokenTest, CloseAmongSeveralOptionsIsHonored) {
  16547. bool announced_close = false;
  16548. bool reusable = true;
  16549. probe_connection_reuse(port_,
  16550. "GET /keepalive HTTP/1.1\r\n"
  16551. "Host: localhost\r\n"
  16552. "Connection: keep-alive, close\r\n"
  16553. "\r\n",
  16554. &announced_close, &reusable);
  16555. EXPECT_TRUE(announced_close);
  16556. EXPECT_FALSE(reusable);
  16557. }
  16558. // "close" split over two field lines is the same list, so it is honored too.
  16559. TEST_F(ConnectionTokenTest, CloseOnALaterFieldLineIsHonored) {
  16560. bool announced_close = false;
  16561. bool reusable = true;
  16562. probe_connection_reuse(port_,
  16563. "GET /keepalive HTTP/1.1\r\n"
  16564. "Host: localhost\r\n"
  16565. "Connection: keep-alive\r\n"
  16566. "Connection: close\r\n"
  16567. "\r\n",
  16568. &announced_close, &reusable);
  16569. EXPECT_TRUE(announced_close);
  16570. EXPECT_FALSE(reusable);
  16571. }
  16572. // Connection options are case-insensitive, so an HTTP/1.0 client asking for
  16573. // keep-alive in the spelling everyone actually sends keeps its connection.
  16574. TEST_F(ConnectionTokenTest, Http10KeepAliveIsCaseInsensitive) {
  16575. bool announced_close = false;
  16576. bool reusable = false;
  16577. probe_connection_reuse(port_,
  16578. "GET /keepalive HTTP/1.0\r\n"
  16579. "Host: localhost\r\n"
  16580. "Connection: keep-alive\r\n"
  16581. "\r\n",
  16582. &announced_close, &reusable);
  16583. EXPECT_FALSE(announced_close);
  16584. EXPECT_TRUE(reusable);
  16585. }
  16586. // A token the value merely contains is not the token itself.
  16587. TEST_F(ConnectionTokenTest, SubstringOfAnOptionIsNotTheOption) {
  16588. bool announced_close = false;
  16589. bool reusable = false;
  16590. probe_connection_reuse(port_,
  16591. "GET /keepalive HTTP/1.1\r\n"
  16592. "Host: localhost\r\n"
  16593. "Connection: notclose\r\n"
  16594. "\r\n",
  16595. &announced_close, &reusable);
  16596. EXPECT_FALSE(announced_close);
  16597. EXPECT_TRUE(reusable);
  16598. }
  16599. TEST(RepeatedFieldLinesTest, AcceptCombinesEveryFieldLine) {
  16600. Server svr;
  16601. std::vector<std::string> observed_types;
  16602. svr.Get("/", [&](const Request &req, Response &res) {
  16603. observed_types = req.accept_content_types;
  16604. res.set_content("ok", "text/plain");
  16605. });
  16606. auto port = svr.bind_to_any_port(HOST);
  16607. thread t = thread([&]() { svr.listen_after_bind(); });
  16608. auto se = detail::scope_exit([&] {
  16609. svr.stop();
  16610. t.join();
  16611. ASSERT_FALSE(svr.is_running());
  16612. });
  16613. svr.wait_until_ready();
  16614. Client cli(HOST, port);
  16615. Headers headers;
  16616. headers.emplace("Accept", "text/plain;q=0.5");
  16617. headers.emplace("Accept", "application/json");
  16618. auto res = cli.Get("/", headers);
  16619. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16620. EXPECT_EQ(StatusCode::OK_200, res->status);
  16621. // Sorted by q-value, so the second field line's type comes first
  16622. ASSERT_EQ(2U, observed_types.size());
  16623. EXPECT_EQ("application/json", observed_types[0]);
  16624. EXPECT_EQ("text/plain", observed_types[1]);
  16625. }
  16626. // RFC 9110 Section 5.6.1.2: empty list elements are parsed and ignored, so an
  16627. // empty field line must not contribute a bare comma to the combined value.
  16628. TEST(RepeatedFieldLinesTest, EmptyFieldLineDoesNotInjectComma) {
  16629. Server svr;
  16630. std::vector<std::string> observed_types;
  16631. svr.Get("/", [&](const Request &req, Response &res) {
  16632. observed_types = req.accept_content_types;
  16633. res.set_content("ok", "text/plain");
  16634. });
  16635. auto port = svr.bind_to_any_port(HOST);
  16636. thread t = thread([&]() { svr.listen_after_bind(); });
  16637. auto se = detail::scope_exit([&] {
  16638. svr.stop();
  16639. t.join();
  16640. ASSERT_FALSE(svr.is_running());
  16641. });
  16642. svr.wait_until_ready();
  16643. // Empty first field line, then a real one
  16644. std::string raw_req = "GET / HTTP/1.1\r\n"
  16645. "Host: localhost\r\n"
  16646. "Accept:\r\n"
  16647. "Accept: application/json\r\n"
  16648. "Connection: close\r\n"
  16649. "\r\n";
  16650. std::string out;
  16651. ASSERT_TRUE(send_request(5, raw_req, &out, port));
  16652. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  16653. ASSERT_EQ(1U, observed_types.size());
  16654. EXPECT_EQ("application/json", observed_types[0]);
  16655. }
  16656. // The skip in get_combined_header_value() is what keeps an empty field line
  16657. // from contributing a bare comma. Only a trailing empty field line exercises
  16658. // it: a leading one is already covered by the "combined is still empty" check,
  16659. // and parse_accept_header() now ignores the empty element either way, so the
  16660. // request-level test above can no longer tell the two apart.
  16661. TEST(RepeatedFieldLinesTest, EmptyFieldLineIsNotCombined) {
  16662. Headers headers;
  16663. headers.emplace("Accept", "text/html");
  16664. headers.emplace("Accept", "");
  16665. EXPECT_EQ("text/html", detail::get_combined_header_value(headers, "Accept"));
  16666. headers.clear();
  16667. headers.emplace("Accept", "");
  16668. headers.emplace("Accept", "application/json");
  16669. EXPECT_EQ("application/json",
  16670. detail::get_combined_header_value(headers, "Accept"));
  16671. }
  16672. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  16673. // An encoding offered on a later Accept-Encoding field line is still offered.
  16674. TEST(RepeatedFieldLinesTest, AcceptEncodingCombinesEveryFieldLine) {
  16675. Server svr;
  16676. svr.Get("/", [](const Request & /*req*/, Response &res) {
  16677. res.set_content(std::string(1024, 'x'), "text/plain");
  16678. });
  16679. auto port = svr.bind_to_any_port(HOST);
  16680. thread t = thread([&]() { svr.listen_after_bind(); });
  16681. auto se = detail::scope_exit([&] {
  16682. svr.stop();
  16683. t.join();
  16684. ASSERT_FALSE(svr.is_running());
  16685. });
  16686. svr.wait_until_ready();
  16687. Client cli(HOST, port);
  16688. cli.set_decompress(false);
  16689. Headers headers;
  16690. headers.emplace("Accept-Encoding", "identity");
  16691. headers.emplace("Accept-Encoding", "gzip");
  16692. auto res = cli.Get("/", headers);
  16693. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  16694. EXPECT_EQ(StatusCode::OK_200, res->status);
  16695. EXPECT_EQ("gzip", res->get_header_value("Content-Encoding"));
  16696. }
  16697. #endif
  16698. #ifndef _WIN32
  16699. TEST(ServerRequestParsingTest, RequestWithoutContentLengthOrTransferEncoding) {
  16700. Server svr;
  16701. svr.Post("/post", [&](const Request &req, Response &res) {
  16702. res.set_content(req.body, "text/plain");
  16703. });
  16704. svr.Put("/put", [&](const Request &req, Response &res) {
  16705. res.set_content(req.body, "text/plain");
  16706. });
  16707. svr.Patch("/patch", [&](const Request &req, Response &res) {
  16708. res.set_content(req.body, "text/plain");
  16709. });
  16710. svr.Delete("/delete", [&](const Request &req, Response &res) {
  16711. res.set_content(req.body, "text/plain");
  16712. });
  16713. thread t = thread([&]() { svr.listen(HOST, PORT); });
  16714. auto se = detail::scope_exit([&] {
  16715. svr.stop();
  16716. t.join();
  16717. ASSERT_FALSE(svr.is_running());
  16718. });
  16719. svr.wait_until_ready();
  16720. std::string resp;
  16721. // POST without Content-Length
  16722. ASSERT_TRUE(send_request(5,
  16723. "POST /post HTTP/1.1\r\n"
  16724. "Host: localhost\r\n"
  16725. "Connection: close\r\n"
  16726. "\r\n",
  16727. &resp));
  16728. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16729. // PUT without Content-Length
  16730. resp.clear();
  16731. ASSERT_TRUE(send_request(5,
  16732. "PUT /put HTTP/1.1\r\n"
  16733. "Host: localhost\r\n"
  16734. "Connection: close\r\n"
  16735. "\r\n",
  16736. &resp));
  16737. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16738. // PATCH without Content-Length
  16739. resp.clear();
  16740. ASSERT_TRUE(send_request(5,
  16741. "PATCH /patch HTTP/1.1\r\n"
  16742. "Host: localhost\r\n"
  16743. "Connection: close\r\n"
  16744. "\r\n",
  16745. &resp));
  16746. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16747. // DELETE without Content-Length
  16748. resp.clear();
  16749. ASSERT_TRUE(send_request(5,
  16750. "DELETE /delete HTTP/1.1\r\n"
  16751. "Host: localhost\r\n"
  16752. "Connection: close\r\n"
  16753. "\r\n",
  16754. &resp));
  16755. EXPECT_TRUE(resp.find("HTTP/1.1 200 OK") == 0);
  16756. }
  16757. #endif
  16758. //==============================================================================
  16759. // open_stream() Tests
  16760. //==============================================================================
  16761. inline std::string read_all(ClientImpl::StreamHandle &handle) {
  16762. std::string result;
  16763. char buf[8192];
  16764. ssize_t n;
  16765. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  16766. result.append(buf, static_cast<size_t>(n));
  16767. }
  16768. return result;
  16769. }
  16770. // Mock stream for unit tests
  16771. class MockStream : public Stream {
  16772. public:
  16773. std::string data;
  16774. size_t pos = 0;
  16775. ssize_t error_after = -1; // -1 = no error
  16776. explicit MockStream(const std::string &d, ssize_t err = -1)
  16777. : data(d), error_after(err) {}
  16778. bool is_readable() const override { return true; }
  16779. bool wait_readable() const override { return true; }
  16780. bool wait_writable() const override { return true; }
  16781. ssize_t read(char *ptr, size_t size) override {
  16782. if (error_after >= 0 && pos >= static_cast<size_t>(error_after)) return -1;
  16783. if (pos >= data.size()) return 0;
  16784. size_t limit =
  16785. error_after >= 0 ? static_cast<size_t>(error_after) : data.size();
  16786. size_t to_read = std::min(size, std::min(data.size() - pos, limit - pos));
  16787. std::memcpy(ptr, data.data() + pos, to_read);
  16788. pos += to_read;
  16789. return static_cast<ssize_t>(to_read);
  16790. }
  16791. ssize_t write(const char *, size_t) override { return -1; }
  16792. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  16793. ip = "127.0.0.1";
  16794. port = 0;
  16795. }
  16796. void get_local_ip_and_port(std::string &ip, int &port) const override {
  16797. ip = "127.0.0.1";
  16798. port = 0;
  16799. }
  16800. socket_t socket() const override { return INVALID_SOCKET; }
  16801. time_t duration() const override { return 0; }
  16802. };
  16803. TEST(StreamHandleTest, Basic) {
  16804. ClientImpl::StreamHandle handle;
  16805. EXPECT_FALSE(handle.is_valid());
  16806. handle.response = detail::make_unique<Response>();
  16807. handle.error = Error::Connection;
  16808. EXPECT_FALSE(handle.is_valid());
  16809. handle.error = Error::Success;
  16810. EXPECT_TRUE(handle.is_valid());
  16811. }
  16812. TEST(BodyReaderTest, Basic) {
  16813. MockStream stream("Hello, World!");
  16814. detail::BodyReader reader;
  16815. reader.stream = &stream;
  16816. reader.content_length = 13;
  16817. char buf[32];
  16818. EXPECT_EQ(13, reader.read(buf, sizeof(buf)));
  16819. EXPECT_EQ(0, reader.read(buf, sizeof(buf)));
  16820. EXPECT_TRUE(reader.eof);
  16821. }
  16822. TEST(BodyReaderTest, NoStream) {
  16823. detail::BodyReader reader;
  16824. char buf[32];
  16825. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16826. EXPECT_EQ(Error::Connection, reader.last_error);
  16827. }
  16828. TEST(BodyReaderTest, Error) {
  16829. MockStream stream("Hello, World!", 5);
  16830. detail::BodyReader reader;
  16831. reader.stream = &stream;
  16832. reader.content_length = 13;
  16833. char buf[32];
  16834. EXPECT_EQ(5, reader.read(buf, sizeof(buf)));
  16835. EXPECT_EQ(-1, reader.read(buf, sizeof(buf)));
  16836. EXPECT_EQ(Error::Read, reader.last_error);
  16837. }
  16838. // Memory buffer mode removed: StreamHandle reads only from socket streams.
  16839. // Mock-based StreamHandle tests relying on private internals are removed.
  16840. class OpenStreamTest : public ::testing::Test {
  16841. protected:
  16842. void SetUp() override {
  16843. svr_.Get("/hello", [](const Request &, Response &res) {
  16844. res.set_content("Hello World!", "text/plain");
  16845. });
  16846. svr_.Get("/large", [](const Request &, Response &res) {
  16847. res.set_content(std::string(10000, 'X'), "text/plain");
  16848. });
  16849. svr_.Get("/unknown-encoding", [](const Request &, Response &res) {
  16850. res.set_content("Hello World!", "image/jpeg");
  16851. res.set_header("Content-Encoding", "UTF-8");
  16852. });
  16853. svr_.Get("/chunked", [](const Request &, Response &res) {
  16854. res.set_chunked_content_provider("text/plain",
  16855. [](size_t offset, DataSink &sink) {
  16856. if (offset < 15) {
  16857. sink.write("chunk", 5);
  16858. return true;
  16859. }
  16860. sink.done();
  16861. return true;
  16862. });
  16863. });
  16864. svr_.Get("/compressible", [](const Request &, Response &res) {
  16865. res.set_chunked_content_provider("text/plain", [](size_t offset,
  16866. DataSink &sink) {
  16867. if (offset < 100 * 1024) {
  16868. std::string chunk(std::min(size_t(8192), 100 * 1024 - offset), 'A');
  16869. sink.write(chunk.data(), chunk.size());
  16870. return true;
  16871. }
  16872. sink.done();
  16873. return true;
  16874. });
  16875. });
  16876. svr_.Get("/streamed-chunked-with-prohibited-trailer",
  16877. [](const Request & /*req*/, Response &res) {
  16878. auto i = new int(0);
  16879. res.set_header("Trailer", "Content-Length, X-Allowed");
  16880. res.set_chunked_content_provider(
  16881. "text/plain",
  16882. [i](size_t /*offset*/, DataSink &sink) {
  16883. switch (*i) {
  16884. case 0: sink.os << "123"; break;
  16885. case 1: sink.os << "456"; break;
  16886. case 2: sink.os << "789"; break;
  16887. case 3: {
  16888. sink.done_with_trailer(
  16889. {{"Content-Length", "5"}, {"X-Allowed", "yes"}});
  16890. } break;
  16891. }
  16892. (*i)++;
  16893. return true;
  16894. },
  16895. [i](bool success) {
  16896. EXPECT_TRUE(success);
  16897. delete i;
  16898. });
  16899. });
  16900. // Echo headers endpoint for header-related tests
  16901. svr_.Get("/echo-headers", [](const Request &req, Response &res) {
  16902. std::string body;
  16903. for (const auto &h : req.headers) {
  16904. body.append(h.first);
  16905. body.push_back(':');
  16906. body.append(h.second);
  16907. body.push_back('\n');
  16908. }
  16909. res.set_content(body, "text/plain");
  16910. });
  16911. svr_.Post("/echo-headers", [](const Request &req, Response &res) {
  16912. std::string body;
  16913. for (const auto &h : req.headers) {
  16914. body.append(h.first);
  16915. body.push_back(':');
  16916. body.append(h.second);
  16917. body.push_back('\n');
  16918. }
  16919. res.set_content(body, "text/plain");
  16920. });
  16921. port_ = svr_.bind_to_any_port("127.0.0.1");
  16922. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  16923. svr_.wait_until_ready();
  16924. }
  16925. void TearDown() override {
  16926. svr_.stop();
  16927. if (thread_.joinable()) thread_.join();
  16928. }
  16929. Server svr_;
  16930. std::thread thread_;
  16931. int port_ = 0;
  16932. };
  16933. TEST_F(OpenStreamTest, Basic) {
  16934. Client cli("127.0.0.1", port_);
  16935. auto handle = cli.open_stream("GET", "/hello");
  16936. EXPECT_TRUE(handle.is_valid());
  16937. EXPECT_EQ("Hello World!", read_all(handle));
  16938. }
  16939. TEST_F(OpenStreamTest, UnknownContentEncodingIsPassedThrough) {
  16940. Client cli("127.0.0.1", port_);
  16941. auto handle = cli.open_stream("GET", "/unknown-encoding");
  16942. ASSERT_TRUE(handle.is_valid());
  16943. EXPECT_EQ("Hello World!", read_all(handle));
  16944. }
  16945. TEST_F(OpenStreamTest, SmallBuffer) {
  16946. Client cli("127.0.0.1", port_);
  16947. auto handle = cli.open_stream("GET", "/hello");
  16948. std::string result;
  16949. char buf[4];
  16950. ssize_t n;
  16951. while ((n = handle.read(buf, sizeof(buf))) > 0)
  16952. result.append(buf, static_cast<size_t>(n));
  16953. EXPECT_EQ("Hello World!", result);
  16954. }
  16955. TEST_F(OpenStreamTest, DefaultHeaders) {
  16956. Client cli("127.0.0.1", port_);
  16957. // open_stream GET should include Host, User-Agent and Accept-Encoding
  16958. {
  16959. auto handle = cli.open_stream("GET", "/echo-headers");
  16960. ASSERT_TRUE(handle.is_valid());
  16961. auto body = read_all(handle);
  16962. EXPECT_NE(body.find("Host:127.0.0.1:" + std::to_string(port_)),
  16963. std::string::npos);
  16964. EXPECT_NE(body.find("User-Agent:cpp-httplib/" CPPHTTPLIB_VERSION),
  16965. std::string::npos);
  16966. EXPECT_NE(body.find("Accept-Encoding:"), std::string::npos);
  16967. }
  16968. // open_stream POST with body and no explicit content_type should NOT add
  16969. // text/plain Content-Type (behavior differs from non-streaming path), but
  16970. // should include Content-Length
  16971. {
  16972. auto handle = cli.open_stream("POST", "/echo-headers", {}, {}, "hello", "");
  16973. ASSERT_TRUE(handle.is_valid());
  16974. auto body = read_all(handle);
  16975. EXPECT_EQ(body.find("Content-Type: text/plain"), std::string::npos);
  16976. EXPECT_NE(body.find("Content-Length:5"), std::string::npos);
  16977. }
  16978. // open_stream POST with explicit Content-Type should preserve it
  16979. {
  16980. auto handle = cli.open_stream("POST", "/echo-headers", {},
  16981. {{"Content-Type", "application/custom"}},
  16982. "{}", "application/custom");
  16983. ASSERT_TRUE(handle.is_valid());
  16984. auto body = read_all(handle);
  16985. EXPECT_NE(body.find("Content-Type:application/custom"), std::string::npos);
  16986. }
  16987. // User-specified User-Agent must not be overwritten for stream API
  16988. {
  16989. auto handle = cli.open_stream("GET", "/echo-headers", {},
  16990. {{"User-Agent", "MyAgent/1.2"}});
  16991. ASSERT_TRUE(handle.is_valid());
  16992. auto body = read_all(handle);
  16993. EXPECT_NE(body.find("User-Agent:MyAgent/1.2"), std::string::npos);
  16994. }
  16995. }
  16996. TEST_F(OpenStreamTest, Large) {
  16997. Client cli("127.0.0.1", port_);
  16998. auto handle = cli.open_stream("GET", "/large");
  16999. EXPECT_EQ(10000u, read_all(handle).size());
  17000. }
  17001. TEST_F(OpenStreamTest, ConnectionError) {
  17002. Client cli("127.0.0.1", 9999);
  17003. auto handle = cli.open_stream("GET", "/hello");
  17004. EXPECT_FALSE(handle.is_valid());
  17005. }
  17006. TEST_F(OpenStreamTest, Chunked) {
  17007. Client cli("127.0.0.1", port_);
  17008. auto handle = cli.open_stream("GET", "/chunked");
  17009. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17010. "Transfer-Encoding") == "chunked");
  17011. EXPECT_EQ("chunkchunkchunk", read_all(handle));
  17012. }
  17013. TEST_F(OpenStreamTest, ProhibitedTrailersAreIgnored_Stream) {
  17014. Client cli("127.0.0.1", port_);
  17015. auto handle =
  17016. cli.open_stream("GET", "/streamed-chunked-with-prohibited-trailer");
  17017. ASSERT_TRUE(handle.is_valid());
  17018. // Consume body to allow trailers to be received/parsed
  17019. auto body = read_all(handle);
  17020. // Explicitly parse trailers (ensure trailers are available for assertion)
  17021. handle.parse_trailers_if_needed();
  17022. EXPECT_EQ(std::string("123456789"), body);
  17023. // The response should include a Trailer header declaring both names
  17024. ASSERT_TRUE(handle.response);
  17025. EXPECT_TRUE(handle.response->has_header("Trailer"));
  17026. EXPECT_EQ(std::string("Content-Length, X-Allowed"),
  17027. handle.response->get_header_value("Trailer"));
  17028. // Prohibited trailer must not be present
  17029. EXPECT_FALSE(handle.response->has_trailer("Content-Length"));
  17030. // Allowed trailer should be present
  17031. EXPECT_TRUE(handle.response->has_trailer("X-Allowed"));
  17032. EXPECT_EQ(std::string("yes"),
  17033. handle.response->get_trailer_value("X-Allowed"));
  17034. // Verify trailers are NOT present as regular headers
  17035. EXPECT_EQ(std::string(""),
  17036. handle.response->get_header_value("Content-Length"));
  17037. EXPECT_EQ(std::string(""), handle.response->get_header_value("X-Allowed"));
  17038. }
  17039. static std::thread serve_single_response(std::promise<int> &port_promise,
  17040. const std::string &response) {
  17041. return std::thread([&port_promise, response] {
  17042. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  17043. default_socket_options(srv);
  17044. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  17045. detail::set_socket_opt_time(srv, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  17046. sockaddr_in addr{};
  17047. addr.sin_family = AF_INET;
  17048. addr.sin_port = htons(0); // Let OS assign a free port
  17049. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  17050. int opt = 1;
  17051. ::setsockopt(srv, SOL_SOCKET, SO_REUSEADDR,
  17052. #ifdef _WIN32
  17053. reinterpret_cast<const char *>(&opt),
  17054. #else
  17055. &opt,
  17056. #endif
  17057. sizeof(opt));
  17058. if (::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) != 0 ||
  17059. ::listen(srv, 1) != 0) {
  17060. port_promise.set_value(-1);
  17061. detail::close_socket(srv);
  17062. return;
  17063. }
  17064. socklen_t addr_len = sizeof(addr);
  17065. ::getsockname(srv, reinterpret_cast<sockaddr *>(&addr), &addr_len);
  17066. port_promise.set_value(static_cast<int>(ntohs(addr.sin_port)));
  17067. sockaddr_in cli_addr{};
  17068. socklen_t cli_len = sizeof(cli_addr);
  17069. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  17070. if (cli != INVALID_SOCKET) {
  17071. // Read the complete HTTP request (until the blank line that terminates
  17072. // headers) before sending the response. If the server closes the socket
  17073. // while the client's request data is still unread in the kernel receive
  17074. // buffer, the TCP stack sends RST instead of FIN. That RST resets the
  17075. // connection on both sides: it discards the client's receive buffer
  17076. // (which already holds our response) and causes any in-progress write on
  17077. // the client to fail with ECONNRESET. Reading all request data first
  17078. // ensures close() emits a graceful FIN.
  17079. {
  17080. char rbuf[256];
  17081. std::string req;
  17082. while (req.find("\r\n\r\n") == std::string::npos) {
  17083. auto n = ::recv(cli, rbuf, sizeof(rbuf), 0);
  17084. if (n <= 0) { break; }
  17085. req.append(rbuf, static_cast<size_t>(n));
  17086. }
  17087. }
  17088. ::send(cli,
  17089. #ifdef _WIN32
  17090. static_cast<const char *>(response.c_str()),
  17091. static_cast<int>(response.size()),
  17092. #else
  17093. response.c_str(), response.size(),
  17094. #endif
  17095. 0);
  17096. detail::close_socket(cli);
  17097. }
  17098. detail::close_socket(srv);
  17099. });
  17100. }
  17101. TEST(OpenStreamMalformedContentLength, InvalidArgument) {
  17102. #ifndef _WIN32
  17103. signal(SIGPIPE, SIG_IGN);
  17104. #endif
  17105. std::promise<int> port_promise;
  17106. auto port_future = port_promise.get_future();
  17107. auto server_thread =
  17108. serve_single_response(port_promise, "HTTP/1.1 200 OK\r\n"
  17109. "Content-Type: text/plain\r\n"
  17110. "Content-Length: not-a-number\r\n"
  17111. "Connection: close\r\n"
  17112. "\r\n"
  17113. "hello");
  17114. auto port = port_future.get();
  17115. ASSERT_GT(port, 0);
  17116. Client cli("127.0.0.1", port);
  17117. auto handle = cli.open_stream("GET", "/");
  17118. EXPECT_FALSE(handle.is_valid());
  17119. server_thread.join();
  17120. }
  17121. TEST(OpenStreamMalformedContentLength, OutOfRange) {
  17122. #ifndef _WIN32
  17123. signal(SIGPIPE, SIG_IGN);
  17124. #endif
  17125. std::promise<int> port_promise;
  17126. auto port_future = port_promise.get_future();
  17127. auto server_thread = serve_single_response(
  17128. port_promise, "HTTP/1.1 200 OK\r\n"
  17129. "Content-Type: text/plain\r\n"
  17130. "Content-Length: 99999999999999999999999999\r\n"
  17131. "Connection: close\r\n"
  17132. "\r\n"
  17133. "hello");
  17134. auto port = port_future.get();
  17135. ASSERT_GT(port, 0);
  17136. // Historically std::stoull would throw std::out_of_range here and crash
  17137. // the process, then parsing silently clamped to a bogus framing length and
  17138. // the stream opened anyway. Now the out-of-range value is flagged invalid,
  17139. // so the stream fails to open, matching the not-a-number case above. The
  17140. // process still must NOT terminate.
  17141. Client cli("127.0.0.1", port);
  17142. auto handle = cli.open_stream("GET", "/");
  17143. EXPECT_FALSE(handle.is_valid());
  17144. server_thread.join();
  17145. }
  17146. // Serves `response` to the single request `fn` makes with a fresh client.
  17147. template <typename Fn>
  17148. static void with_single_response(const std::string &response, Fn fn) {
  17149. #ifndef _WIN32
  17150. signal(SIGPIPE, SIG_IGN);
  17151. #endif
  17152. std::promise<int> port_promise;
  17153. auto port_future = port_promise.get_future();
  17154. auto server_thread = serve_single_response(port_promise, response);
  17155. auto se = detail::scope_exit([&] { server_thread.join(); });
  17156. auto port = port_future.get();
  17157. ASSERT_GT(port, 0);
  17158. Client cli("127.0.0.1", port);
  17159. fn(cli);
  17160. }
  17161. // RFC 9112 §6.3: a response that pairs a non-zero Content-Length with
  17162. // Transfer-Encoding is framed ambiguously. Both read paths delimit its body by
  17163. // the chunked coding and drop Content-Length, so a front-end that trusts
  17164. // Content-Length would disagree about where the body ends (response
  17165. // smuggling). The client must reject such a response.
  17166. TEST(ClientResponseSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  17167. for (const char *te : {"chunked", "gzip, chunked"}) {
  17168. auto response = std::string("HTTP/1.1 200 OK\r\n") +
  17169. "Content-Length: 5\r\n" + "Transfer-Encoding: " + te +
  17170. "\r\n" + "Connection: close\r\n" + "\r\n" +
  17171. "5\r\nhello\r\n0\r\n\r\n";
  17172. with_single_response(response, [&](Client &cli) {
  17173. auto res = cli.Get("/");
  17174. EXPECT_FALSE(static_cast<bool>(res)) << te;
  17175. EXPECT_EQ(Error::Read, res.error()) << te;
  17176. });
  17177. with_single_response(response, [&](Client &cli) {
  17178. auto handle = cli.open_stream("GET", "/");
  17179. EXPECT_FALSE(handle.is_valid()) << te;
  17180. EXPECT_EQ(Error::Read, handle.error) << te;
  17181. });
  17182. }
  17183. }
  17184. // Unambiguous framing stays readable on both paths: chunked alone, and a final
  17185. // coding other than chunked, whose body RFC 9112 §6.3 delimits by the server
  17186. // closing the connection (unlike a request, which must be rejected).
  17187. TEST(ClientResponseSmugglingTest, UnambiguousFramingAccepted) {
  17188. for (const char *response : {"HTTP/1.1 200 OK\r\n"
  17189. "Transfer-Encoding: chunked\r\n"
  17190. "Connection: close\r\n"
  17191. "\r\n"
  17192. "5\r\nhello\r\n0\r\n\r\n",
  17193. "HTTP/1.1 200 OK\r\n"
  17194. "Transfer-Encoding: gzip\r\n"
  17195. "Connection: close\r\n"
  17196. "\r\n"
  17197. "hello"}) {
  17198. with_single_response(response, [&](Client &cli) {
  17199. auto res = cli.Get("/");
  17200. ASSERT_TRUE(static_cast<bool>(res)) << response;
  17201. EXPECT_EQ("hello", res->body);
  17202. });
  17203. with_single_response(response, [&](Client &cli) {
  17204. auto handle = cli.open_stream("GET", "/");
  17205. ASSERT_TRUE(handle.is_valid()) << response;
  17206. EXPECT_EQ("hello", read_all(handle));
  17207. });
  17208. }
  17209. }
  17210. // A response to HEAD, and a 204 or 304 response, carries no body, so its
  17211. // framing headers describe nothing to read and must not be rejected.
  17212. TEST(ClientResponseSmugglingTest, BodylessResponseNotRejected) {
  17213. const std::string framing = "Content-Length: 5\r\n"
  17214. "Transfer-Encoding: chunked\r\n"
  17215. "Connection: close\r\n"
  17216. "\r\n";
  17217. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17218. EXPECT_TRUE(static_cast<bool>(cli.Head("/")));
  17219. });
  17220. with_single_response("HTTP/1.1 200 OK\r\n" + framing, [](Client &cli) {
  17221. EXPECT_TRUE(cli.open_stream("HEAD", "/").is_valid());
  17222. });
  17223. for (const char *status : {"204 No Content", "304 Not Modified"}) {
  17224. auto response = std::string("HTTP/1.1 ") + status + "\r\n" + framing;
  17225. with_single_response(response, [&](Client &cli) {
  17226. EXPECT_TRUE(static_cast<bool>(cli.Get("/"))) << status;
  17227. });
  17228. with_single_response(response, [&](Client &cli) {
  17229. EXPECT_TRUE(cli.open_stream("GET", "/").is_valid()) << status;
  17230. });
  17231. }
  17232. }
  17233. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17234. TEST_F(OpenStreamTest, Gzip) {
  17235. Client cli("127.0.0.1", port_);
  17236. auto handle = cli.open_stream("GET", "/compressible", {},
  17237. {{"Accept-Encoding", "gzip"}});
  17238. EXPECT_EQ("gzip", handle.response->get_header_value("Content-Encoding"));
  17239. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17240. }
  17241. #endif
  17242. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17243. TEST_F(OpenStreamTest, Brotli) {
  17244. Client cli("127.0.0.1", port_);
  17245. auto handle =
  17246. cli.open_stream("GET", "/compressible", {}, {{"Accept-Encoding", "br"}});
  17247. EXPECT_EQ("br", handle.response->get_header_value("Content-Encoding"));
  17248. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17249. }
  17250. #endif
  17251. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17252. TEST_F(OpenStreamTest, Zstd) {
  17253. Client cli("127.0.0.1", port_);
  17254. auto handle = cli.open_stream("GET", "/compressible", {},
  17255. {{"Accept-Encoding", "zstd"}});
  17256. EXPECT_EQ("zstd", handle.response->get_header_value("Content-Encoding"));
  17257. EXPECT_EQ(100u * 1024u, read_all(handle).size());
  17258. }
  17259. #endif
  17260. #ifdef CPPHTTPLIB_SSL_ENABLED
  17261. class SSLOpenStreamTest : public ::testing::Test {
  17262. protected:
  17263. SSLOpenStreamTest() : svr_("cert.pem", "key.pem") {}
  17264. void SetUp() override {
  17265. svr_.Get("/hello", [](const Request &, Response &res) {
  17266. res.set_content("Hello SSL World!", "text/plain");
  17267. });
  17268. svr_.Get("/chunked", [](const Request &, Response &res) {
  17269. res.set_chunked_content_provider("text/plain",
  17270. [](size_t offset, DataSink &sink) {
  17271. if (offset < 15) {
  17272. sink.write("chunk", 5);
  17273. return true;
  17274. }
  17275. sink.done();
  17276. return true;
  17277. });
  17278. });
  17279. svr_.Post("/echo", [](const Request &req, Response &res) {
  17280. res.set_content(req.body, req.get_header_value("Content-Type"));
  17281. });
  17282. svr_.Post("/chunked-response", [](const Request &req, Response &res) {
  17283. std::string body = req.body;
  17284. res.set_chunked_content_provider(
  17285. "text/plain", [body](size_t offset, DataSink &sink) {
  17286. if (offset < body.size()) {
  17287. sink.write(body.data() + offset, body.size() - offset);
  17288. }
  17289. sink.done();
  17290. return true;
  17291. });
  17292. });
  17293. port_ = svr_.bind_to_any_port("127.0.0.1");
  17294. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17295. svr_.wait_until_ready();
  17296. }
  17297. void TearDown() override {
  17298. svr_.stop();
  17299. if (thread_.joinable()) thread_.join();
  17300. }
  17301. SSLServer svr_;
  17302. std::thread thread_;
  17303. int port_ = 0;
  17304. };
  17305. TEST_F(SSLOpenStreamTest, Basic) {
  17306. SSLClient cli("127.0.0.1", port_);
  17307. cli.enable_server_certificate_verification(false);
  17308. auto handle = cli.open_stream("GET", "/hello");
  17309. ASSERT_TRUE(handle.is_valid());
  17310. EXPECT_EQ("Hello SSL World!", read_all(handle));
  17311. }
  17312. TEST_F(SSLOpenStreamTest, Chunked) {
  17313. SSLClient cli("127.0.0.1", port_);
  17314. cli.enable_server_certificate_verification(false);
  17315. auto handle = cli.open_stream("GET", "/chunked");
  17316. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17317. EXPECT_TRUE(handle.response && handle.response->get_header_value(
  17318. "Transfer-Encoding") == "chunked");
  17319. auto body = read_all(handle);
  17320. EXPECT_EQ("chunkchunkchunk", body);
  17321. }
  17322. TEST_F(SSLOpenStreamTest, Post) {
  17323. SSLClient cli("127.0.0.1", port_);
  17324. cli.enable_server_certificate_verification(false);
  17325. auto handle =
  17326. cli.open_stream("POST", "/echo", {}, {}, "Hello SSL POST", "text/plain");
  17327. ASSERT_TRUE(handle.is_valid()) << "Error: " << static_cast<int>(handle.error);
  17328. EXPECT_EQ(200, handle.response->status);
  17329. auto body = read_all(handle);
  17330. EXPECT_EQ("Hello SSL POST", body);
  17331. }
  17332. TEST_F(SSLOpenStreamTest, PostChunked) {
  17333. SSLClient cli("127.0.0.1", port_);
  17334. cli.enable_server_certificate_verification(false);
  17335. auto handle = cli.open_stream("POST", "/chunked-response", {}, {},
  17336. "Chunked SSL Data", "text/plain");
  17337. ASSERT_TRUE(handle.is_valid());
  17338. EXPECT_EQ(200, handle.response->status);
  17339. auto body = read_all(handle);
  17340. EXPECT_EQ("Chunked SSL Data", body);
  17341. }
  17342. // RFC 7230 §3.3: a response body with neither chunked Transfer-Encoding nor
  17343. // Content-Length is terminated by the server closing the connection. When the
  17344. // SSL peer sends a close_notify after the body, the client must treat it as a
  17345. // clean EOF and return a successful response rather than an error.
  17346. TEST(SSLTest, ResponseBodyTerminatedByConnectionClose) {
  17347. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17348. ASSERT_TRUE(svr.is_valid());
  17349. svr.set_keep_alive_max_count(1);
  17350. const std::string expected_body = "Hello from connection-close response!";
  17351. svr.Get("/no-content-length", [&](const Request & /*req*/, Response &res) {
  17352. res.set_content_provider("text/plain",
  17353. [&](size_t offset, DataSink &sink) -> bool {
  17354. if (offset < expected_body.size()) {
  17355. sink.write(expected_body.data() + offset,
  17356. expected_body.size() - offset);
  17357. }
  17358. sink.done();
  17359. return true;
  17360. });
  17361. });
  17362. auto listen_thread = std::thread([&svr] { svr.listen(HOST, PORT); });
  17363. auto se = detail::scope_exit([&] {
  17364. svr.stop();
  17365. listen_thread.join();
  17366. ASSERT_FALSE(svr.is_running());
  17367. });
  17368. svr.wait_until_ready();
  17369. SSLClient cli(HOST, PORT);
  17370. cli.enable_server_certificate_verification(false);
  17371. auto res = cli.Get("/no-content-length");
  17372. ASSERT_TRUE(res) << "Request failed: " << to_string(res.error());
  17373. EXPECT_EQ(StatusCode::OK_200, res->status);
  17374. EXPECT_EQ(expected_body, res->body);
  17375. }
  17376. #endif // CPPHTTPLIB_SSL_ENABLED
  17377. //==============================================================================
  17378. // Parity Tests: ensure streaming and non-streaming APIs produce identical
  17379. // results for various scenarios.
  17380. //==============================================================================
  17381. TEST(ParityTest, GetVsOpenStream) {
  17382. Server svr;
  17383. const std::string path = "/parity";
  17384. const std::string content = "Parity test content: hello world";
  17385. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17386. res.set_content(content, "text/plain");
  17387. });
  17388. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17389. auto se = detail::scope_exit([&] {
  17390. svr.stop();
  17391. t.join();
  17392. ASSERT_FALSE(svr.is_running());
  17393. });
  17394. svr.wait_until_ready();
  17395. Client cli(HOST, PORT);
  17396. // Non-stream path
  17397. auto r1 = cli.Get(path);
  17398. ASSERT_TRUE(r1);
  17399. EXPECT_EQ(StatusCode::OK_200, r1->status);
  17400. // Stream path
  17401. auto h = cli.open_stream("GET", path);
  17402. ASSERT_TRUE(h.is_valid());
  17403. EXPECT_EQ(r1->body, read_all(h));
  17404. }
  17405. // Helper to compress data with provided compressor type T
  17406. template <typename Compressor>
  17407. static std::string compress_payload_for_parity(const std::string &in) {
  17408. std::string out;
  17409. Compressor compressor;
  17410. bool ok = compressor.compress(in.data(), in.size(), /*last=*/true,
  17411. [&](const char *data, size_t n) {
  17412. out.append(data, n);
  17413. return true;
  17414. });
  17415. EXPECT_TRUE(ok);
  17416. return out;
  17417. }
  17418. // Helper function for compression parity tests
  17419. template <typename Compressor>
  17420. static void test_compression_parity(const std::string &original,
  17421. const std::string &path,
  17422. const std::string &encoding) {
  17423. const std::string compressed =
  17424. compress_payload_for_parity<Compressor>(original);
  17425. Server svr;
  17426. svr.Get(path, [&](const Request & /*req*/, Response &res) {
  17427. res.set_content(compressed, "application/octet-stream");
  17428. res.set_header("Content-Encoding", encoding);
  17429. });
  17430. auto t = std::thread([&] { svr.listen(HOST, PORT); });
  17431. auto se = detail::scope_exit([&] {
  17432. svr.stop();
  17433. t.join();
  17434. ASSERT_FALSE(svr.is_running());
  17435. });
  17436. svr.wait_until_ready();
  17437. Client cli(HOST, PORT);
  17438. // Non-streaming
  17439. {
  17440. auto res = cli.Get(path);
  17441. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17442. EXPECT_EQ(StatusCode::OK_200, res->status);
  17443. EXPECT_EQ(original, res->body);
  17444. }
  17445. // Streaming
  17446. {
  17447. auto h = cli.open_stream("GET", path);
  17448. ASSERT_TRUE(h.is_valid());
  17449. EXPECT_EQ(original, read_all(h));
  17450. }
  17451. }
  17452. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  17453. TEST(ParityTest, Gzip) {
  17454. test_compression_parity<detail::gzip_compressor>(
  17455. "The quick brown fox jumps over the lazy dog", "/parity-gzip", "gzip");
  17456. }
  17457. #endif
  17458. #ifdef CPPHTTPLIB_BROTLI_SUPPORT
  17459. TEST(ParityTest, Brotli) {
  17460. test_compression_parity<detail::brotli_compressor>(
  17461. "Hello, brotli parity test payload", "/parity-br", "br");
  17462. }
  17463. #endif
  17464. #ifdef CPPHTTPLIB_ZSTD_SUPPORT
  17465. TEST(ParityTest, Zstd) {
  17466. test_compression_parity<detail::zstd_compressor>(
  17467. "Zstandard parity test payload", "/parity-zstd", "zstd");
  17468. }
  17469. #endif
  17470. //==============================================================================
  17471. // New Stream API Tests
  17472. //==============================================================================
  17473. inline std::string read_body(httplib::stream::Result &result) {
  17474. std::string body;
  17475. while (result.next()) {
  17476. body.append(result.data(), result.size());
  17477. }
  17478. return body;
  17479. }
  17480. TEST(ClientConnectionTest, Basic) {
  17481. httplib::ClientConnection conn;
  17482. EXPECT_FALSE(conn.is_open());
  17483. conn.sock = 1;
  17484. EXPECT_TRUE(conn.is_open());
  17485. httplib::ClientConnection conn2(std::move(conn));
  17486. EXPECT_EQ(INVALID_SOCKET, conn.sock);
  17487. conn2.sock = INVALID_SOCKET;
  17488. }
  17489. // Unified test server for all stream::* tests
  17490. class StreamApiTest : public ::testing::Test {
  17491. protected:
  17492. void SetUp() override {
  17493. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17494. res.set_content("Hello World!", "text/plain");
  17495. });
  17496. svr_.Get("/echo-params",
  17497. [](const httplib::Request &req, httplib::Response &res) {
  17498. std::string r;
  17499. for (const auto &p : req.params) {
  17500. if (!r.empty()) r += "&";
  17501. r += p.first + "=" + p.second;
  17502. }
  17503. res.set_content(r, "text/plain");
  17504. });
  17505. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17506. res.set_content(req.body, req.get_header_value("Content-Type"));
  17507. });
  17508. svr_.Post("/echo-headers",
  17509. [](const httplib::Request &req, httplib::Response &res) {
  17510. std::string r;
  17511. for (const auto &h : req.headers)
  17512. r += h.first + ": " + h.second + "\n";
  17513. res.set_content(r, "text/plain");
  17514. });
  17515. svr_.Post("/echo-params",
  17516. [](const httplib::Request &req, httplib::Response &res) {
  17517. std::string r = "params:";
  17518. for (const auto &p : req.params)
  17519. r += p.first + "=" + p.second + ";";
  17520. res.set_content(r + " body:" + req.body, "text/plain");
  17521. });
  17522. svr_.Post("/large", [](const httplib::Request &, httplib::Response &res) {
  17523. res.set_content(std::string(100 * 1024, 'X'), "application/octet-stream");
  17524. });
  17525. svr_.Put("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17526. res.set_content("PUT:" + req.body, "text/plain");
  17527. });
  17528. svr_.Patch("/echo",
  17529. [](const httplib::Request &req, httplib::Response &res) {
  17530. res.set_content("PATCH:" + req.body, "text/plain");
  17531. });
  17532. svr_.Delete(
  17533. "/resource", [](const httplib::Request &req, httplib::Response &res) {
  17534. res.set_content(req.body.empty() ? "Deleted" : "Deleted:" + req.body,
  17535. "text/plain");
  17536. });
  17537. svr_.Get("/head-test",
  17538. [](const httplib::Request &, httplib::Response &res) {
  17539. res.set_content("body for HEAD", "text/plain");
  17540. });
  17541. svr_.Options("/options",
  17542. [](const httplib::Request &, httplib::Response &res) {
  17543. res.set_header("Allow", "GET, POST, PUT, DELETE, OPTIONS");
  17544. });
  17545. thread_ = std::thread([this]() { svr_.listen(HOST, PORT); });
  17546. svr_.wait_until_ready();
  17547. }
  17548. void TearDown() override {
  17549. svr_.stop();
  17550. if (thread_.joinable()) thread_.join();
  17551. }
  17552. httplib::Server svr_;
  17553. std::thread thread_;
  17554. };
  17555. // stream::Get tests
  17556. TEST_F(StreamApiTest, GetBasic) {
  17557. httplib::Client cli(HOST, PORT);
  17558. auto result = httplib::stream::Get(cli, "/hello");
  17559. ASSERT_TRUE(result.is_valid());
  17560. EXPECT_EQ(200, result.status());
  17561. EXPECT_EQ("Hello World!", read_body(result));
  17562. }
  17563. TEST_F(StreamApiTest, GetWithParams) {
  17564. httplib::Client cli(HOST, PORT);
  17565. httplib::Params params{{"foo", "bar"}};
  17566. auto result = httplib::stream::Get(cli, "/echo-params", params);
  17567. ASSERT_TRUE(result.is_valid());
  17568. EXPECT_TRUE(read_body(result).find("foo=bar") != std::string::npos);
  17569. }
  17570. TEST_F(StreamApiTest, GetConnectionError) {
  17571. httplib::Client cli(HOST, 9999);
  17572. EXPECT_FALSE(httplib::stream::Get(cli, "/hello").is_valid());
  17573. }
  17574. TEST_F(StreamApiTest, Get404) {
  17575. httplib::Client cli(HOST, PORT);
  17576. auto result = httplib::stream::Get(cli, "/nonexistent");
  17577. EXPECT_TRUE(result.is_valid());
  17578. EXPECT_EQ(404, result.status());
  17579. }
  17580. // stream::Post tests
  17581. TEST_F(StreamApiTest, PostBasic) {
  17582. httplib::Client cli(HOST, PORT);
  17583. auto result = httplib::stream::Post(cli, "/echo", R"({"key":"value"})",
  17584. "application/json");
  17585. ASSERT_TRUE(result.is_valid());
  17586. EXPECT_EQ("application/json", result.get_header_value("Content-Type"));
  17587. EXPECT_EQ(R"({"key":"value"})", read_body(result));
  17588. }
  17589. TEST_F(StreamApiTest, PostWithHeaders) {
  17590. httplib::Client cli(HOST, PORT);
  17591. httplib::Headers headers{{"X-Custom", "value"}};
  17592. auto result = httplib::stream::Post(cli, "/echo-headers", headers, "body",
  17593. "text/plain");
  17594. EXPECT_TRUE(read_body(result).find("X-Custom: value") != std::string::npos);
  17595. }
  17596. TEST_F(StreamApiTest, PostWithParams) {
  17597. httplib::Client cli(HOST, PORT);
  17598. httplib::Params params{{"k", "v"}};
  17599. auto result =
  17600. httplib::stream::Post(cli, "/echo-params", params, "data", "text/plain");
  17601. auto body = read_body(result);
  17602. EXPECT_TRUE(body.find("k=v") != std::string::npos);
  17603. EXPECT_TRUE(body.find("body:data") != std::string::npos);
  17604. }
  17605. TEST_F(StreamApiTest, PostLarge) {
  17606. httplib::Client cli(HOST, PORT);
  17607. auto result = httplib::stream::Post(cli, "/large", "", "text/plain");
  17608. size_t total = 0;
  17609. while (result.next()) {
  17610. total += result.size();
  17611. }
  17612. EXPECT_EQ(100u * 1024u, total);
  17613. }
  17614. // stream::Put/Patch tests
  17615. TEST_F(StreamApiTest, PutAndPatch) {
  17616. httplib::Client cli(HOST, PORT);
  17617. auto put = httplib::stream::Put(cli, "/echo", "test", "text/plain");
  17618. EXPECT_EQ("PUT:test", read_body(put));
  17619. auto patch = httplib::stream::Patch(cli, "/echo", "test", "text/plain");
  17620. EXPECT_EQ("PATCH:test", read_body(patch));
  17621. }
  17622. // stream::Delete tests
  17623. TEST_F(StreamApiTest, Delete) {
  17624. httplib::Client cli(HOST, PORT);
  17625. auto del1 = httplib::stream::Delete(cli, "/resource");
  17626. EXPECT_EQ("Deleted", read_body(del1));
  17627. auto del2 = httplib::stream::Delete(cli, "/resource", "data", "text/plain");
  17628. EXPECT_EQ("Deleted:data", read_body(del2));
  17629. }
  17630. // stream::Head/Options tests
  17631. TEST_F(StreamApiTest, HeadAndOptions) {
  17632. httplib::Client cli(HOST, PORT);
  17633. auto head = httplib::stream::Head(cli, "/head-test");
  17634. EXPECT_TRUE(head.is_valid());
  17635. EXPECT_FALSE(head.get_header_value("Content-Length").empty());
  17636. auto opts = httplib::stream::Options(cli, "/options");
  17637. EXPECT_EQ("GET, POST, PUT, DELETE, OPTIONS", opts.get_header_value("Allow"));
  17638. }
  17639. // SSL stream::* tests
  17640. #ifdef CPPHTTPLIB_SSL_ENABLED
  17641. class SSLStreamApiTest : public ::testing::Test {
  17642. protected:
  17643. void SetUp() override {
  17644. svr_.Get("/hello", [](const httplib::Request &, httplib::Response &res) {
  17645. res.set_content("Hello SSL!", "text/plain");
  17646. });
  17647. svr_.Post("/echo", [](const httplib::Request &req, httplib::Response &res) {
  17648. res.set_content(req.body, "text/plain");
  17649. });
  17650. port_ = svr_.bind_to_any_port("127.0.0.1");
  17651. thread_ = std::thread([this]() { svr_.listen_after_bind(); });
  17652. svr_.wait_until_ready();
  17653. }
  17654. void TearDown() override {
  17655. svr_.stop();
  17656. if (thread_.joinable()) thread_.join();
  17657. }
  17658. httplib::SSLServer svr_{"cert.pem", "key.pem"};
  17659. std::thread thread_;
  17660. int port_ = 0;
  17661. };
  17662. TEST_F(SSLStreamApiTest, GetAndPost) {
  17663. httplib::SSLClient cli("127.0.0.1", port_);
  17664. cli.enable_server_certificate_verification(false);
  17665. auto get = httplib::stream::Get(cli, "/hello");
  17666. EXPECT_EQ("Hello SSL!", read_body(get));
  17667. auto post = httplib::stream::Post(cli, "/echo", "test", "text/plain");
  17668. EXPECT_EQ("test", read_body(post));
  17669. }
  17670. #endif
  17671. // Tests for Error::Timeout and Error::ConnectionClosed error types
  17672. // These errors are set in SocketStream/SSLSocketStream and propagated through
  17673. // BodyReader
  17674. TEST(ErrorHandlingTest, StreamReadTimeout) {
  17675. // Test that read timeout during streaming is detected
  17676. // Use a large content-length response where server delays mid-stream
  17677. Server svr;
  17678. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17679. // Send a large response with delay in the middle
  17680. res.set_content_provider(
  17681. 1000, // content_length
  17682. "text/plain", [](size_t offset, size_t /*length*/, DataSink &sink) {
  17683. if (offset < 100) {
  17684. // Send first 100 bytes immediately
  17685. std::string data(100, 'A');
  17686. sink.write(data.c_str(), data.size());
  17687. return true;
  17688. }
  17689. // Then delay longer than client timeout
  17690. std::this_thread::sleep_for(std::chrono::seconds(3));
  17691. std::string data(900, 'B');
  17692. sink.write(data.c_str(), data.size());
  17693. return true;
  17694. });
  17695. });
  17696. auto port = 8091;
  17697. std::thread t([&]() { svr.listen("localhost", port); });
  17698. svr.wait_until_ready();
  17699. Client cli("localhost", port);
  17700. cli.set_read_timeout(1, 0); // 1 second timeout
  17701. auto handle = cli.open_stream("GET", "/slow-stream");
  17702. ASSERT_TRUE(handle.is_valid());
  17703. char buf[256];
  17704. ssize_t total = 0;
  17705. ssize_t n;
  17706. bool got_error = false;
  17707. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17708. total += n;
  17709. }
  17710. if (n < 0) {
  17711. got_error = true;
  17712. // Should be timeout or read error
  17713. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17714. handle.get_read_error() == Error::Read)
  17715. << "Actual error: " << to_string(handle.get_read_error());
  17716. }
  17717. // Either we got an error, or we got less data than expected
  17718. EXPECT_TRUE(got_error || total < 1000)
  17719. << "Expected timeout but got all " << total << " bytes";
  17720. svr.stop();
  17721. t.join();
  17722. }
  17723. TEST(ErrorHandlingTest, StreamConnectionClosed) {
  17724. // Test connection closed detection via BodyReader
  17725. Server svr;
  17726. std::atomic<bool> close_now{false};
  17727. svr.Get("/will-close", [&](const Request &, Response &res) {
  17728. res.set_content_provider(
  17729. 10000, // Large content_length that we won't fully send
  17730. "text/plain", [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17731. if (offset < 100) {
  17732. std::string data(100, 'X');
  17733. sink.write(data.c_str(), data.size());
  17734. return true;
  17735. }
  17736. // Wait for signal then abort
  17737. while (!close_now) {
  17738. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17739. }
  17740. return false; // Abort - server will close connection
  17741. });
  17742. });
  17743. auto port = 8092;
  17744. std::thread t([&]() { svr.listen("localhost", port); });
  17745. svr.wait_until_ready();
  17746. Client cli("localhost", port);
  17747. auto handle = cli.open_stream("GET", "/will-close");
  17748. ASSERT_TRUE(handle.is_valid());
  17749. char buf[256];
  17750. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17751. EXPECT_GT(n, 0) << "First read should succeed";
  17752. // Signal server to close
  17753. close_now = true;
  17754. // Keep reading until error or EOF
  17755. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17756. // Keep reading
  17757. }
  17758. // Should get an error since content_length wasn't satisfied
  17759. if (n < 0) {
  17760. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17761. handle.get_read_error() == Error::Read)
  17762. << "Actual error: " << to_string(handle.get_read_error());
  17763. }
  17764. svr.stop();
  17765. t.join();
  17766. }
  17767. #ifdef CPPHTTPLIB_SSL_ENABLED
  17768. TEST(ErrorHandlingTest, SSLStreamReadTimeout) {
  17769. // Test that read timeout during SSL streaming is detected
  17770. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17771. svr.Get("/slow-stream", [](const Request &, Response &res) {
  17772. res.set_content_provider(
  17773. 1000, "text/plain",
  17774. [](size_t offset, size_t /*length*/, DataSink &sink) {
  17775. if (offset < 100) {
  17776. std::string data(100, 'A');
  17777. sink.write(data.c_str(), data.size());
  17778. return true;
  17779. }
  17780. std::this_thread::sleep_for(std::chrono::seconds(3));
  17781. std::string data(900, 'B');
  17782. sink.write(data.c_str(), data.size());
  17783. return true;
  17784. });
  17785. });
  17786. auto port = 8093;
  17787. std::thread t([&]() { svr.listen("localhost", port); });
  17788. svr.wait_until_ready();
  17789. SSLClient cli("localhost", port);
  17790. cli.enable_server_certificate_verification(false);
  17791. cli.set_read_timeout(1, 0); // 1 second timeout
  17792. auto handle = cli.open_stream("GET", "/slow-stream");
  17793. ASSERT_TRUE(handle.is_valid());
  17794. char buf[256];
  17795. ssize_t total = 0;
  17796. ssize_t n;
  17797. bool got_error = false;
  17798. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17799. total += n;
  17800. }
  17801. if (n < 0) {
  17802. got_error = true;
  17803. EXPECT_TRUE(handle.get_read_error() == Error::Timeout ||
  17804. handle.get_read_error() == Error::Read)
  17805. << "Actual error: " << to_string(handle.get_read_error());
  17806. }
  17807. EXPECT_TRUE(got_error || total < 1000)
  17808. << "Expected timeout but got all " << total << " bytes";
  17809. svr.stop();
  17810. t.join();
  17811. }
  17812. TEST(ErrorHandlingTest, SSLStreamConnectionClosed) {
  17813. // Test SSL connection closed detection
  17814. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  17815. std::atomic<bool> close_now{false};
  17816. svr.Get("/will-close", [&](const Request &, Response &res) {
  17817. res.set_content_provider(
  17818. 10000, "text/plain",
  17819. [&](size_t offset, size_t /*length*/, DataSink &sink) {
  17820. if (offset < 100) {
  17821. std::string data(100, 'X');
  17822. sink.write(data.c_str(), data.size());
  17823. return true;
  17824. }
  17825. while (!close_now) {
  17826. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  17827. }
  17828. return false;
  17829. });
  17830. });
  17831. auto port = 8094;
  17832. std::thread t([&]() { svr.listen("localhost", port); });
  17833. svr.wait_until_ready();
  17834. SSLClient cli("localhost", port);
  17835. cli.enable_server_certificate_verification(false);
  17836. auto handle = cli.open_stream("GET", "/will-close");
  17837. ASSERT_TRUE(handle.is_valid());
  17838. char buf[256];
  17839. ssize_t n = handle.read(buf, sizeof(buf)); // First read
  17840. EXPECT_GT(n, 0);
  17841. // Signal server to close
  17842. close_now = true;
  17843. while ((n = handle.read(buf, sizeof(buf))) > 0) {
  17844. // Keep reading
  17845. }
  17846. if (n < 0) {
  17847. EXPECT_TRUE(handle.get_read_error() == Error::ConnectionClosed ||
  17848. handle.get_read_error() == Error::Read)
  17849. << "Actual error: " << to_string(handle.get_read_error());
  17850. }
  17851. svr.stop();
  17852. t.join();
  17853. }
  17854. #endif
  17855. TEST(ETagTest, StaticFileETagAndIfNoneMatch) {
  17856. using namespace httplib;
  17857. // Create a test file
  17858. const char *fname = "etag_testfile.txt";
  17859. const char *content = "etag-content";
  17860. {
  17861. std::ofstream ofs(fname);
  17862. ofs << content;
  17863. ASSERT_TRUE(ofs.good());
  17864. }
  17865. Server svr;
  17866. svr.set_mount_point("/static", ".");
  17867. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17868. svr.wait_until_ready();
  17869. Client cli(HOST, PORT);
  17870. // First request: should get 200 with ETag header
  17871. auto res1 = cli.Get("/static/etag_testfile.txt");
  17872. ASSERT_TRUE(res1);
  17873. ASSERT_EQ(200, res1->status);
  17874. ASSERT_TRUE(res1->has_header("ETag"));
  17875. std::string etag = res1->get_header_value("ETag");
  17876. EXPECT_FALSE(etag.empty());
  17877. // Verify ETag format: W/"hex-hex"
  17878. ASSERT_GE(etag.length(), 5u); // Minimum: W/""
  17879. EXPECT_EQ('W', etag[0]);
  17880. EXPECT_EQ('/', etag[1]);
  17881. EXPECT_EQ('"', etag[2]);
  17882. EXPECT_EQ('"', etag.back());
  17883. // Exact match: expect 304 Not Modified
  17884. Headers h2 = {{"If-None-Match", etag}};
  17885. auto res2 = cli.Get("/static/etag_testfile.txt", h2);
  17886. ASSERT_TRUE(res2);
  17887. EXPECT_EQ(304, res2->status);
  17888. // Wildcard match: expect 304 Not Modified
  17889. Headers h3 = {{"If-None-Match", "*"}};
  17890. auto res3 = cli.Get("/static/etag_testfile.txt", h3);
  17891. ASSERT_TRUE(res3);
  17892. EXPECT_EQ(304, res3->status);
  17893. // Non-matching ETag: expect 200
  17894. Headers h4 = {{"If-None-Match", "W/\"deadbeef\""}};
  17895. auto res4 = cli.Get("/static/etag_testfile.txt", h4);
  17896. ASSERT_TRUE(res4);
  17897. EXPECT_EQ(200, res4->status);
  17898. // Multiple ETags with one matching: expect 304
  17899. Headers h5 = {{"If-None-Match", "W/\"other\", " + etag + ", W/\"another\""}};
  17900. auto res5 = cli.Get("/static/etag_testfile.txt", h5);
  17901. ASSERT_TRUE(res5);
  17902. EXPECT_EQ(304, res5->status);
  17903. // The ETag list split over several field lines: RFC 9110 Section 5.3 makes
  17904. // that equivalent to the single comma-separated list above, so the match on
  17905. // the second line must still be found.
  17906. Headers h6;
  17907. h6.emplace("If-None-Match", "W/\"other\"");
  17908. h6.emplace("If-None-Match", etag);
  17909. auto res6 = cli.Get("/static/etag_testfile.txt", h6);
  17910. ASSERT_TRUE(res6);
  17911. EXPECT_EQ(304, res6->status);
  17912. svr.stop();
  17913. t.join();
  17914. std::remove(fname);
  17915. }
  17916. TEST(ETagTest, StaticFileETagIfNoneMatchStarNotFound) {
  17917. using namespace httplib;
  17918. Server svr;
  17919. svr.set_mount_point("/static", ".");
  17920. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  17921. svr.wait_until_ready();
  17922. Client cli(HOST, PORT);
  17923. // Send If-None-Match: * to a non-existent file
  17924. Headers h = {{"If-None-Match", "*"}};
  17925. auto res = cli.Get("/static/etag_testfile_notfound.txt", h);
  17926. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  17927. EXPECT_EQ(404, res->status);
  17928. svr.stop();
  17929. t.join();
  17930. }
  17931. TEST(ETagTest, IfNoneMatchBoundaryCheck) {
  17932. using namespace httplib;
  17933. // Create a test file
  17934. const char *fname = "etag_boundary_testfile.txt";
  17935. const char *content = "boundary-test";
  17936. {
  17937. std::ofstream ofs(fname);
  17938. ofs << content;
  17939. ASSERT_TRUE(ofs.good());
  17940. }
  17941. Server svr;
  17942. svr.set_mount_point("/static", ".");
  17943. auto t = std::thread([&]() { svr.listen("localhost", PORT); });
  17944. svr.wait_until_ready();
  17945. Client cli(HOST, PORT);
  17946. // Get the actual ETag
  17947. auto res1 = cli.Get("/static/etag_boundary_testfile.txt");
  17948. ASSERT_TRUE(res1);
  17949. ASSERT_EQ(200, res1->status);
  17950. ASSERT_TRUE(res1->has_header("ETag"));
  17951. std::string etag = res1->get_header_value("ETag");
  17952. // Test 1: Very long ETag value (longer than actual ETag)
  17953. // Should NOT match and return 200 (not trigger out-of-bounds read)
  17954. Headers h1 = {{"If-None-Match", "W/"
  17955. "\"very-long-etag-value-that-is-much-longer-"
  17956. "than-the-actual-etag-value\""}};
  17957. auto res2 = cli.Get("/static/etag_boundary_testfile.txt", h1);
  17958. ASSERT_TRUE(res2);
  17959. EXPECT_EQ(200, res2->status); // Should not match
  17960. // Test 2: Long string followed by wildcard
  17961. // Should match on "*" and return 304 (without out-of-bounds read on the long
  17962. // string)
  17963. Headers h2 = {{"If-None-Match", "W/\"another-very-long-value\", *"}};
  17964. auto res3 = cli.Get("/static/etag_boundary_testfile.txt", h2);
  17965. ASSERT_TRUE(res3);
  17966. EXPECT_EQ(304, res3->status); // Should match on "*"
  17967. // Test 3: Wildcard followed by long string
  17968. // Should match on "*" immediately and return 304
  17969. Headers h3 = {{"If-None-Match", "*, W/\"long-value-after-wildcard\""}};
  17970. auto res4 = cli.Get("/static/etag_boundary_testfile.txt", h3);
  17971. ASSERT_TRUE(res4);
  17972. EXPECT_EQ(304, res4->status); // Should match on "*"
  17973. // Test 4: Multiple long non-matching values
  17974. // Should NOT match and return 200 (test that all comparisons are safe)
  17975. Headers h4 = {{"If-None-Match", "W/\"first-long-non-matching-value\", "
  17976. "W/\"second-long-non-matching-value\", "
  17977. "W/\"third-long-non-matching-value\""}};
  17978. auto res5 = cli.Get("/static/etag_boundary_testfile.txt", h4);
  17979. ASSERT_TRUE(res5);
  17980. EXPECT_EQ(200, res5->status); // Should not match
  17981. // Test 5: Single character that is not "*" (edge case)
  17982. Headers h5 = {{"If-None-Match", "X"}};
  17983. auto res6 = cli.Get("/static/etag_boundary_testfile.txt", h5);
  17984. ASSERT_TRUE(res6);
  17985. EXPECT_EQ(200, res6->status); // Should not match
  17986. svr.stop();
  17987. t.join();
  17988. std::remove(fname);
  17989. }
  17990. TEST(ETagTest, LastModifiedAndIfModifiedSince) {
  17991. using namespace httplib;
  17992. // Create a test file
  17993. const char *fname = "ims_testfile.txt";
  17994. const char *content = "if-modified-since-test";
  17995. {
  17996. std::ofstream ofs(fname);
  17997. ofs << content;
  17998. ASSERT_TRUE(ofs.good());
  17999. }
  18000. Server svr;
  18001. svr.set_mount_point("/static", ".");
  18002. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18003. svr.wait_until_ready();
  18004. Client cli(HOST, PORT);
  18005. // First request: should get 200 with Last-Modified header
  18006. auto res1 = cli.Get("/static/ims_testfile.txt");
  18007. ASSERT_TRUE(res1);
  18008. ASSERT_EQ(200, res1->status);
  18009. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18010. std::string last_modified = res1->get_header_value("Last-Modified");
  18011. EXPECT_FALSE(last_modified.empty());
  18012. // If-Modified-Since with same time: expect 304
  18013. Headers h2 = {{"If-Modified-Since", last_modified}};
  18014. auto res2 = cli.Get("/static/ims_testfile.txt", h2);
  18015. ASSERT_TRUE(res2);
  18016. EXPECT_EQ(304, res2->status);
  18017. // If-Modified-Since with future time: expect 304
  18018. Headers h3 = {{"If-Modified-Since", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18019. auto res3 = cli.Get("/static/ims_testfile.txt", h3);
  18020. ASSERT_TRUE(res3);
  18021. EXPECT_EQ(304, res3->status);
  18022. // If-Modified-Since with past time: expect 200
  18023. Headers h4 = {{"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18024. auto res4 = cli.Get("/static/ims_testfile.txt", h4);
  18025. ASSERT_TRUE(res4);
  18026. EXPECT_EQ(200, res4->status);
  18027. // If-None-Match takes precedence over If-Modified-Since
  18028. // (send matching ETag with old If-Modified-Since -> should still be 304)
  18029. ASSERT_TRUE(res1->has_header("ETag"));
  18030. std::string etag = res1->get_header_value("ETag");
  18031. Headers h5 = {{"If-None-Match", etag},
  18032. {"If-Modified-Since", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18033. auto res5 = cli.Get("/static/ims_testfile.txt", h5);
  18034. ASSERT_TRUE(res5);
  18035. EXPECT_EQ(304, res5->status);
  18036. svr.stop();
  18037. t.join();
  18038. std::remove(fname);
  18039. }
  18040. TEST(ETagTest, VaryAcceptEncodingWithCompression) {
  18041. using namespace httplib;
  18042. Server svr;
  18043. // Endpoint that returns compressible content
  18044. svr.Get("/compressible", [](const Request &, Response &res) {
  18045. // Return a large enough body to trigger compression
  18046. std::string body(1000, 'a');
  18047. res.set_content(body, "text/plain");
  18048. });
  18049. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18050. svr.wait_until_ready();
  18051. Client cli(HOST, PORT);
  18052. // Request with gzip support: should get Vary header when compressed
  18053. cli.set_compress(true);
  18054. auto res1 = cli.Get("/compressible");
  18055. ASSERT_TRUE(res1);
  18056. EXPECT_EQ(200, res1->status);
  18057. // If Content-Encoding is set, Vary should also be set
  18058. if (res1->has_header("Content-Encoding")) {
  18059. EXPECT_TRUE(res1->has_header("Vary"));
  18060. EXPECT_EQ("Accept-Encoding", res1->get_header_value("Vary"));
  18061. }
  18062. // Request without Accept-Encoding header: should not have compression
  18063. Headers h_no_compress;
  18064. auto res2 = cli.Get("/compressible", h_no_compress);
  18065. ASSERT_TRUE(res2);
  18066. EXPECT_EQ(200, res2->status);
  18067. // Verify Vary header is present when compression is applied
  18068. // (the exact behavior depends on server configuration)
  18069. svr.stop();
  18070. t.join();
  18071. }
  18072. TEST(ETagTest, IfRangeWithETag) {
  18073. using namespace httplib;
  18074. // Create a test file with known content
  18075. const char *fname = "if_range_testfile.txt";
  18076. const std::string content = "0123456789ABCDEFGHIJ"; // 20 bytes
  18077. {
  18078. std::ofstream ofs(fname);
  18079. ofs << content;
  18080. ASSERT_TRUE(ofs.good());
  18081. }
  18082. Server svr;
  18083. svr.set_mount_point("/static", ".");
  18084. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18085. svr.wait_until_ready();
  18086. Client cli(HOST, PORT);
  18087. // First request: get ETag
  18088. auto res1 = cli.Get("/static/if_range_testfile.txt");
  18089. ASSERT_TRUE(res1);
  18090. ASSERT_EQ(200, res1->status);
  18091. ASSERT_TRUE(res1->has_header("ETag"));
  18092. std::string etag = res1->get_header_value("ETag");
  18093. // RFC 9110 Section 13.1.5: If-Range requires strong ETag comparison.
  18094. // Since our server generates weak ETags (W/"..."), If-Range with our
  18095. // ETag should NOT result in partial content - it should return full content.
  18096. Headers h2 = {{"Range", "bytes=0-4"}, {"If-Range", etag}};
  18097. auto res2 = cli.Get("/static/if_range_testfile.txt", h2);
  18098. ASSERT_TRUE(res2);
  18099. // Weak ETag in If-Range -> full content (200), not partial (206)
  18100. EXPECT_EQ(200, res2->status);
  18101. EXPECT_EQ(content, res2->body);
  18102. EXPECT_FALSE(res2->has_header("Content-Range"));
  18103. // Range request with non-matching If-Range (ETag): should get 200 (full
  18104. // content)
  18105. Headers h3 = {{"Range", "bytes=0-4"}, {"If-Range", "W/\"wrong-etag\""}};
  18106. auto res3 = cli.Get("/static/if_range_testfile.txt", h3);
  18107. ASSERT_TRUE(res3);
  18108. EXPECT_EQ(200, res3->status);
  18109. EXPECT_EQ(content, res3->body);
  18110. EXPECT_FALSE(res3->has_header("Content-Range"));
  18111. // Range request with strong ETag (hypothetical - our server doesn't generate
  18112. // strong ETags, but if client sends a strong ETag that doesn't match, it
  18113. // should return full content)
  18114. Headers h4 = {{"Range", "bytes=0-4"}, {"If-Range", "\"strong-etag\""}};
  18115. auto res4 = cli.Get("/static/if_range_testfile.txt", h4);
  18116. ASSERT_TRUE(res4);
  18117. EXPECT_EQ(200, res4->status);
  18118. EXPECT_EQ(content, res4->body);
  18119. EXPECT_FALSE(res4->has_header("Content-Range"));
  18120. svr.stop();
  18121. t.join();
  18122. std::remove(fname);
  18123. }
  18124. TEST(ETagTest, IfRangeWithDate) {
  18125. using namespace httplib;
  18126. // Create a test file
  18127. const char *fname = "if_range_date_testfile.txt";
  18128. const std::string content = "ABCDEFGHIJ0123456789"; // 20 bytes
  18129. {
  18130. std::ofstream ofs(fname);
  18131. ofs << content;
  18132. ASSERT_TRUE(ofs.good());
  18133. }
  18134. Server svr;
  18135. svr.set_mount_point("/static", ".");
  18136. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18137. svr.wait_until_ready();
  18138. Client cli(HOST, PORT);
  18139. // First request: get Last-Modified
  18140. auto res1 = cli.Get("/static/if_range_date_testfile.txt");
  18141. ASSERT_TRUE(res1);
  18142. ASSERT_EQ(200, res1->status);
  18143. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18144. std::string last_modified = res1->get_header_value("Last-Modified");
  18145. // Range request with matching If-Range (date): should get 206
  18146. Headers h2 = {{"Range", "bytes=5-9"}, {"If-Range", last_modified}};
  18147. auto res2 = cli.Get("/static/if_range_date_testfile.txt", h2);
  18148. ASSERT_TRUE(res2);
  18149. EXPECT_EQ(206, res2->status);
  18150. EXPECT_EQ("FGHIJ", res2->body);
  18151. // Range request with old If-Range date: should get 200 (full content)
  18152. Headers h3 = {{"Range", "bytes=5-9"},
  18153. {"If-Range", "Sun, 01 Jan 2000 00:00:00 GMT"}};
  18154. auto res3 = cli.Get("/static/if_range_date_testfile.txt", h3);
  18155. ASSERT_TRUE(res3);
  18156. EXPECT_EQ(200, res3->status);
  18157. EXPECT_EQ(content, res3->body);
  18158. // Range request with future If-Range date: should get 206
  18159. Headers h4 = {{"Range", "bytes=0-4"},
  18160. {"If-Range", "Sun, 01 Jan 2099 00:00:00 GMT"}};
  18161. auto res4 = cli.Get("/static/if_range_date_testfile.txt", h4);
  18162. ASSERT_TRUE(res4);
  18163. EXPECT_EQ(206, res4->status);
  18164. EXPECT_EQ("ABCDE", res4->body);
  18165. svr.stop();
  18166. t.join();
  18167. std::remove(fname);
  18168. }
  18169. TEST(ETagTest, MalformedIfNoneMatchAndWhitespace) {
  18170. using namespace httplib;
  18171. const char *fname = "etag_malformed.txt";
  18172. const char *content = "malformed-etag";
  18173. {
  18174. std::ofstream ofs(fname);
  18175. ofs << content;
  18176. ASSERT_TRUE(ofs.good());
  18177. }
  18178. Server svr;
  18179. svr.set_mount_point("/static", ".");
  18180. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18181. svr.wait_until_ready();
  18182. Client cli(HOST, PORT);
  18183. // baseline: should get 200 and an ETag
  18184. auto res1 = cli.Get("/static/etag_malformed.txt");
  18185. ASSERT_TRUE(res1);
  18186. ASSERT_EQ(200, res1->status);
  18187. ASSERT_TRUE(res1->has_header("ETag"));
  18188. // Malformed ETag value (missing quotes) should be treated as non-matching
  18189. Headers h_bad = {{"If-None-Match", "W/noquotes"}};
  18190. auto res_bad = cli.Get("/static/etag_malformed.txt", h_bad);
  18191. ASSERT_TRUE(res_bad);
  18192. EXPECT_EQ(200, res_bad->status);
  18193. // Whitespace-only header value should be considered invalid / non-matching
  18194. std::string raw_req = "GET /static/etag_malformed.txt HTTP/1.1\r\n"
  18195. "Host: localhost\r\n"
  18196. "If-None-Match: \r\n"
  18197. "Connection: close\r\n"
  18198. "\r\n";
  18199. std::string out;
  18200. ASSERT_TRUE(send_request(5, raw_req, &out));
  18201. EXPECT_EQ("HTTP/1.1 200 OK", out.substr(0, 15));
  18202. svr.stop();
  18203. t.join();
  18204. std::remove(fname);
  18205. }
  18206. TEST(ETagTest, InvalidIfModifiedSinceAndIfRangeDate) {
  18207. using namespace httplib;
  18208. const char *fname = "ims_invalid_format.txt";
  18209. const char *content = "ims-bad-format";
  18210. {
  18211. std::ofstream ofs(fname);
  18212. ofs << content;
  18213. ASSERT_TRUE(ofs.good());
  18214. }
  18215. Server svr;
  18216. svr.set_mount_point("/static", ".");
  18217. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18218. svr.wait_until_ready();
  18219. Client cli(HOST, PORT);
  18220. auto res1 = cli.Get("/static/ims_invalid_format.txt");
  18221. ASSERT_TRUE(res1);
  18222. ASSERT_EQ(200, res1->status);
  18223. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18224. // If-Modified-Since with invalid format should not result in 304
  18225. Headers h_bad_date = {{"If-Modified-Since", "not-a-valid-date"}};
  18226. auto res_bad = cli.Get("/static/ims_invalid_format.txt", h_bad_date);
  18227. ASSERT_TRUE(res_bad);
  18228. EXPECT_EQ(200, res_bad->status);
  18229. // If-Range with invalid date format should be treated as mismatch -> full
  18230. // content (200)
  18231. Headers h_ifrange_bad = {{"Range", "bytes=0-3"},
  18232. {"If-Range", "invalid-date"}};
  18233. auto res_ifrange = cli.Get("/static/ims_invalid_format.txt", h_ifrange_bad);
  18234. ASSERT_TRUE(res_ifrange);
  18235. EXPECT_EQ(200, res_ifrange->status);
  18236. svr.stop();
  18237. t.join();
  18238. std::remove(fname);
  18239. }
  18240. TEST(ETagTest, IfRangeWithMalformedETag) {
  18241. using namespace httplib;
  18242. const char *fname = "ifrange_malformed.txt";
  18243. const std::string content = "0123456789";
  18244. {
  18245. std::ofstream ofs(fname);
  18246. ofs << content;
  18247. ASSERT_TRUE(ofs.good());
  18248. }
  18249. Server svr;
  18250. svr.set_mount_point("/static", ".");
  18251. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18252. svr.wait_until_ready();
  18253. Client cli(HOST, PORT);
  18254. // First request: get ETag
  18255. auto res1 = cli.Get("/static/ifrange_malformed.txt");
  18256. ASSERT_TRUE(res1);
  18257. ASSERT_EQ(200, res1->status);
  18258. ASSERT_TRUE(res1->has_header("ETag"));
  18259. // If-Range with malformed ETag (no quotes) should be treated as mismatch ->
  18260. // full content (200)
  18261. Headers h_malformed = {{"Range", "bytes=0-4"}, {"If-Range", "W/noquotes"}};
  18262. auto res2 = cli.Get("/static/ifrange_malformed.txt", h_malformed);
  18263. ASSERT_TRUE(res2);
  18264. EXPECT_EQ(200, res2->status);
  18265. EXPECT_EQ(content, res2->body);
  18266. svr.stop();
  18267. t.join();
  18268. std::remove(fname);
  18269. }
  18270. TEST(ETagTest, ExtremeLargeDateValues) {
  18271. using namespace httplib;
  18272. const char *fname = "ims_extreme_date.txt";
  18273. const char *content = "ims-extreme-date";
  18274. {
  18275. std::ofstream ofs(fname);
  18276. ofs << content;
  18277. ASSERT_TRUE(ofs.good());
  18278. }
  18279. Server svr;
  18280. svr.set_mount_point("/static", ".");
  18281. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18282. svr.wait_until_ready();
  18283. Client cli(HOST, PORT);
  18284. auto res1 = cli.Get(std::string("/static/") + fname);
  18285. ASSERT_TRUE(res1);
  18286. ASSERT_EQ(200, res1->status);
  18287. ASSERT_TRUE(res1->has_header("Last-Modified"));
  18288. // Extremely large year that may overflow date parsing routines.
  18289. Headers h_large_date = {
  18290. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18291. auto res_bad = cli.Get(std::string("/static/") + fname, h_large_date);
  18292. ASSERT_TRUE(res_bad);
  18293. // Expect server to treat this as invalid/mismatch and return full content
  18294. EXPECT_EQ(200, res_bad->status);
  18295. // If-Range with extremely large date should be treated as mismatch -> full
  18296. // content (200)
  18297. Headers h_ifrange_large = {{"Range", "bytes=0-3"},
  18298. {"If-Range", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18299. auto res_ifrange = cli.Get(std::string("/static/") + fname, h_ifrange_large);
  18300. ASSERT_TRUE(res_ifrange);
  18301. EXPECT_EQ(200, res_ifrange->status);
  18302. svr.stop();
  18303. t.join();
  18304. std::remove(fname);
  18305. }
  18306. TEST(ETagTest, NegativeFileModificationTime) {
  18307. using namespace httplib;
  18308. const char *fname = "ims_negative_mtime.txt";
  18309. const std::string content = "negative-mtime";
  18310. {
  18311. std::ofstream ofs(fname);
  18312. ofs << content;
  18313. ASSERT_TRUE(ofs.good());
  18314. }
  18315. // Try to set file mtime to a negative value. This may fail on some
  18316. // platforms/filesystems; if it fails, the test will still verify server
  18317. // behaves safely by performing a regular conditional request.
  18318. #if defined(__APPLE__) || defined(__linux__)
  18319. bool set_negative = false;
  18320. do {
  18321. struct timeval times[2];
  18322. // access time: now
  18323. times[0].tv_sec = time(nullptr);
  18324. times[0].tv_usec = 0;
  18325. // modification time: negative (e.g., -1)
  18326. times[1].tv_sec = -1;
  18327. times[1].tv_usec = 0;
  18328. if (utimes(fname, times) == 0) { set_negative = true; }
  18329. } while (0);
  18330. #else
  18331. bool set_negative = false;
  18332. #endif
  18333. Server svr;
  18334. svr.set_mount_point("/static", ".");
  18335. auto t = std::thread([&]() { svr.listen(HOST, PORT); });
  18336. svr.wait_until_ready();
  18337. Client cli(HOST, PORT);
  18338. auto res1 = cli.Get(std::string("/static/") + fname);
  18339. ASSERT_TRUE(res1);
  18340. ASSERT_EQ(200, res1->status);
  18341. bool has_last_modified = res1->has_header("Last-Modified");
  18342. std::string last_modified;
  18343. if (has_last_modified) {
  18344. last_modified = res1->get_header_value("Last-Modified");
  18345. }
  18346. if (set_negative) {
  18347. // If we successfully set a negative mtime, ensure server returns a
  18348. // Last-Modified string (may be empty or normalized). Send If-Modified-Since
  18349. // with an old date and ensure server handles it without crash.
  18350. Headers h_old = {{"If-Modified-Since", "Sun, 01 Jan 1970 00:00:00 GMT"}};
  18351. auto res2 = cli.Get(std::string("/static/") + fname, h_old);
  18352. ASSERT_TRUE(res2);
  18353. // Behavior may vary; at minimum ensure server responds (200 or 304).
  18354. EXPECT_TRUE(res2->status == 200 || res2->status == 304);
  18355. } else {
  18356. // Could not set negative mtime on this platform; fall back to verifying
  18357. // that normal invalid/malformed dates are treated safely (non-304).
  18358. Headers h_bad_date = {
  18359. {"If-Modified-Since", "Sun, 01 Jan 99999 00:00:00 GMT"}};
  18360. auto res_bad = cli.Get(std::string("/static/") + fname, h_bad_date);
  18361. ASSERT_TRUE(res_bad);
  18362. EXPECT_EQ(200, res_bad->status);
  18363. }
  18364. svr.stop();
  18365. t.join();
  18366. std::remove(fname);
  18367. }
  18368. //==============================================================================
  18369. // SSE Parsing Tests
  18370. //==============================================================================
  18371. class SSEParsingTest : public ::testing::Test {
  18372. protected:
  18373. // Test helper that mimics SSE parsing behavior
  18374. static bool parse_sse_line(const std::string &line, sse::SSEMessage &msg,
  18375. int &retry_ms) {
  18376. // Blank line signals end of event
  18377. if (line.empty() || line == "\r") { return true; }
  18378. // Lines starting with ':' are comments (ignored)
  18379. if (!line.empty() && line[0] == ':') { return false; }
  18380. // Find the colon separator
  18381. auto colon_pos = line.find(':');
  18382. if (colon_pos == std::string::npos) {
  18383. // Line with no colon is treated as field name with empty value
  18384. return false;
  18385. }
  18386. std::string field = line.substr(0, colon_pos);
  18387. std::string value;
  18388. // Value starts after colon, skip optional single space
  18389. if (colon_pos + 1 < line.size()) {
  18390. size_t value_start = colon_pos + 1;
  18391. if (line[value_start] == ' ') { value_start++; }
  18392. value = line.substr(value_start);
  18393. // Remove trailing \r if present
  18394. if (!value.empty() && value.back() == '\r') { value.pop_back(); }
  18395. }
  18396. // Handle known fields
  18397. if (field == "event") {
  18398. msg.event = value;
  18399. } else if (field == "data") {
  18400. // Multiple data lines are concatenated with newlines
  18401. if (!msg.data.empty()) { msg.data += "\n"; }
  18402. msg.data += value;
  18403. } else if (field == "id") {
  18404. // Empty id is valid (clears the last event ID)
  18405. msg.id = value;
  18406. } else if (field == "retry") {
  18407. // Parse retry interval in milliseconds
  18408. {
  18409. int v = 0;
  18410. auto res =
  18411. detail::from_chars(value.data(), value.data() + value.size(), v);
  18412. if (res.ec == std::errc{}) { retry_ms = v; }
  18413. }
  18414. }
  18415. // Unknown fields are ignored per SSE spec
  18416. return false;
  18417. }
  18418. };
  18419. // Test: Single-line data
  18420. TEST_F(SSEParsingTest, SingleLineData) {
  18421. sse::SSEMessage msg;
  18422. int retry_ms = 3000;
  18423. EXPECT_FALSE(parse_sse_line("data: hello", msg, retry_ms));
  18424. EXPECT_EQ(msg.data, "hello");
  18425. EXPECT_EQ(msg.event, "message");
  18426. // Blank line ends event
  18427. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18428. }
  18429. // Test: Multi-line data
  18430. TEST_F(SSEParsingTest, MultiLineData) {
  18431. sse::SSEMessage msg;
  18432. int retry_ms = 3000;
  18433. EXPECT_FALSE(parse_sse_line("data: line1", msg, retry_ms));
  18434. EXPECT_FALSE(parse_sse_line("data: line2", msg, retry_ms));
  18435. EXPECT_FALSE(parse_sse_line("data: line3", msg, retry_ms));
  18436. EXPECT_EQ(msg.data, "line1\nline2\nline3");
  18437. }
  18438. // Test: Custom event types
  18439. TEST_F(SSEParsingTest, CustomEventType) {
  18440. sse::SSEMessage msg;
  18441. int retry_ms = 3000;
  18442. EXPECT_FALSE(parse_sse_line("event: update", msg, retry_ms));
  18443. EXPECT_FALSE(parse_sse_line("data: payload", msg, retry_ms));
  18444. EXPECT_EQ(msg.event, "update");
  18445. EXPECT_EQ(msg.data, "payload");
  18446. }
  18447. // Test: Event ID handling
  18448. TEST_F(SSEParsingTest, EventIdHandling) {
  18449. sse::SSEMessage msg;
  18450. int retry_ms = 3000;
  18451. EXPECT_FALSE(parse_sse_line("id: 12345", msg, retry_ms));
  18452. EXPECT_FALSE(parse_sse_line("data: test", msg, retry_ms));
  18453. EXPECT_EQ(msg.id, "12345");
  18454. }
  18455. // Test: Empty event ID (clears last event ID)
  18456. TEST_F(SSEParsingTest, EmptyEventId) {
  18457. sse::SSEMessage msg;
  18458. msg.id = "previous";
  18459. int retry_ms = 3000;
  18460. EXPECT_FALSE(parse_sse_line("id:", msg, retry_ms));
  18461. EXPECT_EQ(msg.id, "");
  18462. }
  18463. // Test: Retry field parsing
  18464. TEST_F(SSEParsingTest, RetryFieldParsing) {
  18465. sse::SSEMessage msg;
  18466. int retry_ms = 3000;
  18467. EXPECT_FALSE(parse_sse_line("retry: 5000", msg, retry_ms));
  18468. EXPECT_EQ(retry_ms, 5000);
  18469. }
  18470. // Test: Invalid retry value
  18471. TEST_F(SSEParsingTest, InvalidRetryValue) {
  18472. sse::SSEMessage msg;
  18473. int retry_ms = 3000;
  18474. EXPECT_FALSE(parse_sse_line("retry: invalid", msg, retry_ms));
  18475. EXPECT_EQ(retry_ms, 3000); // Unchanged
  18476. }
  18477. // Test: Comments (lines starting with :)
  18478. TEST_F(SSEParsingTest, CommentsIgnored) {
  18479. sse::SSEMessage msg;
  18480. int retry_ms = 3000;
  18481. EXPECT_FALSE(parse_sse_line(": this is a comment", msg, retry_ms));
  18482. EXPECT_EQ(msg.data, "");
  18483. EXPECT_EQ(msg.event, "message");
  18484. }
  18485. // Test: Colon in value
  18486. TEST_F(SSEParsingTest, ColonInValue) {
  18487. sse::SSEMessage msg;
  18488. int retry_ms = 3000;
  18489. EXPECT_FALSE(parse_sse_line("data: hello:world:test", msg, retry_ms));
  18490. EXPECT_EQ(msg.data, "hello:world:test");
  18491. }
  18492. // Test: Line with no colon (field name only)
  18493. TEST_F(SSEParsingTest, FieldNameOnly) {
  18494. sse::SSEMessage msg;
  18495. int retry_ms = 3000;
  18496. // According to SSE spec, this is treated as field name with empty value
  18497. EXPECT_FALSE(parse_sse_line("data", msg, retry_ms));
  18498. // Since we don't recognize "data" without colon, data should be empty
  18499. EXPECT_EQ(msg.data, "");
  18500. }
  18501. // Test: Trailing \r handling
  18502. TEST_F(SSEParsingTest, TrailingCarriageReturn) {
  18503. sse::SSEMessage msg;
  18504. int retry_ms = 3000;
  18505. EXPECT_FALSE(parse_sse_line("data: hello\r", msg, retry_ms));
  18506. EXPECT_EQ(msg.data, "hello");
  18507. }
  18508. // Test: Unknown fields ignored
  18509. TEST_F(SSEParsingTest, UnknownFieldsIgnored) {
  18510. sse::SSEMessage msg;
  18511. int retry_ms = 3000;
  18512. EXPECT_FALSE(parse_sse_line("unknown: value", msg, retry_ms));
  18513. EXPECT_EQ(msg.data, "");
  18514. EXPECT_EQ(msg.event, "message");
  18515. }
  18516. // Test: Space after colon is optional
  18517. TEST_F(SSEParsingTest, SpaceAfterColonOptional) {
  18518. sse::SSEMessage msg1, msg2;
  18519. int retry_ms = 3000;
  18520. EXPECT_FALSE(parse_sse_line("data: hello", msg1, retry_ms));
  18521. EXPECT_FALSE(parse_sse_line("data:hello", msg2, retry_ms));
  18522. EXPECT_EQ(msg1.data, "hello");
  18523. EXPECT_EQ(msg2.data, "hello");
  18524. }
  18525. // Test: SSEMessage clear
  18526. TEST_F(SSEParsingTest, MessageClear) {
  18527. sse::SSEMessage msg;
  18528. msg.event = "custom";
  18529. msg.data = "some data";
  18530. msg.id = "123";
  18531. msg.clear();
  18532. EXPECT_EQ(msg.event, "message");
  18533. EXPECT_EQ(msg.data, "");
  18534. EXPECT_EQ(msg.id, "");
  18535. }
  18536. // Test: Complete event parsing
  18537. TEST_F(SSEParsingTest, CompleteEventParsing) {
  18538. sse::SSEMessage msg;
  18539. int retry_ms = 3000;
  18540. EXPECT_FALSE(parse_sse_line("event: notification", msg, retry_ms));
  18541. EXPECT_FALSE(parse_sse_line("id: evt-42", msg, retry_ms));
  18542. EXPECT_FALSE(parse_sse_line("data: {\"type\":\"alert\"}", msg, retry_ms));
  18543. EXPECT_FALSE(parse_sse_line("retry: 1000", msg, retry_ms));
  18544. // Blank line ends event
  18545. EXPECT_TRUE(parse_sse_line("", msg, retry_ms));
  18546. EXPECT_EQ(msg.event, "notification");
  18547. EXPECT_EQ(msg.id, "evt-42");
  18548. EXPECT_EQ(msg.data, "{\"type\":\"alert\"}");
  18549. EXPECT_EQ(retry_ms, 1000);
  18550. }
  18551. //==============================================================================
  18552. // Integration Tests with Server
  18553. //==============================================================================
  18554. class SSEIntegrationTest : public ::testing::Test {
  18555. protected:
  18556. void SetUp() override {
  18557. stop_server_.store(false);
  18558. events_.clear();
  18559. server_ = httplib::detail::make_unique<Server>();
  18560. setup_server();
  18561. start_server();
  18562. }
  18563. void TearDown() override {
  18564. stop_server_.store(true);
  18565. event_cv_.notify_all();
  18566. server_->stop();
  18567. if (server_thread_.joinable()) { server_thread_.join(); }
  18568. }
  18569. void setup_server() {
  18570. // Simple SSE endpoint
  18571. server_->Get("/events", [this](const Request &req, Response &res) {
  18572. auto last_id = req.get_header_value("Last-Event-ID");
  18573. if (!last_id.empty()) { last_received_event_id_ = last_id; }
  18574. res.set_chunked_content_provider(
  18575. "text/event-stream", [this](size_t /*offset*/, DataSink &sink) {
  18576. std::unique_lock<std::mutex> lock(event_mutex_);
  18577. if (event_cv_.wait_for(
  18578. lock, std::chrono::milliseconds(200), [this] {
  18579. return !events_.empty() || stop_server_.load();
  18580. })) {
  18581. if (stop_server_.load()) { return false; }
  18582. if (!events_.empty()) {
  18583. std::string event = events_.front();
  18584. events_.erase(events_.begin());
  18585. sink.write(event.data(), event.size());
  18586. return true;
  18587. }
  18588. }
  18589. return !stop_server_.load();
  18590. });
  18591. });
  18592. // Endpoint that returns error
  18593. server_->Get("/error-endpoint", [](const Request &, Response &res) {
  18594. res.status = 500;
  18595. res.set_content("Internal Server Error", "text/plain");
  18596. });
  18597. // Endpoint for custom event types
  18598. server_->Get("/custom-events", [](const Request &, Response &res) {
  18599. res.set_chunked_content_provider(
  18600. "text/event-stream", [](size_t offset, DataSink &sink) {
  18601. if (offset == 0) {
  18602. std::string event = "event: update\ndata: updated\n\n"
  18603. "event: delete\ndata: deleted\n\n";
  18604. sink.write(event.data(), event.size());
  18605. }
  18606. return false; // End stream after sending
  18607. });
  18608. });
  18609. }
  18610. void start_server() {
  18611. port_ = server_->bind_to_any_port(HOST);
  18612. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  18613. // Wait for server to start
  18614. while (!server_->is_running()) {
  18615. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  18616. }
  18617. }
  18618. int get_port() const { return port_; }
  18619. void send_event(const std::string &event) {
  18620. std::lock_guard<std::mutex> lock(event_mutex_);
  18621. events_.push_back(event);
  18622. event_cv_.notify_all();
  18623. }
  18624. std::unique_ptr<Server> server_;
  18625. std::thread server_thread_;
  18626. std::mutex event_mutex_;
  18627. std::condition_variable event_cv_;
  18628. std::vector<std::string> events_;
  18629. std::atomic<bool> stop_server_{false};
  18630. std::string last_received_event_id_;
  18631. int port_ = 0;
  18632. };
  18633. // Test: Successful connection and on_open callback
  18634. TEST_F(SSEIntegrationTest, SuccessfulConnection) {
  18635. // Add a simple endpoint that sends one event and closes
  18636. server_->Get("/simple-event", [](const Request &, Response &res) {
  18637. res.set_chunked_content_provider(
  18638. "text/event-stream", [](size_t offset, DataSink &sink) {
  18639. if (offset == 0) {
  18640. std::string event = "data: hello\n\n";
  18641. sink.write(event.data(), event.size());
  18642. }
  18643. return false; // Close stream after sending
  18644. });
  18645. });
  18646. Client client("localhost", get_port());
  18647. sse::SSEClient sse(client, "/simple-event");
  18648. std::atomic<bool> open_called{false};
  18649. std::atomic<bool> message_received{false};
  18650. sse.on_open([&open_called]() { open_called.store(true); });
  18651. sse.on_message([&message_received](const sse::SSEMessage &msg) {
  18652. if (msg.data == "hello") { message_received.store(true); }
  18653. });
  18654. sse.set_reconnect_interval(100);
  18655. sse.set_max_reconnect_attempts(1);
  18656. // Start async
  18657. sse.start_async();
  18658. // Wait for message to be processed
  18659. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18660. sse.stop();
  18661. EXPECT_TRUE(open_called.load());
  18662. EXPECT_TRUE(message_received.load());
  18663. }
  18664. // Test: on_message callback
  18665. TEST_F(SSEIntegrationTest, OnMessageCallback) {
  18666. // Endpoint that sends multiple events then closes
  18667. server_->Get("/multi-event", [](const Request &, Response &res) {
  18668. res.set_chunked_content_provider(
  18669. "text/event-stream", [](size_t offset, DataSink &sink) {
  18670. if (offset == 0) {
  18671. std::string events = "data: message1\n\ndata: message2\n\n";
  18672. sink.write(events.data(), events.size());
  18673. }
  18674. return false;
  18675. });
  18676. });
  18677. Client client("localhost", get_port());
  18678. sse::SSEClient sse(client, "/multi-event");
  18679. std::vector<std::string> received_messages;
  18680. std::mutex messages_mutex;
  18681. sse.on_message([&](const sse::SSEMessage &msg) {
  18682. std::lock_guard<std::mutex> lock(messages_mutex);
  18683. received_messages.push_back(msg.data);
  18684. });
  18685. sse.set_reconnect_interval(100);
  18686. sse.set_max_reconnect_attempts(1);
  18687. sse.start_async();
  18688. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18689. sse.stop();
  18690. std::lock_guard<std::mutex> lock(messages_mutex);
  18691. EXPECT_GE(received_messages.size(), 2u);
  18692. if (received_messages.size() >= 2) {
  18693. EXPECT_EQ(received_messages[0], "message1");
  18694. EXPECT_EQ(received_messages[1], "message2");
  18695. }
  18696. }
  18697. // Test: on_event for specific types
  18698. TEST_F(SSEIntegrationTest, OnEventForSpecificTypes) {
  18699. Client client("localhost", get_port());
  18700. sse::SSEClient sse(client, "/custom-events");
  18701. std::atomic<bool> update_received{false};
  18702. std::atomic<bool> delete_received{false};
  18703. sse.on_event("update", [&update_received](const sse::SSEMessage &msg) {
  18704. if (msg.data == "updated") { update_received.store(true); }
  18705. });
  18706. sse.on_event("delete", [&delete_received](const sse::SSEMessage &msg) {
  18707. if (msg.data == "deleted") { delete_received.store(true); }
  18708. });
  18709. sse.set_max_reconnect_attempts(1);
  18710. sse.start_async();
  18711. std::this_thread::sleep_for(std::chrono::milliseconds(300));
  18712. sse.stop();
  18713. EXPECT_TRUE(update_received.load());
  18714. EXPECT_TRUE(delete_received.load());
  18715. }
  18716. // Test: on_error callback on connection failure
  18717. TEST_F(SSEIntegrationTest, OnErrorCallback) {
  18718. // Connect to a non-existent port
  18719. Client client("localhost", 59999);
  18720. sse::SSEClient sse(client, "/events");
  18721. std::atomic<bool> error_called{false};
  18722. Error received_error = Error::Success;
  18723. sse.on_error([&](Error err) {
  18724. error_called.store(true);
  18725. received_error = err;
  18726. });
  18727. sse.set_reconnect_interval(50);
  18728. sse.set_max_reconnect_attempts(1);
  18729. sse.start_async();
  18730. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18731. sse.stop();
  18732. EXPECT_TRUE(error_called.load());
  18733. EXPECT_NE(received_error, Error::Success);
  18734. }
  18735. // Test: Last-Event-ID header sent on reconnect
  18736. TEST_F(SSEIntegrationTest, LastEventIdHeader) {
  18737. // Endpoint that sends event with ID
  18738. server_->Get("/event-with-id", [](const Request &, Response &res) {
  18739. res.set_chunked_content_provider(
  18740. "text/event-stream", [](size_t offset, DataSink &sink) {
  18741. if (offset == 0) {
  18742. std::string event = "id: evt-123\ndata: test\n\n";
  18743. sink.write(event.data(), event.size());
  18744. }
  18745. return false;
  18746. });
  18747. });
  18748. Client client("localhost", get_port());
  18749. sse::SSEClient sse(client, "/event-with-id");
  18750. std::atomic<bool> id_received{false};
  18751. sse.on_message([&](const sse::SSEMessage &msg) {
  18752. if (!msg.id.empty()) { id_received.store(true); }
  18753. });
  18754. sse.set_reconnect_interval(100);
  18755. sse.set_max_reconnect_attempts(1);
  18756. sse.start_async();
  18757. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18758. sse.stop();
  18759. EXPECT_TRUE(id_received.load());
  18760. EXPECT_EQ(sse.last_event_id(), "evt-123");
  18761. }
  18762. // Test: Manual stop
  18763. TEST_F(SSEIntegrationTest, ManualStop) {
  18764. // Endpoint that sends one event and stays open briefly
  18765. std::atomic<bool> handler_running{true};
  18766. server_->Get("/stay-open", [&handler_running](const Request &,
  18767. Response &res) {
  18768. res.set_chunked_content_provider(
  18769. "text/event-stream", [&handler_running](size_t offset, DataSink &sink) {
  18770. if (offset == 0) {
  18771. std::string event = "data: connected\n\n";
  18772. sink.write(event.data(), event.size());
  18773. }
  18774. // Keep connection open while handler_running is true
  18775. for (int i = 0; i < 10 && handler_running.load(); ++i) {
  18776. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18777. }
  18778. return false;
  18779. });
  18780. });
  18781. Client client("localhost", get_port());
  18782. sse::SSEClient sse(client, "/stay-open");
  18783. std::atomic<bool> connected{false};
  18784. sse.on_open([&connected]() { connected.store(true); });
  18785. sse.set_reconnect_interval(100);
  18786. sse.set_max_reconnect_attempts(1);
  18787. sse.start_async();
  18788. // Wait for connection to establish
  18789. for (int i = 0; i < 20 && !connected.load(); ++i) {
  18790. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  18791. }
  18792. EXPECT_TRUE(connected.load());
  18793. EXPECT_TRUE(sse.is_connected());
  18794. // Signal handler to stop
  18795. handler_running.store(false);
  18796. // Stop SSE client
  18797. sse.stop();
  18798. EXPECT_FALSE(sse.is_connected());
  18799. }
  18800. // Test: SSEClient with custom headers
  18801. TEST_F(SSEIntegrationTest, CustomHeaders) {
  18802. // Setup a server endpoint that checks for custom header
  18803. std::atomic<bool> header_received{false};
  18804. server_->Get("/header-check", [&](const Request &req, Response &res) {
  18805. if (req.get_header_value("X-Custom-Header") == "custom-value") {
  18806. header_received.store(true);
  18807. }
  18808. res.set_chunked_content_provider("text/event-stream",
  18809. [](size_t, DataSink &) { return false; });
  18810. });
  18811. Client client("localhost", get_port());
  18812. Headers headers = {{"X-Custom-Header", "custom-value"}};
  18813. sse::SSEClient sse(client, "/header-check", headers);
  18814. sse.set_max_reconnect_attempts(1);
  18815. sse.start_async();
  18816. std::this_thread::sleep_for(std::chrono::milliseconds(200));
  18817. sse.stop();
  18818. EXPECT_TRUE(header_received.load());
  18819. }
  18820. // Test: Reconnect interval configuration
  18821. TEST_F(SSEIntegrationTest, ReconnectIntervalConfiguration) {
  18822. Client client("localhost", get_port());
  18823. sse::SSEClient sse(client, "/events");
  18824. auto &result = sse.set_reconnect_interval(500);
  18825. // Builder pattern should return reference to self
  18826. EXPECT_EQ(&result, &sse);
  18827. }
  18828. // Test: Max reconnect attempts
  18829. TEST_F(SSEIntegrationTest, MaxReconnectAttempts) {
  18830. // Connect to non-existent port to force reconnects
  18831. Client client("localhost", 59998);
  18832. sse::SSEClient sse(client, "/events");
  18833. std::atomic<int> error_count{0};
  18834. sse.on_error([&](Error) { error_count.fetch_add(1); });
  18835. sse.set_reconnect_interval(50);
  18836. sse.set_max_reconnect_attempts(2);
  18837. auto start = std::chrono::steady_clock::now();
  18838. sse.start(); // Blocking call
  18839. auto end = std::chrono::steady_clock::now();
  18840. // Should have stopped after 2 failed attempts
  18841. EXPECT_GE(error_count.load(), 2);
  18842. // Should not have taken too long (max 2 attempts * 50ms + overhead)
  18843. auto duration =
  18844. std::chrono::duration_cast<std::chrono::milliseconds>(end - start);
  18845. #ifdef _WIN32
  18846. // Windows is much slower for socket connection failures
  18847. EXPECT_LT(duration.count(), 7000);
  18848. #else
  18849. EXPECT_LT(duration.count(), 1000);
  18850. #endif
  18851. }
  18852. // Test: Multi-line data in integration
  18853. TEST_F(SSEIntegrationTest, MultiLineDataIntegration) {
  18854. // Endpoint with multi-line data
  18855. server_->Get("/multiline-data", [](const Request &, Response &res) {
  18856. res.set_chunked_content_provider(
  18857. "text/event-stream", [](size_t offset, DataSink &sink) {
  18858. if (offset == 0) {
  18859. std::string event = "data: line1\ndata: line2\ndata: line3\n\n";
  18860. sink.write(event.data(), event.size());
  18861. }
  18862. return false;
  18863. });
  18864. });
  18865. Client client("localhost", get_port());
  18866. sse::SSEClient sse(client, "/multiline-data");
  18867. std::string received_data;
  18868. std::mutex data_mutex;
  18869. sse.on_message([&](const sse::SSEMessage &msg) {
  18870. std::lock_guard<std::mutex> lock(data_mutex);
  18871. received_data = msg.data;
  18872. });
  18873. sse.set_reconnect_interval(100);
  18874. sse.set_max_reconnect_attempts(1);
  18875. sse.start_async();
  18876. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18877. sse.stop();
  18878. std::lock_guard<std::mutex> lock(data_mutex);
  18879. EXPECT_EQ(received_data, "line1\nline2\nline3");
  18880. }
  18881. // Test: Auto-reconnect after server disconnection
  18882. TEST_F(SSEIntegrationTest, AutoReconnectAfterDisconnect) {
  18883. std::atomic<int> connection_count{0};
  18884. std::atomic<int> message_count{0};
  18885. // Endpoint that sends one event and closes, forcing reconnect
  18886. server_->Get("/reconnect-test",
  18887. [&connection_count](const Request &, Response &res) {
  18888. connection_count.fetch_add(1);
  18889. res.set_chunked_content_provider(
  18890. "text/event-stream", [](size_t offset, DataSink &sink) {
  18891. if (offset == 0) {
  18892. std::string event = "data: hello\n\n";
  18893. sink.write(event.data(), event.size());
  18894. }
  18895. return false; // Close connection after sending
  18896. });
  18897. });
  18898. Client client("localhost", get_port());
  18899. sse::SSEClient sse(client, "/reconnect-test");
  18900. sse.on_message([&message_count](const sse::SSEMessage &) {
  18901. message_count.fetch_add(1);
  18902. });
  18903. sse.set_reconnect_interval(100);
  18904. sse.set_max_reconnect_attempts(3);
  18905. sse.start_async();
  18906. // Wait long enough for multiple reconnects
  18907. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18908. sse.stop();
  18909. // Should have connected multiple times (initial + reconnects)
  18910. EXPECT_GE(connection_count.load(), 2);
  18911. // Should have received messages from multiple connections
  18912. EXPECT_GE(message_count.load(), 2);
  18913. }
  18914. // Test: Last-Event-ID sent on reconnect
  18915. TEST_F(SSEIntegrationTest, LastEventIdSentOnReconnect) {
  18916. std::atomic<int> connection_count{0};
  18917. std::vector<std::string> received_last_event_ids;
  18918. std::mutex id_mutex;
  18919. // Endpoint that checks Last-Event-ID header and sends event with ID
  18920. server_->Get("/reconnect-with-id", [&](const Request &req, Response &res) {
  18921. int conn = connection_count.fetch_add(1);
  18922. // Capture the Last-Event-ID header from each connection
  18923. {
  18924. std::lock_guard<std::mutex> lock(id_mutex);
  18925. received_last_event_ids.push_back(req.get_header_value("Last-Event-ID"));
  18926. }
  18927. res.set_chunked_content_provider(
  18928. "text/event-stream", [conn](size_t offset, DataSink &sink) {
  18929. if (offset == 0) {
  18930. std::string event =
  18931. "id: event-" + std::to_string(conn) + "\ndata: msg\n\n";
  18932. sink.write(event.data(), event.size());
  18933. }
  18934. return false;
  18935. });
  18936. });
  18937. Client client("localhost", get_port());
  18938. sse::SSEClient sse(client, "/reconnect-with-id");
  18939. sse.set_reconnect_interval(100);
  18940. sse.set_max_reconnect_attempts(3);
  18941. sse.start_async();
  18942. // Wait for at least 2 connections
  18943. std::this_thread::sleep_for(std::chrono::milliseconds(500));
  18944. sse.stop();
  18945. // Verify behavior
  18946. std::lock_guard<std::mutex> lock(id_mutex);
  18947. EXPECT_GE(received_last_event_ids.size(), 2u);
  18948. // First connection should have no Last-Event-ID
  18949. if (!received_last_event_ids.empty()) {
  18950. EXPECT_EQ(received_last_event_ids[0], "");
  18951. }
  18952. // Second connection should have Last-Event-ID from first connection
  18953. if (received_last_event_ids.size() >= 2) {
  18954. EXPECT_EQ(received_last_event_ids[1], "event-0");
  18955. }
  18956. }
  18957. // Test: set_headers updates headers used on reconnect
  18958. TEST_F(SSEIntegrationTest, SetHeadersUpdatesOnReconnect) {
  18959. std::vector<std::string> received_tokens;
  18960. std::mutex token_mutex;
  18961. // Endpoint that captures Authorization header
  18962. server_->Get("/auth-check", [&](const Request &req, Response &res) {
  18963. {
  18964. std::lock_guard<std::mutex> lock(token_mutex);
  18965. received_tokens.push_back(req.get_header_value("Authorization"));
  18966. }
  18967. res.set_chunked_content_provider(
  18968. "text/event-stream", [](size_t offset, DataSink &sink) {
  18969. if (offset == 0) {
  18970. std::string event = "data: hello\n\n";
  18971. sink.write(event.data(), event.size());
  18972. }
  18973. return false; // Close connection to trigger reconnect
  18974. });
  18975. });
  18976. Client client("localhost", get_port());
  18977. Headers headers = {{"Authorization", "Bearer old-token"}};
  18978. sse::SSEClient sse(client, "/auth-check", headers);
  18979. // Update headers on each successful connection
  18980. sse.on_open(
  18981. [&sse]() { sse.set_headers({{"Authorization", "Bearer new-token"}}); });
  18982. sse.set_reconnect_interval(100);
  18983. sse.set_max_reconnect_attempts(3);
  18984. sse.start_async();
  18985. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  18986. sse.stop();
  18987. std::lock_guard<std::mutex> lock(token_mutex);
  18988. ASSERT_GE(received_tokens.size(), 2u);
  18989. // First connection uses original header
  18990. EXPECT_EQ(received_tokens[0], "Bearer old-token");
  18991. // Second connection uses updated header from set_headers
  18992. EXPECT_EQ(received_tokens[1], "Bearer new-token");
  18993. }
  18994. // Test: 401 allows reconnection (so on_error can refresh headers)
  18995. TEST_F(SSEIntegrationTest, ReconnectOn401WithHeaderRefresh) {
  18996. std::atomic<int> connection_count{0};
  18997. // Endpoint: returns 401 on first attempt, 200 on second
  18998. server_->Get("/auth-retry", [&](const Request &req, Response &res) {
  18999. int conn = connection_count.fetch_add(1);
  19000. if (conn == 0 || req.get_header_value("Authorization") != "Bearer valid") {
  19001. res.status = StatusCode::Unauthorized_401;
  19002. res.set_content("Unauthorized", "text/plain");
  19003. return;
  19004. }
  19005. res.set_chunked_content_provider(
  19006. "text/event-stream", [](size_t offset, DataSink &sink) {
  19007. if (offset == 0) {
  19008. std::string event = "data: authenticated\n\n";
  19009. sink.write(event.data(), event.size());
  19010. }
  19011. return false;
  19012. });
  19013. });
  19014. Client client("localhost", get_port());
  19015. Headers headers = {{"Authorization", "Bearer expired"}};
  19016. sse::SSEClient sse(client, "/auth-retry", headers);
  19017. std::atomic<bool> message_received{false};
  19018. // Refresh token on error
  19019. sse.on_error(
  19020. [&sse](Error) { sse.set_headers({{"Authorization", "Bearer valid"}}); });
  19021. sse.on_message([&](const sse::SSEMessage &msg) {
  19022. if (msg.data == "authenticated") { message_received.store(true); }
  19023. });
  19024. sse.set_reconnect_interval(100);
  19025. sse.set_max_reconnect_attempts(3);
  19026. sse.start_async();
  19027. std::this_thread::sleep_for(std::chrono::milliseconds(800));
  19028. sse.stop();
  19029. // Should have reconnected after 401 and succeeded with new token
  19030. EXPECT_GE(connection_count.load(), 2);
  19031. EXPECT_TRUE(message_received.load());
  19032. }
  19033. TEST(Issue2318Test, EmptyHostString) {
  19034. {
  19035. httplib::Client cli_empty("", PORT);
  19036. auto res = cli_empty.Get("/");
  19037. ASSERT_FALSE(res);
  19038. EXPECT_EQ(httplib::Error::Connection, res.error());
  19039. }
  19040. {
  19041. httplib::Client cli(" ", PORT);
  19042. auto res = cli.Get("/");
  19043. ASSERT_FALSE(res);
  19044. EXPECT_EQ(httplib::Error::Connection, res.error());
  19045. }
  19046. }
  19047. #ifdef CPPHTTPLIB_ZLIB_SUPPORT
  19048. TEST(ZipBombProtectionTest, DecompressedSizeExceedsLimit) {
  19049. Server svr;
  19050. // Set a small payload limit (1KB)
  19051. svr.set_payload_max_length(1024);
  19052. svr.Post("/test", [&](const Request &req, Response &res) {
  19053. res.set_content("Body size: " + std::to_string(req.body.size()),
  19054. "text/plain");
  19055. });
  19056. auto listen_thread = std::thread([&]() { svr.listen(HOST, PORT); });
  19057. auto se = detail::scope_exit([&] {
  19058. svr.stop();
  19059. listen_thread.join();
  19060. });
  19061. svr.wait_until_ready();
  19062. // Create data that compresses well but exceeds limit when decompressed
  19063. // 8KB of repeated null bytes compresses to a very small size
  19064. std::string original_data(8 * 1024, '\0');
  19065. // Compress the data using gzip
  19066. std::string compressed_data;
  19067. detail::gzip_compressor compressor;
  19068. compressor.compress(original_data.data(), original_data.size(), true,
  19069. [&](const char *data, size_t size) {
  19070. compressed_data.append(data, size);
  19071. return true;
  19072. });
  19073. // Verify compression worked (compressed should be much smaller)
  19074. ASSERT_LT(compressed_data.size(), original_data.size());
  19075. ASSERT_LT(compressed_data.size(), 1024u); // Compressed fits in limit
  19076. // Send compressed data with Content-Encoding: gzip
  19077. Client cli(HOST, PORT);
  19078. Headers headers = {{"Content-Encoding", "gzip"}};
  19079. auto res =
  19080. cli.Post("/test", headers, compressed_data, "application/octet-stream");
  19081. // Server should reject because decompressed size (8KB) exceeds limit (1KB)
  19082. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19083. EXPECT_EQ(StatusCode::PayloadTooLarge_413, res->status);
  19084. }
  19085. #endif
  19086. // ============================================================================
  19087. // OpenSSL-Specific Tests
  19088. // ============================================================================
  19089. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  19090. X509 *readCertificate(const std::string &strFileName) {
  19091. std::ifstream inStream(strFileName);
  19092. std::string strCertPEM((std::istreambuf_iterator<char>(inStream)),
  19093. std::istreambuf_iterator<char>());
  19094. if (strCertPEM.empty()) return (nullptr);
  19095. BIO *pbCert = BIO_new(BIO_s_mem());
  19096. BIO_write(pbCert, strCertPEM.c_str(), (int)strCertPEM.size());
  19097. X509 *pCert = PEM_read_bio_X509(pbCert, NULL, 0, NULL);
  19098. BIO_free(pbCert);
  19099. return (pCert);
  19100. }
  19101. EVP_PKEY *readPrivateKey(const std::string &strFileName) {
  19102. std::ifstream inStream(strFileName);
  19103. std::string strPrivateKeyPEM((std::istreambuf_iterator<char>(inStream)),
  19104. std::istreambuf_iterator<char>());
  19105. if (strPrivateKeyPEM.empty()) return (nullptr);
  19106. BIO *pbPrivKey = BIO_new(BIO_s_mem());
  19107. BIO_write(pbPrivKey, strPrivateKeyPEM.c_str(), (int)strPrivateKeyPEM.size());
  19108. EVP_PKEY *pPrivateKey = PEM_read_bio_PrivateKey(pbPrivKey, NULL, NULL, NULL);
  19109. BIO_free(pbPrivKey);
  19110. return (pPrivateKey);
  19111. }
  19112. TEST(BindServerTest, UpdateCerts) {
  19113. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19114. int port = svr.bind_to_any_port("0.0.0.0");
  19115. ASSERT_TRUE(svr.is_valid());
  19116. ASSERT_TRUE(port > 0);
  19117. X509 *cert = readCertificate(SERVER_CERT_FILE);
  19118. X509 *ca_cert = readCertificate(CLIENT_CA_CERT_FILE);
  19119. EVP_PKEY *key = readPrivateKey(SERVER_PRIVATE_KEY_FILE);
  19120. ASSERT_TRUE(cert != nullptr);
  19121. ASSERT_TRUE(ca_cert != nullptr);
  19122. ASSERT_TRUE(key != nullptr);
  19123. X509_STORE *cert_store = X509_STORE_new();
  19124. X509_STORE_add_cert(cert_store, ca_cert);
  19125. // svr.update_certs(cert, key, cert_store); // deprecated
  19126. svr.update_certs_pem(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE,
  19127. CLIENT_CA_CERT_FILE);
  19128. ASSERT_TRUE(svr.is_valid());
  19129. svr.stop();
  19130. X509_STORE_free(cert_store);
  19131. X509_free(cert);
  19132. X509_free(ca_cert);
  19133. EVP_PKEY_free(key);
  19134. }
  19135. // Test that update_certs() updates client CA list correctly
  19136. TEST(SSLClientServerTest, UpdateCertsSetsClientCAList) {
  19137. // Start with file-based constructor
  19138. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19139. ASSERT_TRUE(svr.is_valid());
  19140. // Initially no client CA list should be set
  19141. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19142. ASSERT_TRUE(ssl_ctx != nullptr);
  19143. STACK_OF(X509_NAME) *ca_list_before = SSL_CTX_get_client_CA_list(ssl_ctx);
  19144. int count_before = ca_list_before ? sk_X509_NAME_num(ca_list_before) : 0;
  19145. EXPECT_EQ(0, count_before);
  19146. // Now update with client CA (PEM string)
  19147. std::string cert_pem, key_pem, ca_pem;
  19148. read_file(SERVER_CERT_FILE, cert_pem);
  19149. read_file(SERVER_PRIVATE_KEY_FILE, key_pem);
  19150. read_file(CLIENT_CA_CERT_FILE, ca_pem);
  19151. svr.update_certs_pem(cert_pem.c_str(), key_pem.c_str(), ca_pem.c_str());
  19152. ASSERT_TRUE(svr.is_valid());
  19153. // Now client CA list should be set
  19154. STACK_OF(X509_NAME) *ca_list_after = SSL_CTX_get_client_CA_list(ssl_ctx);
  19155. ASSERT_TRUE(ca_list_after != nullptr);
  19156. EXPECT_GT(sk_X509_NAME_num(ca_list_after), 0);
  19157. }
  19158. TEST(SSLClientServerTest, FilePathConstructorSetsClientCAList) {
  19159. // Test that the file-path SSLServer constructor properly sets the client CA
  19160. // list that is sent to clients during the TLS handshake (CertificateRequest)
  19161. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  19162. ASSERT_TRUE(svr.is_valid());
  19163. auto ssl_ctx = static_cast<SSL_CTX *>(svr.tls_context());
  19164. ASSERT_TRUE(ssl_ctx != nullptr);
  19165. STACK_OF(X509_NAME) *ca_list = SSL_CTX_get_client_CA_list(ssl_ctx);
  19166. ASSERT_TRUE(ca_list != nullptr);
  19167. EXPECT_GT(sk_X509_NAME_num(ca_list), 0);
  19168. }
  19169. #endif
  19170. // ============================================================================
  19171. // MbedTLS-Specific Tests
  19172. // ============================================================================
  19173. #ifdef CPPHTTPLIB_MBEDTLS_SUPPORT
  19174. TEST(SSLClientServerTest, CustomizeServerSSLCtxMbedTLS) {
  19175. using namespace httplib::tls;
  19176. // Track if callback was invoked
  19177. bool callback_invoked = false;
  19178. // The callback receives void* ctx which is actually MbedTlsContext*
  19179. // We can access the mbedtls_ssl_config via the context
  19180. auto setup_callback = [&callback_invoked](void *ctx) {
  19181. callback_invoked = true;
  19182. // Cast to MbedTlsContext* to access the ssl config
  19183. auto *mbedtls_ctx = static_cast<httplib::tls::impl::MbedTlsContext *>(ctx);
  19184. mbedtls_ssl_config *conf = &mbedtls_ctx->conf;
  19185. // Use static variables to hold certificate data (simplified for test)
  19186. static mbedtls_x509_crt own_cert;
  19187. static mbedtls_pk_context own_key;
  19188. static mbedtls_x509_crt ca_chain;
  19189. static bool initialized = false;
  19190. if (!initialized) {
  19191. mbedtls_x509_crt_init(&own_cert);
  19192. mbedtls_pk_init(&own_key);
  19193. mbedtls_x509_crt_init(&ca_chain);
  19194. // Load server certificate
  19195. if (mbedtls_x509_crt_parse_file(&own_cert, SERVER_CERT_FILE) != 0) {
  19196. return false;
  19197. }
  19198. // Load server private key.
  19199. // Mbed TLS 3.x takes an RNG callback here; 2.x and 4.x do not.
  19200. if (mbedtls_pk_parse_keyfile(&own_key, SERVER_PRIVATE_KEY_FILE, nullptr
  19201. #if MBEDTLS_VERSION_MAJOR == 3
  19202. ,
  19203. mbedtls_ctr_drbg_random, nullptr
  19204. #endif
  19205. ) != 0) {
  19206. return false;
  19207. }
  19208. // Load CA chain for client verification
  19209. if (mbedtls_x509_crt_parse_file(&ca_chain, CLIENT_CA_CERT_FILE) != 0) {
  19210. return false;
  19211. }
  19212. initialized = true;
  19213. }
  19214. // Configure the SSL config
  19215. mbedtls_ssl_conf_own_cert(conf, &own_cert, &own_key);
  19216. mbedtls_ssl_conf_ca_chain(conf, &ca_chain, nullptr);
  19217. mbedtls_ssl_conf_authmode(conf, MBEDTLS_SSL_VERIFY_REQUIRED);
  19218. // Set minimum TLS version using mbedTLS native API
  19219. #if MBEDTLS_VERSION_MAJOR >= 3
  19220. mbedtls_ssl_conf_min_tls_version(conf, MBEDTLS_SSL_VERSION_TLS1_2);
  19221. #else
  19222. mbedtls_ssl_conf_min_version(conf, MBEDTLS_SSL_MAJOR_VERSION_3,
  19223. MBEDTLS_SSL_MINOR_VERSION_3);
  19224. #endif
  19225. return true;
  19226. };
  19227. SSLServer svr(setup_callback);
  19228. ASSERT_TRUE(svr.is_valid());
  19229. ASSERT_TRUE(callback_invoked);
  19230. svr.Get("/test", [&](const Request &req, Response &res) {
  19231. res.set_content("test", "text/plain");
  19232. auto cert = req.peer_cert();
  19233. ASSERT_TRUE(static_cast<bool>(cert));
  19234. auto common_name = cert.subject_cn();
  19235. EXPECT_EQ("Common Name", common_name);
  19236. });
  19237. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19238. auto se = detail::scope_exit([&] {
  19239. svr.stop();
  19240. t.join();
  19241. ASSERT_FALSE(svr.is_running());
  19242. });
  19243. svr.wait_until_ready();
  19244. SSLClient cli(HOST, PORT, CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE);
  19245. cli.enable_server_certificate_verification(false);
  19246. cli.set_connection_timeout(30);
  19247. auto res = cli.Get("/test");
  19248. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19249. ASSERT_EQ(StatusCode::OK_200, res->status);
  19250. }
  19251. // Regression test for a use-after-free where ~SSLClient freed the mbedTLS
  19252. // context (owning mbedtls_ssl_config) before shutting down a still-open
  19253. // keep-alive SSL session, which reads through that config in
  19254. // mbedtls_ssl_close_notify.
  19255. TEST(SSLClientServerTest, DestructWithLiveKeepAliveSessionMbedTLS) {
  19256. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  19257. ASSERT_TRUE(svr.is_valid());
  19258. svr.Get("/test", [&](const Request & /*req*/, Response &res) {
  19259. res.set_content("test", "text/plain");
  19260. });
  19261. thread t = thread([&]() { ASSERT_TRUE(svr.listen(HOST, PORT)); });
  19262. auto se = detail::scope_exit([&] {
  19263. svr.stop();
  19264. t.join();
  19265. ASSERT_FALSE(svr.is_running());
  19266. });
  19267. svr.wait_until_ready();
  19268. {
  19269. SSLClient cli(HOST, PORT);
  19270. cli.enable_server_certificate_verification(false);
  19271. cli.set_keep_alive(true);
  19272. auto res = cli.Get("/test");
  19273. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  19274. ASSERT_EQ(StatusCode::OK_200, res->status);
  19275. // cli is destructed here with the keep-alive SSL session still open.
  19276. }
  19277. }
  19278. #endif
  19279. // WebSocket Tests
  19280. TEST(WebSocketTest, RSVBitsMustBeZero) {
  19281. // RFC 6455 Section 5.2: RSV1, RSV2, RSV3 MUST be 0 unless an extension
  19282. // defining the meaning of these bits has been negotiated.
  19283. auto make_frame = [](uint8_t first_byte) {
  19284. std::string frame;
  19285. frame += static_cast<char>(first_byte); // FIN + RSV + opcode
  19286. frame += static_cast<char>(0x05); // mask=0, payload_len=5
  19287. frame += "Hello";
  19288. return frame;
  19289. };
  19290. // RSV1 set (0x40)
  19291. {
  19292. detail::BufferStream strm;
  19293. strm.write(make_frame(0x81 | 0x40).data(), 8); // FIN + RSV1 + Text
  19294. ws::Opcode opcode;
  19295. std::string payload;
  19296. bool fin;
  19297. EXPECT_EQ(
  19298. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19299. ws::impl::FrameRead::Fail);
  19300. }
  19301. // RSV2 set (0x20)
  19302. {
  19303. detail::BufferStream strm;
  19304. strm.write(make_frame(0x81 | 0x20).data(), 8); // FIN + RSV2 + Text
  19305. ws::Opcode opcode;
  19306. std::string payload;
  19307. bool fin;
  19308. EXPECT_EQ(
  19309. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19310. ws::impl::FrameRead::Fail);
  19311. }
  19312. // RSV3 set (0x10)
  19313. {
  19314. detail::BufferStream strm;
  19315. strm.write(make_frame(0x81 | 0x10).data(), 8); // FIN + RSV3 + Text
  19316. ws::Opcode opcode;
  19317. std::string payload;
  19318. bool fin;
  19319. EXPECT_EQ(
  19320. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19321. ws::impl::FrameRead::Fail);
  19322. }
  19323. // No RSV bits set - should succeed
  19324. {
  19325. detail::BufferStream strm;
  19326. strm.write(make_frame(0x81).data(), 8); // FIN + Text, no RSV
  19327. ws::Opcode opcode;
  19328. std::string payload;
  19329. bool fin;
  19330. EXPECT_EQ(
  19331. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19332. ws::impl::FrameRead::Ok);
  19333. EXPECT_EQ(ws::Opcode::Text, opcode);
  19334. EXPECT_EQ("Hello", payload);
  19335. EXPECT_TRUE(fin);
  19336. }
  19337. }
  19338. TEST(WebSocketTest, ControlFrameValidation) {
  19339. // RFC 6455 Section 5.5: control frames MUST have FIN=1 and
  19340. // payload length <= 125.
  19341. // Ping with FIN=0 - must be rejected
  19342. {
  19343. detail::BufferStream strm;
  19344. std::string frame;
  19345. frame += static_cast<char>(0x09); // FIN=0, opcode=Ping
  19346. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19347. strm.write(frame.data(), frame.size());
  19348. ws::Opcode opcode;
  19349. std::string payload;
  19350. bool fin;
  19351. EXPECT_EQ(
  19352. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19353. ws::impl::FrameRead::Fail);
  19354. }
  19355. // Close with FIN=0 - must be rejected
  19356. {
  19357. detail::BufferStream strm;
  19358. std::string frame;
  19359. frame += static_cast<char>(0x08); // FIN=0, opcode=Close
  19360. frame += static_cast<char>(0x00); // mask=0, payload_len=0
  19361. strm.write(frame.data(), frame.size());
  19362. ws::Opcode opcode;
  19363. std::string payload;
  19364. bool fin;
  19365. EXPECT_EQ(
  19366. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19367. ws::impl::FrameRead::Fail);
  19368. }
  19369. // Ping with payload_len=126 (extended length) - must be rejected
  19370. {
  19371. detail::BufferStream strm;
  19372. std::string frame;
  19373. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19374. frame += static_cast<char>(126); // payload_len=126 (>125)
  19375. frame += static_cast<char>(0x00); // extended length high byte
  19376. frame += static_cast<char>(126); // extended length low byte
  19377. frame += std::string(126, 'x');
  19378. strm.write(frame.data(), frame.size());
  19379. ws::Opcode opcode;
  19380. std::string payload;
  19381. bool fin;
  19382. EXPECT_EQ(
  19383. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19384. ws::impl::FrameRead::Fail);
  19385. }
  19386. // Ping with FIN=1 and payload_len=125 - should succeed
  19387. {
  19388. detail::BufferStream strm;
  19389. std::string frame;
  19390. frame += static_cast<char>(0x89); // FIN=1, opcode=Ping
  19391. frame += static_cast<char>(125); // payload_len=125
  19392. frame += std::string(125, 'x');
  19393. strm.write(frame.data(), frame.size());
  19394. ws::Opcode opcode;
  19395. std::string payload;
  19396. bool fin;
  19397. EXPECT_EQ(
  19398. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19399. ws::impl::FrameRead::Ok);
  19400. EXPECT_EQ(ws::Opcode::Ping, opcode);
  19401. EXPECT_EQ(125u, payload.size());
  19402. EXPECT_TRUE(fin);
  19403. }
  19404. }
  19405. TEST(WebSocketTest, PayloadLength64BitMSBMustBeZero) {
  19406. // RFC 6455 Section 5.2: the most significant bit of a 64-bit payload
  19407. // length MUST be 0.
  19408. // MSB set - must be rejected
  19409. {
  19410. detail::BufferStream strm;
  19411. std::string frame;
  19412. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19413. frame += static_cast<char>(127); // 64-bit extended length
  19414. frame += static_cast<char>(0x80); // MSB set (invalid)
  19415. frame += std::string(7, '\0'); // remaining 7 bytes of length
  19416. strm.write(frame.data(), frame.size());
  19417. ws::Opcode opcode;
  19418. std::string payload;
  19419. bool fin;
  19420. EXPECT_EQ(
  19421. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19422. ws::impl::FrameRead::Fail);
  19423. }
  19424. // MSB clear - should pass length parsing (will be rejected by max_len,
  19425. // but that's a different check; use a small length to verify)
  19426. {
  19427. detail::BufferStream strm;
  19428. std::string frame;
  19429. frame += static_cast<char>(0x81); // FIN=1, opcode=Text
  19430. frame += static_cast<char>(127); // 64-bit extended length
  19431. frame += std::string(7, '\0'); // high bytes = 0
  19432. frame += static_cast<char>(0x03); // length = 3
  19433. frame += "abc";
  19434. strm.write(frame.data(), frame.size());
  19435. ws::Opcode opcode;
  19436. std::string payload;
  19437. bool fin;
  19438. EXPECT_EQ(
  19439. ws::impl::read_websocket_frame(strm, opcode, payload, fin, false, 1024),
  19440. ws::impl::FrameRead::Ok);
  19441. EXPECT_EQ(ws::Opcode::Text, opcode);
  19442. EXPECT_EQ("abc", payload);
  19443. }
  19444. }
  19445. TEST(WebSocketTest, InvalidUTF8TextFrame) {
  19446. // RFC 6455 Section 5.6: text frames must contain valid UTF-8.
  19447. // Valid UTF-8
  19448. EXPECT_TRUE(ws::impl::is_valid_utf8("Hello"));
  19449. EXPECT_TRUE(ws::impl::is_valid_utf8("\xC3\xA9")); // é (U+00E9)
  19450. EXPECT_TRUE(ws::impl::is_valid_utf8("\xE3\x81\x82")); // あ (U+3042)
  19451. EXPECT_TRUE(ws::impl::is_valid_utf8("\xF0\x9F\x98\x80")); // 😀 (U+1F600)
  19452. EXPECT_TRUE(ws::impl::is_valid_utf8(""));
  19453. // Invalid UTF-8
  19454. EXPECT_FALSE(ws::impl::is_valid_utf8("\x80")); // Invalid start byte
  19455. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC3\x28")); // Bad continuation
  19456. EXPECT_FALSE(ws::impl::is_valid_utf8("\xC0\xAF")); // Overlong encoding
  19457. EXPECT_FALSE(
  19458. ws::impl::is_valid_utf8("\xED\xA0\x80")); // Surrogate half U+D800
  19459. EXPECT_FALSE(ws::impl::is_valid_utf8("\xF4\x90\x80\x80")); // Beyond U+10FFFF
  19460. }
  19461. TEST(WebSocketTest, ConnectAndDisconnect) {
  19462. Server svr;
  19463. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19464. std::string msg;
  19465. while (ws.read(msg)) {}
  19466. });
  19467. auto port = svr.bind_to_any_port(HOST);
  19468. std::thread t([&]() { svr.listen_after_bind(); });
  19469. svr.wait_until_ready();
  19470. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19471. auto res = client.connect();
  19472. ASSERT_TRUE(res);
  19473. EXPECT_EQ(Error::Success, res.error());
  19474. EXPECT_EQ(StatusCode::SwitchingProtocol_101, res.status());
  19475. EXPECT_TRUE(res.has_header("Sec-WebSocket-Accept"));
  19476. EXPECT_TRUE(client.is_open());
  19477. client.close();
  19478. EXPECT_FALSE(client.is_open());
  19479. svr.stop();
  19480. t.join();
  19481. }
  19482. TEST(WebSocketTest, ValidURL) {
  19483. ws::WebSocketClient ws1("ws://localhost:8080/path");
  19484. EXPECT_TRUE(ws1.is_valid());
  19485. ws::WebSocketClient ws2("ws://example.com/path");
  19486. EXPECT_TRUE(ws2.is_valid());
  19487. ws::WebSocketClient ws3("ws://example.com:9090/path/to/endpoint");
  19488. EXPECT_TRUE(ws3.is_valid());
  19489. #ifdef CPPHTTPLIB_SSL_ENABLED
  19490. ws::WebSocketClient wss1("wss://example.com/path");
  19491. EXPECT_TRUE(wss1.is_valid());
  19492. ws::WebSocketClient wss2("wss://example.com:443/path");
  19493. EXPECT_TRUE(wss2.is_valid());
  19494. #endif
  19495. }
  19496. TEST(WebSocketTest, InvalidURL) {
  19497. // No scheme
  19498. ws::WebSocketClient ws1("localhost:8080/path");
  19499. EXPECT_FALSE(ws1.is_valid());
  19500. // No path
  19501. ws::WebSocketClient ws2("ws://localhost:8080");
  19502. EXPECT_FALSE(ws2.is_valid());
  19503. // Empty string
  19504. ws::WebSocketClient ws3("");
  19505. EXPECT_FALSE(ws3.is_valid());
  19506. // Missing host
  19507. ws::WebSocketClient ws4("ws://:8080/path");
  19508. EXPECT_FALSE(ws4.is_valid());
  19509. // Port number overflow — should not crash
  19510. ws::WebSocketClient ws5("ws://localhost:99999999999999999999/path");
  19511. EXPECT_FALSE(ws5.is_valid());
  19512. // Port out of range
  19513. ws::WebSocketClient ws6("ws://localhost:99999/path");
  19514. EXPECT_FALSE(ws6.is_valid());
  19515. }
  19516. TEST(WebSocketTest, UnsupportedScheme) {
  19517. #ifdef CPPHTTPLIB_NO_EXCEPTIONS
  19518. ws::WebSocketClient ws1("http://localhost:8080/path");
  19519. EXPECT_FALSE(ws1.is_valid());
  19520. ws::WebSocketClient ws2("https://localhost:8080/path");
  19521. EXPECT_FALSE(ws2.is_valid());
  19522. ws::WebSocketClient ws3("ftp://localhost:8080/path");
  19523. EXPECT_FALSE(ws3.is_valid());
  19524. #else
  19525. EXPECT_THROW(ws::WebSocketClient("http://localhost:8080/path"),
  19526. std::invalid_argument);
  19527. EXPECT_THROW(ws::WebSocketClient("ftp://localhost:8080/path"),
  19528. std::invalid_argument);
  19529. #endif
  19530. }
  19531. TEST(WebSocketTest, ConnectWhenInvalid) {
  19532. ws::WebSocketClient ws("not a valid url");
  19533. EXPECT_FALSE(ws.is_valid());
  19534. auto res = ws.connect();
  19535. EXPECT_FALSE(res);
  19536. EXPECT_EQ(Error::Connection, res.error());
  19537. EXPECT_EQ(-1, res.status());
  19538. }
  19539. TEST(WebSocketTest, ConnectRefusedReportsError) {
  19540. // Grab a port that is free, then close it again so nothing listens there
  19541. Server svr;
  19542. auto port = svr.bind_to_any_port(HOST);
  19543. svr.stop();
  19544. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19545. auto res = client.connect();
  19546. ASSERT_FALSE(res);
  19547. EXPECT_EQ(Error::Connection, res.error());
  19548. EXPECT_EQ(-1, res.status());
  19549. }
  19550. TEST(WebSocketTest, DefaultPort) {
  19551. ws::WebSocketClient ws1("ws://example.com/path");
  19552. EXPECT_TRUE(ws1.is_valid());
  19553. // ws:// defaults to port 80 (verified by successful parse)
  19554. #ifdef CPPHTTPLIB_SSL_ENABLED
  19555. ws::WebSocketClient ws2("wss://example.com/path");
  19556. EXPECT_TRUE(ws2.is_valid());
  19557. // wss:// defaults to port 443 (verified by successful parse)
  19558. #endif
  19559. }
  19560. TEST(WebSocketTest, IPv6LiteralAddress) {
  19561. ws::WebSocketClient ws1("ws://[::1]:8080/path");
  19562. EXPECT_TRUE(ws1.is_valid());
  19563. ws::WebSocketClient ws2("ws://[fe80::1]:3000/ws");
  19564. EXPECT_TRUE(ws2.is_valid());
  19565. }
  19566. TEST(WebSocketTest, ComplexPath) {
  19567. ws::WebSocketClient ws1("ws://localhost:8080/path/to/endpoint");
  19568. EXPECT_TRUE(ws1.is_valid());
  19569. ws::WebSocketClient ws2("ws://localhost:8080/");
  19570. EXPECT_TRUE(ws2.is_valid());
  19571. }
  19572. TEST(WebSocketTest, SpecifyServerIPAddress_AnotherHostname) {
  19573. Server svr;
  19574. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19575. std::string msg;
  19576. while (ws.read(msg)) {}
  19577. });
  19578. auto port = svr.bind_to_any_port(HOST);
  19579. std::thread t([&]() { svr.listen_after_bind(); });
  19580. svr.wait_until_ready();
  19581. auto another_host = "example.com";
  19582. auto wrong_ip = "192.0.2.1";
  19583. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19584. client.set_hostname_addr_map({{another_host, wrong_ip}});
  19585. ASSERT_TRUE(client.connect());
  19586. EXPECT_TRUE(client.is_open());
  19587. client.close();
  19588. svr.stop();
  19589. t.join();
  19590. }
  19591. TEST(WebSocketTest, SpecifyServerIPAddress_RealHostname) {
  19592. Server svr;
  19593. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  19594. std::string msg;
  19595. while (ws.read(msg)) {}
  19596. });
  19597. auto port = svr.bind_to_any_port(HOST);
  19598. std::thread t([&]() { svr.listen_after_bind(); });
  19599. svr.wait_until_ready();
  19600. auto wrong_ip = "192.0.2.1";
  19601. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  19602. client.set_hostname_addr_map({{"localhost", wrong_ip}});
  19603. client.set_connection_timeout(1);
  19604. client.set_read_timeout(1);
  19605. client.set_write_timeout(1);
  19606. EXPECT_FALSE(client.connect());
  19607. EXPECT_FALSE(client.is_open());
  19608. svr.stop();
  19609. t.join();
  19610. }
  19611. TEST(WebSocketTest, SpecifyServerIPAddress_HostnameAsAddrMapValue) {
  19612. // A mapped value that is not an IP literal must be resolved. HOST resolves
  19613. // from the hosts file, so this test needs no external DNS. "target.invalid"
  19614. // (RFC 6761) is only a map key and the Host header value.
  19615. auto host = "target.invalid";
  19616. Server svr;
  19617. std::string received_host;
  19618. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  19619. received_host = req.get_header_value("Host");
  19620. std::string msg;
  19621. while (ws.read(msg)) {}
  19622. });
  19623. auto port = svr.bind_to_any_port(HOST);
  19624. std::thread t([&]() { svr.listen_after_bind(); });
  19625. // ASSERT_* below returns from the test body, which would leave t joinable
  19626. // and make ~thread call std::terminate.
  19627. auto se = detail::scope_exit([&] {
  19628. svr.stop();
  19629. if (t.joinable()) { t.join(); }
  19630. });
  19631. svr.wait_until_ready();
  19632. ws::WebSocketClient client("ws://" + std::string(host) + ":" +
  19633. std::to_string(port) + "/ws");
  19634. client.set_hostname_addr_map({{host, HOST}});
  19635. ASSERT_TRUE(client.connect());
  19636. EXPECT_TRUE(client.is_open());
  19637. client.close();
  19638. svr.stop();
  19639. t.join();
  19640. // The mapping only redirects the connection; the identity stays host_.
  19641. EXPECT_EQ(std::string(host) + ":" + std::to_string(port), received_host);
  19642. }
  19643. class WebSocketIntegrationTest : public ::testing::Test {
  19644. protected:
  19645. void SetUp() override {
  19646. server_ = httplib::detail::make_unique<Server>();
  19647. setup_server();
  19648. start_server();
  19649. }
  19650. void TearDown() override {
  19651. server_->stop();
  19652. if (server_thread_.joinable()) { server_thread_.join(); }
  19653. }
  19654. void setup_server() {
  19655. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  19656. std::string msg;
  19657. ws::ReadResult ret;
  19658. while ((ret = ws.read(msg))) {
  19659. if (ret == ws::Binary) {
  19660. ws.send(msg.data(), msg.size());
  19661. } else {
  19662. ws.send(msg);
  19663. }
  19664. }
  19665. });
  19666. server_->WebSocket("/ws-echo-string",
  19667. [](const Request &, ws::WebSocket &ws) {
  19668. std::string msg;
  19669. while (ws.read(msg)) {
  19670. ws.send("echo: " + msg);
  19671. }
  19672. });
  19673. server_->WebSocket(
  19674. "/ws-request-info", [](const Request &req, ws::WebSocket &ws) {
  19675. // Echo back request metadata
  19676. ws.send("path:" + req.path);
  19677. ws.send("header:" + req.get_header_value("X-Test-Header"));
  19678. std::string msg;
  19679. while (ws.read(msg)) {}
  19680. });
  19681. server_->WebSocket("/ws-close", [](const Request &, ws::WebSocket &ws) {
  19682. std::string msg;
  19683. ws.read(msg); // wait for a message
  19684. ws.close();
  19685. });
  19686. server_->WebSocket("/ws-close-status",
  19687. [](const Request &, ws::WebSocket &ws) {
  19688. std::string msg;
  19689. ws.read(msg); // wait for a message
  19690. ws.close(ws::CloseStatus::GoingAway, "shutting down");
  19691. });
  19692. server_->WebSocket(
  19693. "/ws-subprotocol",
  19694. [](const Request &, ws::WebSocket &ws) {
  19695. std::string msg;
  19696. while (ws.read(msg)) {
  19697. ws.send(msg);
  19698. }
  19699. },
  19700. [](const std::vector<std::string> &protocols) -> std::string {
  19701. for (const auto &p : protocols) {
  19702. if (p == "graphql-ws") { return p; }
  19703. }
  19704. return "";
  19705. });
  19706. }
  19707. void start_server() {
  19708. port_ = server_->bind_to_any_port(HOST);
  19709. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  19710. server_->wait_until_ready();
  19711. }
  19712. std::unique_ptr<Server> server_;
  19713. std::thread server_thread_;
  19714. int port_ = 0;
  19715. };
  19716. TEST_F(WebSocketIntegrationTest, TextEcho) {
  19717. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19718. "/ws-echo");
  19719. ASSERT_TRUE(client.connect());
  19720. ASSERT_TRUE(client.is_open());
  19721. ASSERT_TRUE(client.send("Hello WebSocket"));
  19722. std::string msg;
  19723. EXPECT_EQ(ws::Text, client.read(msg));
  19724. EXPECT_EQ("Hello WebSocket", msg);
  19725. client.close();
  19726. }
  19727. TEST_F(WebSocketIntegrationTest, BinaryEcho) {
  19728. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19729. "/ws-echo");
  19730. ASSERT_TRUE(client.connect());
  19731. std::string binary_data = {'\x00', '\x01', '\x02', '\xFF', '\xFE'};
  19732. ASSERT_TRUE(client.send(binary_data.data(), binary_data.size()));
  19733. std::string msg;
  19734. EXPECT_EQ(ws::Binary, client.read(msg));
  19735. EXPECT_EQ(binary_data, msg);
  19736. client.close();
  19737. }
  19738. TEST_F(WebSocketIntegrationTest, MultipleMessages) {
  19739. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19740. "/ws-echo");
  19741. ASSERT_TRUE(client.connect());
  19742. for (int i = 0; i < 10; i++) {
  19743. auto text = "message " + std::to_string(i);
  19744. ASSERT_TRUE(client.send(text));
  19745. std::string msg;
  19746. ASSERT_TRUE(client.read(msg));
  19747. EXPECT_EQ(text, msg);
  19748. }
  19749. client.close();
  19750. }
  19751. TEST_F(WebSocketIntegrationTest, CloseHandshake) {
  19752. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19753. "/ws-close");
  19754. ASSERT_TRUE(client.connect());
  19755. // Send a message to trigger the server to close
  19756. ASSERT_TRUE(client.send("trigger close"));
  19757. // The server will close, so read should return false
  19758. std::string msg;
  19759. EXPECT_FALSE(client.read(msg));
  19760. EXPECT_FALSE(client.is_open());
  19761. }
  19762. TEST_F(WebSocketIntegrationTest, LargeMessage) {
  19763. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19764. "/ws-echo");
  19765. ASSERT_TRUE(client.connect());
  19766. // 128KB message
  19767. std::string large_data(128 * 1024, 'X');
  19768. ASSERT_TRUE(client.send(large_data));
  19769. std::string msg;
  19770. ASSERT_TRUE(client.read(msg));
  19771. EXPECT_EQ(large_data, msg);
  19772. client.close();
  19773. }
  19774. TEST_F(WebSocketIntegrationTest, ConcurrentSend) {
  19775. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19776. "/ws-echo");
  19777. ASSERT_TRUE(client.connect());
  19778. const int num_threads = 4;
  19779. std::vector<std::thread> threads;
  19780. std::atomic<int> send_count{0};
  19781. for (int t = 0; t < num_threads; t++) {
  19782. threads.emplace_back([&client, &send_count, t]() {
  19783. for (int i = 0; i < 5; i++) {
  19784. auto text = "thread" + std::to_string(t) + "_msg" + std::to_string(i);
  19785. if (client.send(text)) { send_count++; }
  19786. }
  19787. });
  19788. }
  19789. for (auto &th : threads) {
  19790. th.join();
  19791. }
  19792. int received = 0;
  19793. std::string msg;
  19794. while (received < send_count.load()) {
  19795. if (!client.read(msg)) { break; }
  19796. received++;
  19797. }
  19798. EXPECT_EQ(send_count.load(), received);
  19799. client.close();
  19800. }
  19801. TEST_F(WebSocketIntegrationTest, ReadString) {
  19802. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19803. "/ws-echo-string");
  19804. ASSERT_TRUE(client.connect());
  19805. ASSERT_TRUE(client.send("hello"));
  19806. std::string msg;
  19807. ASSERT_TRUE(client.read(msg));
  19808. EXPECT_EQ("echo: hello", msg);
  19809. ASSERT_TRUE(client.send("world"));
  19810. ASSERT_TRUE(client.read(msg));
  19811. EXPECT_EQ("echo: world", msg);
  19812. client.close();
  19813. }
  19814. TEST_F(WebSocketIntegrationTest, RequestAccess) {
  19815. Headers headers = {{"X-Test-Header", "test-value"}};
  19816. ws::WebSocketClient client(
  19817. "ws://localhost:" + std::to_string(port_) + "/ws-request-info", headers);
  19818. ASSERT_TRUE(client.connect());
  19819. std::string msg;
  19820. ASSERT_TRUE(client.read(msg));
  19821. EXPECT_EQ("path:/ws-request-info", msg);
  19822. ASSERT_TRUE(client.read(msg));
  19823. EXPECT_EQ("header:test-value", msg);
  19824. client.close();
  19825. }
  19826. TEST_F(WebSocketIntegrationTest, ReadTimeout) {
  19827. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19828. "/ws-echo");
  19829. client.set_read_timeout(1, 0); // 1 second
  19830. ASSERT_TRUE(client.connect());
  19831. // Don't send anything — server echo handler waits for a message, so read()
  19832. // should time out. The connection survives it: nothing was consumed.
  19833. std::string msg;
  19834. EXPECT_EQ(client.read(msg), ws::Timeout);
  19835. EXPECT_TRUE(client.is_open());
  19836. // And it is still usable afterwards.
  19837. EXPECT_TRUE(client.send("after timeout"));
  19838. EXPECT_EQ(client.read(msg), ws::Text);
  19839. EXPECT_EQ(msg, "after timeout");
  19840. }
  19841. TEST_F(WebSocketIntegrationTest, ReadTimeoutLeavesMessageUntouched) {
  19842. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19843. "/ws-echo");
  19844. client.set_read_timeout(1, 0);
  19845. ASSERT_TRUE(client.connect());
  19846. ASSERT_TRUE(client.send("first"));
  19847. std::string msg;
  19848. ASSERT_EQ(client.read(msg), ws::Text);
  19849. ASSERT_EQ(msg, "first");
  19850. // A timeout does not write to msg. This is why `while (ws.read(msg))` must
  19851. // not be used with a read timeout: it would reprocess the previous message.
  19852. EXPECT_EQ(client.read(msg), ws::Timeout);
  19853. EXPECT_EQ(msg, "first");
  19854. }
  19855. TEST_F(WebSocketIntegrationTest, ReadTimeoutSetAfterConnect) {
  19856. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19857. "/ws-echo");
  19858. ASSERT_TRUE(client.connect());
  19859. // Setting it once the connection is open reaches the live stream, not just
  19860. // the seed for the next connect().
  19861. client.set_read_timeout(1, 0);
  19862. std::string msg;
  19863. EXPECT_EQ(client.read(msg), ws::Timeout);
  19864. EXPECT_TRUE(client.is_open());
  19865. }
  19866. TEST_F(WebSocketIntegrationTest, MaxPayloadExceeded) {
  19867. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19868. "/ws-echo");
  19869. client.set_read_timeout(5, 0);
  19870. ASSERT_TRUE(client.connect());
  19871. // Send a message exceeding CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19872. // The server should reject it and close the connection.
  19873. std::string oversized(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH + 1, 'A');
  19874. client.send(oversized);
  19875. // The server's read() should have failed due to payload limit,
  19876. // so our read() should return false (connection closed).
  19877. std::string msg;
  19878. EXPECT_FALSE(client.read(msg));
  19879. }
  19880. TEST_F(WebSocketIntegrationTest, MaxPayloadAtLimit) {
  19881. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19882. "/ws-echo");
  19883. client.set_read_timeout(10, 0);
  19884. ASSERT_TRUE(client.connect());
  19885. // Send a message exactly at CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH (16MB).
  19886. // This should succeed.
  19887. std::string at_limit(CPPHTTPLIB_WEBSOCKET_MAX_PAYLOAD_LENGTH, 'B');
  19888. ASSERT_TRUE(client.send(at_limit));
  19889. std::string msg;
  19890. ASSERT_TRUE(client.read(msg));
  19891. EXPECT_EQ(at_limit.size(), msg.size());
  19892. client.close();
  19893. }
  19894. TEST_F(WebSocketIntegrationTest, ConnectToInvalidPath) {
  19895. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19896. "/nonexistent");
  19897. auto res = client.connect();
  19898. EXPECT_FALSE(res);
  19899. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  19900. EXPECT_EQ(StatusCode::NotFound_404, res.status());
  19901. EXPECT_FALSE(client.is_open());
  19902. }
  19903. TEST_F(WebSocketIntegrationTest, EmptyMessage) {
  19904. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19905. "/ws-echo");
  19906. ASSERT_TRUE(client.connect());
  19907. ASSERT_TRUE(client.send(""));
  19908. std::string msg;
  19909. EXPECT_EQ(ws::Text, client.read(msg));
  19910. EXPECT_EQ("", msg);
  19911. client.close();
  19912. }
  19913. TEST_F(WebSocketIntegrationTest, Reconnect) {
  19914. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19915. "/ws-echo");
  19916. // First connection
  19917. ASSERT_TRUE(client.connect());
  19918. ASSERT_TRUE(client.send("first"));
  19919. std::string msg;
  19920. ASSERT_TRUE(client.read(msg));
  19921. EXPECT_EQ("first", msg);
  19922. client.close();
  19923. EXPECT_FALSE(client.is_open());
  19924. // Reconnect using the same client object
  19925. ASSERT_TRUE(client.connect());
  19926. ASSERT_TRUE(client.is_open());
  19927. ASSERT_TRUE(client.send("second"));
  19928. ASSERT_TRUE(client.read(msg));
  19929. EXPECT_EQ("second", msg);
  19930. client.close();
  19931. }
  19932. TEST_F(WebSocketIntegrationTest, CloseWithStatus) {
  19933. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19934. "/ws-close-status");
  19935. ASSERT_TRUE(client.connect());
  19936. // Trigger the server to close with GoingAway status
  19937. ASSERT_TRUE(client.send("trigger"));
  19938. // read() should return false after receiving the close frame
  19939. std::string msg;
  19940. EXPECT_FALSE(client.read(msg));
  19941. EXPECT_FALSE(client.is_open());
  19942. }
  19943. TEST_F(WebSocketIntegrationTest, ClientCloseWithStatus) {
  19944. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19945. "/ws-echo");
  19946. ASSERT_TRUE(client.connect());
  19947. client.close(ws::CloseStatus::GoingAway, "client leaving");
  19948. EXPECT_FALSE(client.is_open());
  19949. }
  19950. TEST_F(WebSocketIntegrationTest, SubProtocolNegotiation) {
  19951. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, graphql-ws"}};
  19952. ws::WebSocketClient client(
  19953. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19954. ASSERT_TRUE(client.connect());
  19955. // Server should have selected graphql-ws
  19956. EXPECT_EQ("graphql-ws", client.subprotocol());
  19957. client.close();
  19958. }
  19959. TEST_F(WebSocketIntegrationTest, SubProtocolSplitAcrossFieldLines) {
  19960. Headers headers;
  19961. headers.emplace("Sec-WebSocket-Protocol", "mqtt");
  19962. headers.emplace("Sec-WebSocket-Protocol", "graphql-ws");
  19963. ws::WebSocketClient client(
  19964. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19965. ASSERT_TRUE(client.connect());
  19966. // The offer on the second field line counts too, so graphql-ws is selected
  19967. EXPECT_EQ("graphql-ws", client.subprotocol());
  19968. client.close();
  19969. }
  19970. TEST_F(WebSocketIntegrationTest, SubProtocolNoMatch) {
  19971. Headers headers = {{"Sec-WebSocket-Protocol", "mqtt, wamp"}};
  19972. ws::WebSocketClient client(
  19973. "ws://localhost:" + std::to_string(port_) + "/ws-subprotocol", headers);
  19974. ASSERT_TRUE(client.connect());
  19975. // Server should not have selected any subprotocol
  19976. EXPECT_TRUE(client.subprotocol().empty());
  19977. client.close();
  19978. }
  19979. TEST_F(WebSocketIntegrationTest, SubProtocolNotRequested) {
  19980. // Connect without requesting any subprotocol
  19981. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19982. "/ws-subprotocol");
  19983. ASSERT_TRUE(client.connect());
  19984. EXPECT_TRUE(client.subprotocol().empty());
  19985. client.close();
  19986. }
  19987. TEST_F(WebSocketIntegrationTest, SocketSettings) {
  19988. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  19989. "/ws-echo");
  19990. client.set_tcp_nodelay(true);
  19991. client.set_connection_timeout(3, 0);
  19992. bool socket_options_called = false;
  19993. client.set_socket_options([&](socket_t) { socket_options_called = true; });
  19994. ASSERT_TRUE(client.connect());
  19995. ASSERT_TRUE(client.is_open());
  19996. EXPECT_TRUE(socket_options_called);
  19997. ASSERT_TRUE(client.send("hello"));
  19998. std::string msg;
  19999. auto result = client.read(msg);
  20000. EXPECT_EQ(result, ws::ReadResult::Text);
  20001. EXPECT_EQ(msg, "hello");
  20002. client.close();
  20003. }
  20004. TEST_F(WebSocketIntegrationTest, ChronoTimeoutSetters) {
  20005. ws::WebSocketClient client("ws://localhost:" + std::to_string(port_) +
  20006. "/ws-echo");
  20007. client.set_connection_timeout(std::chrono::seconds(3));
  20008. client.set_write_timeout(std::chrono::seconds(3));
  20009. // A sub-second remainder exercises the seconds/microseconds split.
  20010. client.set_read_timeout(std::chrono::milliseconds(1500));
  20011. ASSERT_TRUE(client.connect());
  20012. auto start = std::chrono::steady_clock::now();
  20013. std::string msg;
  20014. EXPECT_EQ(client.read(msg), ws::ReadResult::Timeout);
  20015. auto elapsed = std::chrono::duration_cast<std::chrono::milliseconds>(
  20016. std::chrono::steady_clock::now() - start)
  20017. .count();
  20018. // Above 1s so that dropping the microseconds half of the split fails here.
  20019. // Ignoring the setter altogether would not reach this line at all: a client
  20020. // waits forever by default.
  20021. EXPECT_GE(elapsed, 1400);
  20022. EXPECT_LT(elapsed, 30000);
  20023. }
  20024. TEST(WebSocketPreRoutingTest, RejectWithoutAuth) {
  20025. Server svr;
  20026. svr.set_pre_routing_handler([](const Request &req, Response &res) {
  20027. if (!req.has_header("Authorization")) {
  20028. res.status = StatusCode::Unauthorized_401;
  20029. res.set_content("Unauthorized", "text/plain");
  20030. return Server::HandlerResponse::Handled;
  20031. }
  20032. return Server::HandlerResponse::Unhandled;
  20033. });
  20034. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20035. std::string msg;
  20036. while (ws.read(msg)) {
  20037. ws.send(msg);
  20038. }
  20039. });
  20040. auto port = svr.bind_to_any_port("localhost");
  20041. std::thread t([&]() { svr.listen_after_bind(); });
  20042. svr.wait_until_ready();
  20043. // Without Authorization header - should be rejected before upgrade
  20044. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) + "/ws");
  20045. EXPECT_FALSE(client1.connect());
  20046. // The rejection is framed like any other HTTP response
  20047. {
  20048. Client cli("localhost", port);
  20049. Headers headers = {{"Upgrade", "websocket"},
  20050. {"Connection", "Upgrade"},
  20051. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20052. {"Sec-WebSocket-Version", "13"}};
  20053. auto res = cli.Get("/ws", headers);
  20054. ASSERT_TRUE(res);
  20055. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20056. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20057. EXPECT_EQ("Unauthorized", res->body);
  20058. }
  20059. // With Authorization header - should succeed
  20060. Headers headers = {{"Authorization", "Bearer token123"}};
  20061. ws::WebSocketClient client2("ws://localhost:" + std::to_string(port) + "/ws",
  20062. headers);
  20063. ASSERT_TRUE(client2.connect());
  20064. ASSERT_TRUE(client2.send("hello"));
  20065. std::string msg;
  20066. ASSERT_TRUE(client2.read(msg));
  20067. EXPECT_EQ("hello", msg);
  20068. client2.close();
  20069. svr.stop();
  20070. t.join();
  20071. }
  20072. TEST(WebSocketPreRequestTest, RejectWithoutAuth) {
  20073. Server svr;
  20074. std::atomic<int> pre_request_calls{0};
  20075. std::atomic<bool> route_matched{false};
  20076. svr.set_pre_request_handler([&](const Request &req, Response &res) {
  20077. pre_request_calls++;
  20078. if (req.matched_route == "/ws/:id") { route_matched = true; }
  20079. if (req.get_header_value("Authorization") != "Bearer token123") {
  20080. res.status = StatusCode::Unauthorized_401;
  20081. res.set_content("Unauthorized", "text/plain");
  20082. return Server::HandlerResponse::Handled;
  20083. }
  20084. return Server::HandlerResponse::Unhandled;
  20085. });
  20086. std::atomic<bool> handler_called{false};
  20087. svr.WebSocket("/ws/:id", [&](const Request &req, ws::WebSocket &ws) {
  20088. handler_called = true;
  20089. ws.send(req.matched_route + " " + req.path_params.at("id"));
  20090. });
  20091. auto port = svr.bind_to_any_port("localhost");
  20092. std::thread t([&]() { svr.listen_after_bind(); });
  20093. svr.wait_until_ready();
  20094. // Without Authorization header - should be rejected before upgrade
  20095. ws::WebSocketClient client1("ws://localhost:" + std::to_string(port) +
  20096. "/ws/1");
  20097. EXPECT_FALSE(client1.connect());
  20098. EXPECT_FALSE(handler_called);
  20099. EXPECT_EQ(1, pre_request_calls);
  20100. EXPECT_TRUE(route_matched);
  20101. // The rejection is an ordinary HTTP response, not a protocol switch
  20102. {
  20103. Client cli("localhost", port);
  20104. Headers headers = {{"Upgrade", "websocket"},
  20105. {"Connection", "Upgrade"},
  20106. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20107. {"Sec-WebSocket-Version", "13"}};
  20108. auto res = cli.Get("/ws/1", headers);
  20109. ASSERT_TRUE(res);
  20110. EXPECT_EQ(StatusCode::Unauthorized_401, res->status);
  20111. EXPECT_EQ("12", res->get_header_value("Content-Length"));
  20112. EXPECT_EQ("Unauthorized", res->body);
  20113. }
  20114. EXPECT_FALSE(handler_called);
  20115. // With Authorization header - should succeed
  20116. Headers headers = {{"Authorization", "Bearer token123"}};
  20117. ws::WebSocketClient client2(
  20118. "ws://localhost:" + std::to_string(port) + "/ws/2", headers);
  20119. ASSERT_TRUE(client2.connect());
  20120. std::string msg;
  20121. ASSERT_TRUE(client2.read(msg));
  20122. EXPECT_EQ("/ws/:id 2", msg);
  20123. EXPECT_TRUE(handler_called);
  20124. client2.close();
  20125. svr.stop();
  20126. t.join();
  20127. }
  20128. TEST(WebSocketServerTimeoutTest, HandlerSendsWhileNothingArrives) {
  20129. Server svr;
  20130. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &ws) {
  20131. // A read timeout is how a handler gets control back. Without it, a handler
  20132. // parked in read() can never write on the connection it is reading.
  20133. ws.set_read_timeout(std::chrono::milliseconds(100));
  20134. std::string msg;
  20135. while (ws.is_open()) {
  20136. auto r = ws.read(msg);
  20137. if (r == httplib::ws::Timeout) {
  20138. ws.send("tick");
  20139. continue;
  20140. }
  20141. if (r == httplib::ws::Fail) { break; }
  20142. ws.send(msg);
  20143. }
  20144. });
  20145. auto port = svr.bind_to_any_port("localhost");
  20146. std::thread t([&]() { svr.listen_after_bind(); });
  20147. svr.wait_until_ready();
  20148. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20149. client.set_read_timeout(10, 0); // fail rather than hang if no tick arrives
  20150. ASSERT_TRUE(client.connect());
  20151. // The client sends nothing, so anything it receives came out of the
  20152. // handler's timeout path.
  20153. std::string msg;
  20154. ASSERT_EQ(client.read(msg), ws::Text);
  20155. EXPECT_EQ("tick", msg);
  20156. client.close();
  20157. svr.stop();
  20158. t.join();
  20159. }
  20160. // Stream::read may return fewer bytes than asked for. This is that contract at
  20161. // its worst -- one byte per call -- which is what a frame header straddling a
  20162. // read buffer's boundary looks like to the frame parser.
  20163. class WsByteAtATimeStream : public Stream {
  20164. public:
  20165. explicit WsByteAtATimeStream(std::string data) : data_(std::move(data)) {}
  20166. bool is_readable() const override { return true; }
  20167. bool wait_readable() const override { return true; }
  20168. bool wait_writable() const override { return true; }
  20169. ssize_t read(char *ptr, size_t size) override {
  20170. if (size == 0 || pos_ >= data_.size()) { return 0; }
  20171. *ptr = data_[pos_++];
  20172. return 1;
  20173. }
  20174. ssize_t write(const char *, size_t size) override {
  20175. return static_cast<ssize_t>(size);
  20176. }
  20177. void get_remote_ip_and_port(std::string &ip, int &port) const override {
  20178. ip = "127.0.0.1";
  20179. port = 0;
  20180. }
  20181. void get_local_ip_and_port(std::string &ip, int &port) const override {
  20182. ip = "127.0.0.1";
  20183. port = 0;
  20184. }
  20185. socket_t socket() const override { return INVALID_SOCKET; }
  20186. time_t duration() const override { return 0; }
  20187. private:
  20188. std::string data_;
  20189. size_t pos_ = 0;
  20190. };
  20191. TEST(WebSocketFrameTest, MultiByteFieldsSplitAcrossReads) {
  20192. // A 200-byte payload uses the 16-bit extended length, so the header, the
  20193. // length and the mask key are all multi-byte fields here. Each used to be
  20194. // read with a single read() call, which fails as soon as one is split.
  20195. std::string body(200, 'x');
  20196. const uint8_t mask[4] = {0x0a, 0x0b, 0x0c, 0x0d};
  20197. std::string frame;
  20198. frame += static_cast<char>(0x81); // FIN + Text
  20199. frame += static_cast<char>(0x80 | 126); // masked, 16-bit length follows
  20200. frame += static_cast<char>(body.size() >> 8);
  20201. frame += static_cast<char>(body.size() & 0xff);
  20202. for (size_t i = 0; i < 4; i++) {
  20203. frame += static_cast<char>(mask[i]);
  20204. }
  20205. for (size_t i = 0; i < body.size(); i++) {
  20206. frame += static_cast<char>(body[i] ^ mask[i % 4]);
  20207. }
  20208. WsByteAtATimeStream strm(frame);
  20209. ws::Opcode opcode;
  20210. std::string payload;
  20211. bool fin = false;
  20212. ASSERT_EQ(ws::impl::read_websocket_frame(strm, opcode, payload, fin,
  20213. /*expect_masked=*/true, 1024),
  20214. ws::impl::FrameRead::Ok);
  20215. EXPECT_TRUE(fin);
  20216. EXPECT_EQ(opcode, ws::Opcode::Text);
  20217. EXPECT_EQ(payload, body);
  20218. }
  20219. TEST(WebSocketTest, QueryStringInHandshake) {
  20220. Server svr;
  20221. std::mutex mtx;
  20222. std::string received_target;
  20223. std::string received_token;
  20224. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20225. {
  20226. std::lock_guard<std::mutex> lock(mtx);
  20227. received_target = req.target;
  20228. if (req.has_param("token")) {
  20229. received_token = req.get_param_value("token");
  20230. }
  20231. }
  20232. std::string msg;
  20233. while (ws.read(msg)) {
  20234. ws.send(msg);
  20235. }
  20236. });
  20237. auto port = svr.bind_to_any_port("localhost");
  20238. std::thread t([&]() { svr.listen_after_bind(); });
  20239. svr.wait_until_ready();
  20240. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) +
  20241. "/ws?token=ABC&session=123");
  20242. ASSERT_TRUE(client.connect());
  20243. // Round-trip ensures the handler has run and captured the request.
  20244. ASSERT_TRUE(client.send("hello"));
  20245. std::string msg;
  20246. ASSERT_TRUE(client.read(msg));
  20247. EXPECT_EQ("hello", msg);
  20248. client.close();
  20249. {
  20250. std::lock_guard<std::mutex> lock(mtx);
  20251. EXPECT_EQ("/ws?token=ABC&session=123", received_target);
  20252. EXPECT_EQ("ABC", received_token);
  20253. }
  20254. svr.stop();
  20255. t.join();
  20256. }
  20257. // Run a handshake against a throwaway server and hand the request the server
  20258. // received back to the caller, so tests can assert on the headers the client
  20259. // actually put on the wire.
  20260. static void capture_websocket_handshake_request(
  20261. const Headers &client_headers,
  20262. std::function<void(const Request &, int port)> verify) {
  20263. Server svr;
  20264. std::mutex mtx;
  20265. Request received;
  20266. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20267. {
  20268. std::lock_guard<std::mutex> lock(mtx);
  20269. received = req;
  20270. }
  20271. std::string msg;
  20272. while (ws.read(msg)) {
  20273. ws.send(msg);
  20274. }
  20275. });
  20276. auto port = svr.bind_to_any_port("localhost");
  20277. std::thread t([&]() { svr.listen_after_bind(); });
  20278. auto se = detail::scope_exit([&] {
  20279. svr.stop();
  20280. t.join();
  20281. });
  20282. svr.wait_until_ready();
  20283. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws",
  20284. client_headers);
  20285. ASSERT_TRUE(client.connect());
  20286. ASSERT_TRUE(client.send("hello"));
  20287. std::string msg;
  20288. ASSERT_TRUE(client.read(msg));
  20289. client.close();
  20290. {
  20291. std::lock_guard<std::mutex> lock(mtx);
  20292. verify(received, port);
  20293. }
  20294. }
  20295. TEST(WebSocketTest, DefaultHeadersInHandshake) {
  20296. capture_websocket_handshake_request({}, [](const Request &req, int port) {
  20297. // Non-default port must be present in the Host header. Default ports
  20298. // (80/443) are omitted; that logic is covered by
  20299. // MakeHostAndPortStringTest.
  20300. EXPECT_EQ("localhost:" + std::to_string(port),
  20301. req.get_header_value("Host"));
  20302. EXPECT_EQ(std::string("cpp-httplib/") + CPPHTTPLIB_VERSION,
  20303. req.get_header_value("User-Agent"));
  20304. EXPECT_FALSE(req.has_header("Accept"));
  20305. EXPECT_FALSE(req.has_header("Accept-Encoding"));
  20306. EXPECT_FALSE(req.has_header("Content-Length"));
  20307. });
  20308. }
  20309. TEST(WebSocketTest, UserHeadersOverrideGeneratedOnesInHandshake) {
  20310. capture_websocket_handshake_request(
  20311. {{"Host", "example.com"},
  20312. {"User-Agent", "custom-agent"},
  20313. {"X-Custom", "value"}},
  20314. [](const Request &req, int) {
  20315. EXPECT_EQ("example.com", req.get_header_value("Host"));
  20316. EXPECT_EQ(1U, req.get_header_value_count("Host"));
  20317. EXPECT_EQ("custom-agent", req.get_header_value("User-Agent"));
  20318. EXPECT_EQ(1U, req.get_header_value_count("User-Agent"));
  20319. EXPECT_EQ("value", req.get_header_value("X-Custom"));
  20320. });
  20321. }
  20322. TEST(WebSocketTest, MandatoryHeadersInHandshakeAreEnforced) {
  20323. capture_websocket_handshake_request(
  20324. {{"Upgrade", "bogus"},
  20325. {"Connection", "close"},
  20326. {"Sec-WebSocket-Key", "AAAAAAAAAAAAAAAAAAAAAA=="},
  20327. {"Sec-WebSocket-Version", "8"}},
  20328. [](const Request &req, int) {
  20329. EXPECT_EQ("websocket", req.get_header_value("Upgrade"));
  20330. EXPECT_EQ(1U, req.get_header_value_count("Upgrade"));
  20331. EXPECT_EQ("Upgrade", req.get_header_value("Connection"));
  20332. EXPECT_EQ(1U, req.get_header_value_count("Connection"));
  20333. EXPECT_EQ("13", req.get_header_value("Sec-WebSocket-Version"));
  20334. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Version"));
  20335. EXPECT_EQ(1U, req.get_header_value_count("Sec-WebSocket-Key"));
  20336. EXPECT_NE("AAAAAAAAAAAAAAAAAAAAAA==",
  20337. req.get_header_value("Sec-WebSocket-Key"));
  20338. });
  20339. }
  20340. TEST(WebSocketTest, InvalidHeaderInHandshakeWritesNothing) {
  20341. // A header the client refuses to send must abort the handshake before any
  20342. // part of it reaches the wire; a lone request line would otherwise sit in
  20343. // the peer's buffer as a truncated request.
  20344. auto srv = ::socket(AF_INET, SOCK_STREAM, 0);
  20345. ASSERT_NE(INVALID_SOCKET, srv);
  20346. auto se_srv = detail::scope_exit([&] { detail::close_socket(srv); });
  20347. sockaddr_in addr{};
  20348. addr.sin_family = AF_INET;
  20349. addr.sin_port = 0; // ephemeral, so parallel shards don't collide
  20350. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20351. ASSERT_EQ(0, ::bind(srv, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)));
  20352. ASSERT_EQ(0, ::listen(srv, 1));
  20353. sockaddr_in bound{};
  20354. socklen_t bound_len = sizeof(bound);
  20355. ASSERT_EQ(
  20356. 0, ::getsockname(srv, reinterpret_cast<sockaddr *>(&bound), &bound_len));
  20357. auto port = ntohs(bound.sin_port);
  20358. ssize_t received = -1;
  20359. std::thread t([&] {
  20360. // Bound every blocking call so a regression fails the test with a bad
  20361. // value instead of hanging the suite.
  20362. fd_set rfds;
  20363. FD_ZERO(&rfds);
  20364. FD_SET(srv, &rfds);
  20365. timeval tv{5, 0};
  20366. if (::select(static_cast<int>(srv + 1), &rfds, nullptr, nullptr, &tv) <=
  20367. 0) {
  20368. return;
  20369. }
  20370. sockaddr_in cli_addr{};
  20371. socklen_t cli_len = sizeof(cli_addr);
  20372. auto cli = ::accept(srv, reinterpret_cast<sockaddr *>(&cli_addr), &cli_len);
  20373. if (cli == INVALID_SOCKET) { return; }
  20374. auto se_cli = detail::scope_exit([&] { detail::close_socket(cli); });
  20375. detail::set_socket_opt_time(cli, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20376. char buf[4096];
  20377. received = ::recv(cli, buf, sizeof(buf), 0);
  20378. });
  20379. // The CR/LF makes the value invalid, so check_and_write_headers rejects it.
  20380. // connect() has already shut the socket down by the time it returns false,
  20381. // so the peer sees EOF without waiting for the client to be destroyed.
  20382. ws::WebSocketClient client("ws://127.0.0.1:" + std::to_string(port) + "/ws",
  20383. {{"X-Bad", "a\r\nInjected: 1"}});
  20384. EXPECT_FALSE(client.connect());
  20385. t.join();
  20386. // 0 means the peer saw a clean EOF without a single byte of the handshake.
  20387. EXPECT_EQ(0, received);
  20388. }
  20389. TEST(WebSocketTest, ConnectionHeaderNeedsCompleteUpgradeToken) {
  20390. // RFC 6455 4.2.1: Connection is a token list, so a value that merely
  20391. // contains "upgrade" as a substring is a different token and must not
  20392. // start a WebSocket handshake.
  20393. auto make_request = [](const std::vector<std::string> &connection_values) {
  20394. Request req;
  20395. req.method = "GET";
  20396. req.headers.emplace("Upgrade", "websocket");
  20397. for (const auto &value : connection_values) {
  20398. req.headers.emplace("Connection", value);
  20399. }
  20400. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20401. req.headers.emplace("Sec-WebSocket-Version", "13");
  20402. return req;
  20403. };
  20404. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"Upgrade"})));
  20405. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"upgrade"})));
  20406. EXPECT_TRUE(
  20407. detail::is_websocket_upgrade(make_request({"keep-alive, Upgrade"})));
  20408. EXPECT_TRUE(
  20409. detail::is_websocket_upgrade(make_request({"Upgrade , keep-alive"})));
  20410. EXPECT_TRUE(
  20411. detail::is_websocket_upgrade(make_request({"keep-alive", "Upgrade"})));
  20412. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notupgrade"})));
  20413. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"upgrade-not"})));
  20414. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xupgrade"})));
  20415. EXPECT_FALSE(
  20416. detail::is_websocket_upgrade(make_request({"keep-alive, notupgrade"})));
  20417. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"close"})));
  20418. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20419. }
  20420. TEST(WebSocketTest, UpgradeHeaderNeedsCompleteWebsocketToken) {
  20421. // RFC 9110 7.8 defines Upgrade as a comma-separated list of protocols and
  20422. // asks recipients to match each protocol-name case-insensitively, and RFC
  20423. // 6455 4.2.1 asks for a header field containing the value "websocket". A
  20424. // client naming websocket alongside another protocol, or on a second field
  20425. // line, is offering websocket; a value that merely contains "websocket" as a
  20426. // substring is a different protocol name and is not.
  20427. auto make_request = [](const std::vector<std::string> &upgrade_values) {
  20428. Request req;
  20429. req.method = "GET";
  20430. for (const auto &value : upgrade_values) {
  20431. req.headers.emplace("Upgrade", value);
  20432. }
  20433. req.headers.emplace("Connection", "Upgrade");
  20434. req.headers.emplace("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==");
  20435. req.headers.emplace("Sec-WebSocket-Version", "13");
  20436. return req;
  20437. };
  20438. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"websocket"})));
  20439. EXPECT_TRUE(detail::is_websocket_upgrade(make_request({"WebSocket"})));
  20440. EXPECT_TRUE(
  20441. detail::is_websocket_upgrade(make_request({"websocket, HTTP/3.0"})));
  20442. EXPECT_TRUE(
  20443. detail::is_websocket_upgrade(make_request({"HTTP/3.0 , websocket"})));
  20444. EXPECT_TRUE(
  20445. detail::is_websocket_upgrade(make_request({"HTTP/3.0", "websocket"})));
  20446. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"notwebsocket"})));
  20447. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"websocket-2"})));
  20448. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"xwebsocket"})));
  20449. EXPECT_FALSE(
  20450. detail::is_websocket_upgrade(make_request({"HTTP/3.0, notwebsocket"})));
  20451. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({"h2c"})));
  20452. EXPECT_FALSE(detail::is_websocket_upgrade(make_request({})));
  20453. }
  20454. TEST(WebSocketTest, ServerRejectsHandshakeWithoutUpgradeToken) {
  20455. Server svr;
  20456. svr.WebSocket("/ws", [](const Request &, ws::WebSocket &) {});
  20457. auto port = svr.bind_to_any_port("localhost");
  20458. std::thread t([&]() { svr.listen_after_bind(); });
  20459. auto se = detail::scope_exit([&] {
  20460. svr.stop();
  20461. t.join();
  20462. });
  20463. svr.wait_until_ready();
  20464. Headers headers = {{"Upgrade", "websocket"},
  20465. {"Connection", "notupgrade"},
  20466. {"Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ=="},
  20467. {"Sec-WebSocket-Version", "13"}};
  20468. Client cli("localhost", port);
  20469. auto res = cli.Get("/ws", headers);
  20470. // The route exists only as a WebSocket route, so a request that fails the
  20471. // handshake check falls through to ordinary routing.
  20472. ASSERT_TRUE(res);
  20473. EXPECT_EQ(StatusCode::NotFound_404, res->status);
  20474. }
  20475. TEST(WebSocketTest, ClientRejectsResponseWithoutUpgradeToken) {
  20476. // The peer answers 101 with a correct Sec-WebSocket-Accept, so the
  20477. // Connection value is the only thing left for the client to reject.
  20478. Server svr;
  20479. svr.Get("/ws", [](const Request &req, Response &res) {
  20480. res.status = StatusCode::SwitchingProtocol_101;
  20481. res.set_header("Upgrade", "websocket");
  20482. res.set_header("Connection", "notupgrade");
  20483. res.set_header("Sec-WebSocket-Accept",
  20484. detail::websocket_accept_key(
  20485. req.get_header_value("Sec-WebSocket-Key")));
  20486. });
  20487. auto port = svr.bind_to_any_port("localhost");
  20488. std::thread t([&]() { svr.listen_after_bind(); });
  20489. auto se = detail::scope_exit([&] {
  20490. svr.stop();
  20491. t.join();
  20492. });
  20493. svr.wait_until_ready();
  20494. ws::WebSocketClient client("ws://localhost:" + std::to_string(port) + "/ws");
  20495. auto res = client.connect();
  20496. EXPECT_FALSE(res);
  20497. EXPECT_EQ(Error::WebSocketHandshake, res.error());
  20498. EXPECT_FALSE(client.is_open());
  20499. }
  20500. TEST(WebSocketTest, HostHeaderOverUnixSocket) {
  20501. // The socket path doubles as the URL host, so it must not contain '/'.
  20502. const char *shard = getenv("GTEST_SHARD_INDEX");
  20503. const std::string sock_path =
  20504. shard ? std::string("httplib-ws-") + shard + ".sock"
  20505. : std::string("httplib-ws.sock");
  20506. std::remove(sock_path.c_str());
  20507. Server svr;
  20508. std::mutex mtx;
  20509. std::string received_host;
  20510. svr.WebSocket("/ws", [&](const Request &req, ws::WebSocket &ws) {
  20511. {
  20512. std::lock_guard<std::mutex> lock(mtx);
  20513. received_host = req.get_header_value("Host");
  20514. }
  20515. std::string msg;
  20516. while (ws.read(msg)) {
  20517. ws.send(msg);
  20518. }
  20519. });
  20520. svr.set_address_family(AF_UNIX);
  20521. std::thread t([&]() { ASSERT_TRUE(svr.listen(sock_path, 80)); });
  20522. auto se = detail::scope_exit([&] {
  20523. svr.stop();
  20524. t.join();
  20525. std::remove(sock_path.c_str());
  20526. });
  20527. svr.wait_until_ready();
  20528. ws::WebSocketClient client("ws://" + sock_path + "/ws");
  20529. client.set_address_family(AF_UNIX);
  20530. ASSERT_TRUE(client.connect());
  20531. ASSERT_TRUE(client.send("hello"));
  20532. std::string msg;
  20533. ASSERT_TRUE(client.read(msg));
  20534. client.close();
  20535. {
  20536. std::lock_guard<std::mutex> lock(mtx);
  20537. // There is no host:port for a Unix socket, so the same "localhost"
  20538. // placeholder the HTTP client uses is expected.
  20539. EXPECT_EQ("localhost", received_host);
  20540. }
  20541. }
  20542. // Two threads must never parse WebSocket frames from the same stream.
  20543. // close() used to read the peer's Close reply with its own frame read, so it
  20544. // raced a reader thread that was in the middle of a payload: the payload loop
  20545. // in read_websocket_frame() keeps reading until payload_len bytes are in hand,
  20546. // so bytes taken by close() were replaced with bytes from further along the
  20547. // stream. The message kept its length and silently changed content.
  20548. //
  20549. // The raw peer below sends a frame header plus part of the payload, waits for
  20550. // the handler to call close(), and only then sends the rest. Whichever thread
  20551. // would win the race for those bytes, the message must arrive intact, because
  20552. // close() must not touch the stream while read() owns it.
  20553. TEST(WebSocketTest, CloseDoesNotStealBytesFromConcurrentRead) {
  20554. #ifndef _WIN32
  20555. signal(SIGPIPE, SIG_IGN);
  20556. #endif
  20557. const size_t payload_len = 120; // fits the 7-bit length field
  20558. const size_t prefix_len = 8;
  20559. const int attempts = 8;
  20560. std::string expected(payload_len, '\0');
  20561. for (size_t i = 0; i < payload_len; i++) {
  20562. expected[i] = static_cast<char>('a' + i % 26);
  20563. }
  20564. std::atomic<bool> peer_stalled{false};
  20565. std::atomic<bool> handler_done{false};
  20566. std::mutex received_mutex;
  20567. std::vector<std::string> received;
  20568. // Bound every wait, so a regression fails the test instead of hanging the
  20569. // suite.
  20570. auto wait_for = [](const std::atomic<bool> &flag) {
  20571. for (int i = 0; i < 500 && !flag; i++) {
  20572. std::this_thread::sleep_for(std::chrono::milliseconds(10));
  20573. }
  20574. };
  20575. Server svr;
  20576. svr.set_websocket_ping_interval(0);
  20577. svr.WebSocket("/ws", [&](const Request &, ws::WebSocket &ws) {
  20578. std::thread reader([&]() {
  20579. std::string msg;
  20580. while (ws.read(msg)) {
  20581. std::lock_guard<std::mutex> guard(received_mutex);
  20582. received.push_back(msg);
  20583. }
  20584. });
  20585. // Wait until the peer stalls mid-payload, so the reader thread is parked
  20586. // inside read_websocket_frame() when close() runs.
  20587. wait_for(peer_stalled);
  20588. ws.close();
  20589. reader.join();
  20590. handler_done = true;
  20591. });
  20592. auto port = svr.bind_to_any_port("127.0.0.1");
  20593. std::thread t([&]() { svr.listen_after_bind(); });
  20594. auto se = detail::scope_exit([&] {
  20595. svr.stop();
  20596. t.join();
  20597. });
  20598. svr.wait_until_ready();
  20599. auto send_bytes = [](socket_t s, const std::string &data) {
  20600. #ifdef _WIN32
  20601. auto n = ::send(s, data.data(), static_cast<int>(data.size()), 0);
  20602. #else
  20603. auto n = ::send(s, data.data(), data.size(), 0);
  20604. #endif
  20605. return n == static_cast<decltype(n)>(data.size());
  20606. };
  20607. // Frame header with an all-zero mask key, so the payload goes out verbatim.
  20608. // Every length used here fits the 7-bit length field.
  20609. auto masked_header = [](uint8_t first_byte, size_t len) {
  20610. std::string h;
  20611. h += static_cast<char>(first_byte);
  20612. h += static_cast<char>(0x80 | len); // masked, 7-bit length
  20613. h.append(4, '\0'); // mask key
  20614. return h;
  20615. };
  20616. for (int attempt = 0; attempt < attempts; attempt++) {
  20617. peer_stalled = false;
  20618. handler_done = false;
  20619. auto sock = ::socket(AF_INET, SOCK_STREAM, 0);
  20620. ASSERT_NE(INVALID_SOCKET, sock) << "attempt " << attempt;
  20621. auto se_sock = detail::scope_exit([&] {
  20622. if (sock != INVALID_SOCKET) { detail::close_socket(sock); }
  20623. });
  20624. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_RCVTIMEO, 5, 0);
  20625. detail::set_socket_opt_time(sock, SOL_SOCKET, SO_SNDTIMEO, 5, 0);
  20626. sockaddr_in addr{};
  20627. addr.sin_family = AF_INET;
  20628. addr.sin_port = htons(static_cast<uint16_t>(port));
  20629. ::inet_pton(AF_INET, "127.0.0.1", &addr.sin_addr);
  20630. ASSERT_EQ(
  20631. 0, ::connect(sock, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)))
  20632. << "attempt " << attempt;
  20633. ASSERT_TRUE(send_bytes(sock,
  20634. "GET /ws HTTP/1.1\r\n"
  20635. "Host: 127.0.0.1\r\n"
  20636. "Upgrade: websocket\r\n"
  20637. "Connection: Upgrade\r\n"
  20638. "Sec-WebSocket-Key: AAAAAAAAAAAAAAAAAAAAAA==\r\n"
  20639. "Sec-WebSocket-Version: 13\r\n"
  20640. "\r\n"))
  20641. << "attempt " << attempt;
  20642. std::string response;
  20643. while (response.find("\r\n\r\n") == std::string::npos) {
  20644. char buf[512];
  20645. auto n = ::recv(sock, buf, static_cast<int>(sizeof(buf)), 0);
  20646. if (n <= 0) { break; }
  20647. response.append(buf, static_cast<size_t>(n));
  20648. }
  20649. ASSERT_NE(std::string::npos, response.find(" 101 "))
  20650. << "attempt " << attempt;
  20651. // Send the header of a Binary message but only the first prefix_len bytes
  20652. // of its payload, leaving the reader thread stalled inside the payload.
  20653. ASSERT_TRUE(send_bytes(sock, masked_header(0x82, payload_len) +
  20654. expected.substr(0, prefix_len)))
  20655. << "attempt " << attempt;
  20656. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20657. peer_stalled = true;
  20658. // Let close() send its Close frame and park in its own read before the
  20659. // rest of the payload arrives, so both threads are waiting for it.
  20660. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20661. std::string close_frame = masked_header(0x88, 2); // FIN + Close
  20662. close_frame += static_cast<char>(0x03); // status 1000
  20663. close_frame += static_cast<char>(0xE8);
  20664. ASSERT_TRUE(send_bytes(sock, expected.substr(prefix_len) + close_frame))
  20665. << "attempt " << attempt;
  20666. // Closing the peer releases the reader thread even on the buggy path,
  20667. // where it waits for bytes another thread already consumed.
  20668. std::this_thread::sleep_for(std::chrono::milliseconds(50));
  20669. detail::close_socket(sock);
  20670. sock = INVALID_SOCKET;
  20671. wait_for(handler_done);
  20672. ASSERT_TRUE(handler_done) << "attempt " << attempt;
  20673. }
  20674. std::lock_guard<std::mutex> guard(received_mutex);
  20675. EXPECT_EQ(static_cast<size_t>(attempts), received.size())
  20676. << "a message in flight when close() ran was dropped";
  20677. for (size_t i = 0; i < received.size(); i++) {
  20678. EXPECT_EQ(expected, received[i]) << "message " << i;
  20679. }
  20680. }
  20681. #ifdef CPPHTTPLIB_OPENSSL_SUPPORT
  20682. class WebSocketSSLIntegrationTest : public ::testing::Test {
  20683. protected:
  20684. void SetUp() override {
  20685. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT_FILE,
  20686. SERVER_PRIVATE_KEY_FILE);
  20687. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20688. std::string msg;
  20689. ws::ReadResult ret;
  20690. while ((ret = ws.read(msg))) {
  20691. if (ret == ws::Binary) {
  20692. ws.send(msg.data(), msg.size());
  20693. } else {
  20694. ws.send(msg);
  20695. }
  20696. }
  20697. });
  20698. port_ = server_->bind_to_any_port(HOST);
  20699. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20700. server_->wait_until_ready();
  20701. }
  20702. void TearDown() override {
  20703. server_->stop();
  20704. if (server_thread_.joinable()) { server_thread_.join(); }
  20705. }
  20706. std::unique_ptr<SSLServer> server_;
  20707. std::thread server_thread_;
  20708. int port_ = 0;
  20709. };
  20710. TEST_F(WebSocketSSLIntegrationTest, TextEcho) {
  20711. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20712. "/ws-echo");
  20713. client.enable_server_certificate_verification(false);
  20714. ASSERT_TRUE(client.connect());
  20715. ASSERT_TRUE(client.is_open());
  20716. ASSERT_TRUE(client.send("Hello WSS"));
  20717. std::string msg;
  20718. EXPECT_EQ(ws::Text, client.read(msg));
  20719. EXPECT_EQ("Hello WSS", msg);
  20720. client.close();
  20721. }
  20722. // Regression test (GHSA-w7p7-f35j-mw7q): shutdown_and_close() used to free the
  20723. // TLS session before ws_->close() sent the close frame. Because the WebSocket's
  20724. // SSLSocketStream keeps a raw pointer to that session, sending the close frame
  20725. // then read/wrote a freed SSL object (use-after-free). Destroying an open wss
  20726. // client (without calling close() first) is the only path that runs
  20727. // shutdown_and_close() while the WebSocket is still open, so it reproduces the
  20728. // bug exactly.
  20729. //
  20730. // NOTE: the offending read/write happens inside OpenSSL, so ASan only flags it
  20731. // when linked against an instrumented libssl; run under Valgrind to catch it
  20732. // with a stock OpenSSL. The short timeouts keep a regression from wedging the
  20733. // suite (the freed session otherwise stalls on the close handshake) — this test
  20734. // is a memory-tool tripwire, not a pass/fail assertion on stock builds.
  20735. TEST_F(WebSocketSSLIntegrationTest, DestroyWhileOpenSendsCloseOverLiveSession) {
  20736. {
  20737. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20738. "/ws-echo");
  20739. client.enable_server_certificate_verification(false);
  20740. client.set_read_timeout(2, 0);
  20741. client.set_write_timeout(2, 0);
  20742. ASSERT_TRUE(client.connect());
  20743. ASSERT_TRUE(client.is_open());
  20744. ASSERT_TRUE(client.send("still open"));
  20745. // Intentionally do NOT call client.close(): leaving scope runs
  20746. // shutdown_and_close() with the WebSocket still open, which must send the
  20747. // close frame while the TLS session is still alive.
  20748. }
  20749. }
  20750. // Regression test (GHSA-w7p7-f35j-mw7q): reconnecting an open wss client runs
  20751. // shutdown_and_close() at the start of connect(), reproducing the same
  20752. // use-after-free within the test body rather than at scope exit. The second
  20753. // connect must succeed and echo, proving the close handshake ran over a live
  20754. // session. See the note above about memory-tool requirements.
  20755. TEST_F(WebSocketSSLIntegrationTest,
  20756. ReconnectWhileOpenSendsCloseOverLiveSession) {
  20757. ws::WebSocketClient client("wss://localhost:" + std::to_string(port_) +
  20758. "/ws-echo");
  20759. client.enable_server_certificate_verification(false);
  20760. client.set_read_timeout(2, 0);
  20761. client.set_write_timeout(2, 0);
  20762. ASSERT_TRUE(client.connect());
  20763. ASSERT_TRUE(client.is_open());
  20764. ASSERT_TRUE(client.send("still open"));
  20765. // Reconnect without closing first: connect() calls shutdown_and_close() on
  20766. // the still-open connection, which must not touch a freed TLS session.
  20767. ASSERT_TRUE(client.connect());
  20768. ASSERT_TRUE(client.is_open());
  20769. ASSERT_TRUE(client.send("after reconnect"));
  20770. std::string msg;
  20771. EXPECT_EQ(ws::Text, client.read(msg));
  20772. EXPECT_EQ("after reconnect", msg);
  20773. client.close();
  20774. }
  20775. #endif
  20776. #ifdef CPPHTTPLIB_SSL_ENABLED
  20777. class WebSocketSSLCATest : public ::testing::Test {
  20778. protected:
  20779. void SetUp() override {
  20780. server_ = httplib::detail::make_unique<SSLServer>(SERVER_CERT2_FILE,
  20781. SERVER_PRIVATE_KEY_FILE);
  20782. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20783. std::string msg;
  20784. while (ws.read(msg)) {
  20785. ws.send(msg);
  20786. }
  20787. });
  20788. port_ = server_->bind_to_any_port("127.0.0.1");
  20789. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20790. server_->wait_until_ready();
  20791. }
  20792. void TearDown() override {
  20793. server_->stop();
  20794. if (server_thread_.joinable()) { server_thread_.join(); }
  20795. }
  20796. std::string url() const {
  20797. return "wss://127.0.0.1:" + std::to_string(port_) + "/echo";
  20798. }
  20799. std::unique_ptr<SSLServer> server_;
  20800. std::thread server_thread_;
  20801. int port_ = 0;
  20802. };
  20803. // A custom CA loaded as PEM verifies the server with full certificate
  20804. // verification enabled
  20805. TEST_F(WebSocketSSLCATest, LoadCaCertStoreVerifiesServer) {
  20806. ws::WebSocketClient client(url());
  20807. std::string cert;
  20808. read_file(SERVER_CERT2_FILE, cert);
  20809. client.load_ca_cert_store(cert.c_str(), cert.size());
  20810. ASSERT_TRUE(client.connect());
  20811. ASSERT_TRUE(client.send("hello"));
  20812. std::string msg;
  20813. EXPECT_EQ(ws::Text, client.read(msg));
  20814. EXPECT_EQ("hello", msg);
  20815. client.close();
  20816. }
  20817. // A custom CA that does not cover the server must fail verification (the
  20818. // custom CA is exclusive; system certs are not loaded alongside it)
  20819. TEST_F(WebSocketSSLCATest, WrongCustomCaFailsVerification) {
  20820. ws::WebSocketClient client(url());
  20821. std::string cert;
  20822. read_file(CLIENT_CA_CERT_FILE, cert);
  20823. client.load_ca_cert_store(cert.c_str(), cert.size());
  20824. auto res = client.connect();
  20825. ASSERT_FALSE(res);
  20826. EXPECT_EQ(Error::SSLServerVerification, res.error());
  20827. EXPECT_EQ(-1, res.status());
  20828. EXPECT_NE(0u, res.ssl_backend_error());
  20829. }
  20830. // The same CA as a file path rather than PEM in memory
  20831. TEST_F(WebSocketSSLCATest, SetCaCertPathVerifiesServer) {
  20832. ws::WebSocketClient client(url());
  20833. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20834. ASSERT_TRUE(client.connect());
  20835. ASSERT_TRUE(client.send("hello"));
  20836. std::string msg;
  20837. EXPECT_EQ(ws::Text, client.read(msg));
  20838. EXPECT_EQ("hello", msg);
  20839. client.close();
  20840. }
  20841. // ...and a CA file that does not cover the server still fails, so it is the
  20842. // path above that decides the outcome
  20843. TEST_F(WebSocketSSLCATest, WrongCaCertPathFailsVerification) {
  20844. ws::WebSocketClient client(url());
  20845. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20846. ASSERT_FALSE(client.connect());
  20847. }
  20848. // Regression test: reconnecting with a native custom CA store used to reuse
  20849. // a store handle the previous TLS context had already freed (use-after-free
  20850. // under the OpenSSL backend). The context now lives as long as the client.
  20851. TEST_F(WebSocketSSLCATest, ReconnectWithCustomCaStore) {
  20852. ws::WebSocketClient client(url());
  20853. std::string cert;
  20854. read_file(SERVER_CERT2_FILE, cert);
  20855. client.set_ca_cert_store(tls::create_ca_store(cert.c_str(), cert.size()));
  20856. ASSERT_TRUE(client.connect());
  20857. client.close();
  20858. ASSERT_TRUE(client.connect());
  20859. ASSERT_TRUE(client.send("again"));
  20860. std::string msg;
  20861. EXPECT_EQ(ws::Text, client.read(msg));
  20862. EXPECT_EQ("again", msg);
  20863. client.close();
  20864. }
  20865. // Regression test: a certificate with a trusted chain but no identity match
  20866. // for the server IP must be rejected. The Mbed TLS backend used to skip
  20867. // verification entirely for IP hosts, so this connection succeeded there.
  20868. // SERVER_CERT_FILE has no IP SAN (CN only), so trusting it as a CA satisfies
  20869. // chain verification while the identity check must still fail.
  20870. TEST(WebSocketSSLVerifyTest, TrustedChainWrongIdentityFails) {
  20871. SSLServer svr(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE);
  20872. ASSERT_TRUE(svr.is_valid());
  20873. svr.WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20874. std::string msg;
  20875. while (ws.read(msg)) {
  20876. ws.send(msg);
  20877. }
  20878. });
  20879. auto port = svr.bind_to_any_port("127.0.0.1");
  20880. auto t = std::thread([&]() { svr.listen_after_bind(); });
  20881. auto se = detail::scope_exit([&] {
  20882. svr.stop();
  20883. t.join();
  20884. });
  20885. svr.wait_until_ready();
  20886. ws::WebSocketClient client("wss://127.0.0.1:" + std::to_string(port) +
  20887. "/echo");
  20888. std::string cert;
  20889. read_file(SERVER_CERT_FILE, cert);
  20890. client.load_ca_cert_store(cert.c_str(), cert.size());
  20891. ASSERT_FALSE(client.connect());
  20892. }
  20893. // The tests above all connect to an IP literal, for which RFC 6066 forbids
  20894. // SNI, so nothing binds the host name to the TLS session. These bind the
  20895. // server to "localhost" instead, the only shape that exercises the SNI and
  20896. // hostname-verification path with certificate verification left enabled.
  20897. class WebSocketSSLDnsHostTest : public ::testing::Test {
  20898. protected:
  20899. void Start(const char *cert_file) {
  20900. server_ = httplib::detail::make_unique<SSLServer>(cert_file,
  20901. SERVER_PRIVATE_KEY_FILE);
  20902. ASSERT_TRUE(server_->is_valid());
  20903. server_->WebSocket("/echo", [](const Request &, ws::WebSocket &ws) {
  20904. std::string msg;
  20905. while (ws.read(msg)) {
  20906. ws.send(msg);
  20907. }
  20908. });
  20909. port_ = server_->bind_to_any_port("localhost");
  20910. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20911. server_->wait_until_ready();
  20912. }
  20913. void TearDown() override {
  20914. if (server_) { server_->stop(); }
  20915. if (server_thread_.joinable()) { server_thread_.join(); }
  20916. }
  20917. std::string url() const {
  20918. return "wss://localhost:" + std::to_string(port_) + "/echo";
  20919. }
  20920. std::unique_ptr<SSLServer> server_;
  20921. std::thread server_thread_;
  20922. int port_ = 0;
  20923. };
  20924. // cert2 carries a DNS:localhost SAN, so both the chain and the identity check
  20925. // out and the connection is usable
  20926. TEST_F(WebSocketSSLDnsHostTest, TrustedChainMatchingNameVerifies) {
  20927. Start(SERVER_CERT2_FILE);
  20928. ws::WebSocketClient client(url());
  20929. client.set_ca_cert_path(SERVER_CERT2_FILE);
  20930. ASSERT_TRUE(client.connect());
  20931. ASSERT_TRUE(client.send("hello"));
  20932. std::string msg;
  20933. EXPECT_EQ(ws::Text, client.read(msg));
  20934. EXPECT_EQ("hello", msg);
  20935. client.close();
  20936. }
  20937. // cert.pem has a CN but no SAN, so trusting it as a CA satisfies the chain
  20938. // while the identity check must still reject "localhost"
  20939. TEST_F(WebSocketSSLDnsHostTest, TrustedChainWrongNameFails) {
  20940. Start(SERVER_CERT_FILE);
  20941. ws::WebSocketClient client(url());
  20942. client.set_ca_cert_path(SERVER_CERT_FILE);
  20943. auto res = client.connect();
  20944. ASSERT_FALSE(res);
  20945. EXPECT_EQ(Error::SSLServerHostnameVerification, res.error());
  20946. EXPECT_EQ(-1, res.status());
  20947. }
  20948. // Same setup as TrustedChainWrongNameFails, but with hostname verification
  20949. // disabled: the chain is still checked, only the identity check is skipped
  20950. TEST_F(WebSocketSSLDnsHostTest, HostnameVerificationDisabledAcceptsWrongName) {
  20951. Start(SERVER_CERT_FILE);
  20952. ws::WebSocketClient client(url());
  20953. client.set_ca_cert_path(SERVER_CERT_FILE);
  20954. client.enable_server_hostname_verification(false);
  20955. ASSERT_TRUE(client.connect());
  20956. ASSERT_TRUE(client.send("hello"));
  20957. std::string msg;
  20958. EXPECT_EQ(ws::Text, client.read(msg));
  20959. EXPECT_EQ("hello", msg);
  20960. client.close();
  20961. }
  20962. // A CA that did not sign the server certificate fails the chain, even though
  20963. // the name would match
  20964. TEST_F(WebSocketSSLDnsHostTest, UntrustedChainFails) {
  20965. Start(SERVER_CERT2_FILE);
  20966. ws::WebSocketClient client(url());
  20967. client.set_ca_cert_path(CLIENT_CA_CERT_FILE);
  20968. ASSERT_FALSE(client.connect());
  20969. }
  20970. // With verification disabled, neither the chain nor the name is checked
  20971. TEST_F(WebSocketSSLDnsHostTest, VerificationDisabledAcceptsAnyName) {
  20972. Start(SERVER_CERT_FILE);
  20973. ws::WebSocketClient client(url());
  20974. client.enable_server_certificate_verification(false);
  20975. ASSERT_TRUE(client.connect());
  20976. ASSERT_TRUE(client.send("hello"));
  20977. std::string msg;
  20978. EXPECT_EQ(ws::Text, client.read(msg));
  20979. EXPECT_EQ("hello", msg);
  20980. client.close();
  20981. }
  20982. class WebSocketSSLPemMemoryTest : public ::testing::Test {
  20983. protected:
  20984. void SetUp() override {
  20985. server_ = httplib::detail::make_unique<SSLServer>(
  20986. SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE, CLIENT_CA_CERT_FILE);
  20987. ASSERT_TRUE(server_->is_valid());
  20988. server_->WebSocket("/ws-echo", [](const Request &, ws::WebSocket &ws) {
  20989. std::string msg;
  20990. while (ws.read(msg)) {
  20991. ws.send(msg);
  20992. }
  20993. });
  20994. port_ = server_->bind_to_any_port("localhost");
  20995. server_thread_ = std::thread([this]() { server_->listen_after_bind(); });
  20996. server_->wait_until_ready();
  20997. }
  20998. void TearDown() override {
  20999. server_->stop();
  21000. if (server_thread_.joinable()) { server_thread_.join(); }
  21001. }
  21002. std::string url() const {
  21003. return "wss://localhost:" + std::to_string(port_) + "/ws-echo";
  21004. }
  21005. void ConnectWithClientCert(const std::string &client_cert_file,
  21006. const std::string &client_private_key_file,
  21007. const char *private_key_password) {
  21008. std::string cert_pem, key_pem;
  21009. read_file(client_cert_file, cert_pem);
  21010. read_file(client_private_key_file, key_pem);
  21011. ws::WebSocketClient::PemMemory pem = {cert_pem.c_str(), cert_pem.size(),
  21012. key_pem.c_str(), key_pem.size(),
  21013. private_key_password};
  21014. ws::WebSocketClient client(url(), pem);
  21015. ASSERT_TRUE(client.is_valid());
  21016. client.enable_server_certificate_verification(false);
  21017. ASSERT_TRUE(client.connect());
  21018. ASSERT_TRUE(client.send("hello"));
  21019. std::string msg;
  21020. EXPECT_EQ(ws::Text, client.read(msg));
  21021. EXPECT_EQ("hello", msg);
  21022. client.close();
  21023. }
  21024. std::unique_ptr<SSLServer> server_;
  21025. std::thread server_thread_;
  21026. int port_ = 0;
  21027. };
  21028. TEST_F(WebSocketSSLPemMemoryTest, ClientCertAccepted) {
  21029. ConnectWithClientCert(CLIENT_CERT_FILE, CLIENT_PRIVATE_KEY_FILE, nullptr);
  21030. }
  21031. // Control for the tests above: the fixture's server really does require a
  21032. // client certificate, so it is the PEM the constructor installed that decides
  21033. // the outcome.
  21034. TEST_F(WebSocketSSLPemMemoryTest, NoClientCertRejected) {
  21035. ws::WebSocketClient client(url());
  21036. ASSERT_TRUE(client.is_valid());
  21037. client.enable_server_certificate_verification(false);
  21038. EXPECT_FALSE(client.connect());
  21039. }
  21040. TEST_F(WebSocketSSLPemMemoryTest, EncryptedClientCertAccepted) {
  21041. ConnectWithClientCert(CLIENT_ENCRYPTED_CERT_FILE,
  21042. CLIENT_ENCRYPTED_PRIVATE_KEY_FILE,
  21043. CLIENT_ENCRYPTED_PRIVATE_KEY_PASS);
  21044. }
  21045. #endif
  21046. #if !defined(_WIN32)
  21047. TEST(SymlinkTest, SymlinkEscapeFromBaseDirectory) {
  21048. auto secret_dir = std::string("./symlink_test_secret");
  21049. auto served_dir = std::string("./symlink_test_served");
  21050. auto secret_file = secret_dir + "/secret.txt";
  21051. auto symlink_path = served_dir + "/escape";
  21052. // Setup: create directories and files
  21053. mkdir(secret_dir.c_str(), 0755);
  21054. mkdir(served_dir.c_str(), 0755);
  21055. {
  21056. std::ofstream ofs(secret_file);
  21057. ofs << "SECRET_DATA";
  21058. }
  21059. // Create symlink using absolute path so it resolves correctly
  21060. #ifdef PATH_MAX
  21061. char abs_secret[PATH_MAX];
  21062. ASSERT_NE(nullptr, realpath(secret_dir.c_str(), abs_secret));
  21063. #else
  21064. auto abs_secret = realpath(secret_dir.c_str(), nullptr);
  21065. auto abs_secret_guard = detail::scope_exit([&]() { std::free(abs_secret); });
  21066. ASSERT_NE(nullptr, abs_secret);
  21067. #endif
  21068. ASSERT_EQ(0, symlink(abs_secret, symlink_path.c_str()));
  21069. auto se = detail::scope_exit([&] {
  21070. unlink(symlink_path.c_str());
  21071. unlink(secret_file.c_str());
  21072. rmdir(served_dir.c_str());
  21073. rmdir(secret_dir.c_str());
  21074. });
  21075. Server svr;
  21076. svr.set_mount_point("/", served_dir);
  21077. auto listen_thread = std::thread([&svr]() { svr.listen("localhost", PORT); });
  21078. auto se2 = detail::scope_exit([&] {
  21079. svr.stop();
  21080. listen_thread.join();
  21081. });
  21082. svr.wait_until_ready();
  21083. Client cli("localhost", PORT);
  21084. // Symlink pointing outside base dir should be blocked
  21085. auto res = cli.Get("/escape/secret.txt");
  21086. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21087. EXPECT_EQ(StatusCode::Forbidden_403, res->status);
  21088. }
  21089. #endif
  21090. TEST(RequestSmugglingTest, UnconsumedGETBodyOnFileHandler) {
  21091. // A GET request with Content-Length to a static file handler must have its
  21092. // body drained before the keep-alive connection is reused. Otherwise the
  21093. // unread body bytes are interpreted as the next HTTP request.
  21094. //
  21095. // The body is sent AFTER receiving the first response (as in the original
  21096. // PoC) so that the stream_line_reader cannot buffer it together with the
  21097. // headers of the first request.
  21098. Server svr;
  21099. svr.set_mount_point("/", "./www");
  21100. std::atomic<int> smuggled_count(0);
  21101. svr.Get("/smuggled", [&](const Request &, Response &res) {
  21102. smuggled_count++;
  21103. res.set_content("oops", "text/plain");
  21104. });
  21105. auto port = svr.bind_to_any_port("localhost");
  21106. thread t = thread([&] { svr.listen_after_bind(); });
  21107. auto se = detail::scope_exit([&] {
  21108. svr.stop();
  21109. t.join();
  21110. });
  21111. svr.wait_until_ready();
  21112. auto error = Error::Success;
  21113. auto sock = detail::create_client_socket(
  21114. "localhost", "", port, AF_UNSPEC, false, false, nullptr,
  21115. /*connection_timeout_sec=*/2, 0,
  21116. /*read_timeout_sec=*/2, 0,
  21117. /*write_timeout_sec=*/2, 0, std::string(), error);
  21118. ASSERT_NE(INVALID_SOCKET, sock);
  21119. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21120. // The "smuggled" request will be sent as the body of the outer GET
  21121. std::string smuggled = "GET /smuggled HTTP/1.1\r\n"
  21122. "Host: localhost\r\n"
  21123. "Connection: close\r\n"
  21124. "\r\n";
  21125. // Step 1: Send only the outer request headers (no body yet)
  21126. std::string outer_headers = "GET /file HTTP/1.1\r\n"
  21127. "Host: localhost\r\n"
  21128. "Content-Length: " +
  21129. std::to_string(smuggled.size()) +
  21130. "\r\n"
  21131. "\r\n";
  21132. auto sent = send(sock, outer_headers.data(), outer_headers.size(), 0);
  21133. ASSERT_EQ(static_cast<ssize_t>(outer_headers.size()), sent);
  21134. // Step 2: Read the first response (server serves file without reading body)
  21135. std::string first_response;
  21136. char buf[4096];
  21137. for (;;) {
  21138. auto n = recv(sock, buf, sizeof(buf), 0);
  21139. if (n <= 0) break;
  21140. first_response.append(buf, static_cast<size_t>(n));
  21141. // Stop once we have a complete response (headers + body)
  21142. auto hdr_end = first_response.find("\r\n\r\n");
  21143. if (hdr_end != std::string::npos) {
  21144. // Check for Content-Length to know when the body is complete
  21145. auto cl_pos = first_response.find("Content-Length:");
  21146. if (cl_pos != std::string::npos) {
  21147. auto cl_val_start = cl_pos + 15; // length of "Content-Length:"
  21148. auto cl_val_end = first_response.find("\r\n", cl_val_start);
  21149. auto cl = std::stoul(
  21150. first_response.substr(cl_val_start, cl_val_end - cl_val_start));
  21151. if (first_response.size() >= hdr_end + 4 + cl) { break; }
  21152. } else {
  21153. break; // No Content-Length, assume headers-only response
  21154. }
  21155. }
  21156. }
  21157. ASSERT_TRUE(first_response.find("HTTP/1.1 200") != std::string::npos);
  21158. // Step 3: Now send the body, which looks like a new HTTP request.
  21159. // On a vulnerable server the keep-alive loop reads this as a second request.
  21160. sent = send(sock, smuggled.data(), smuggled.size(), 0);
  21161. ASSERT_EQ(static_cast<ssize_t>(smuggled.size()), sent);
  21162. // Step 4: Try to read a second response (should NOT exist after fix)
  21163. std::string second_response;
  21164. for (;;) {
  21165. auto n = recv(sock, buf, sizeof(buf), 0);
  21166. if (n <= 0) break;
  21167. second_response.append(buf, static_cast<size_t>(n));
  21168. }
  21169. // The smuggled request must NOT have been processed
  21170. EXPECT_EQ(0, smuggled_count.load());
  21171. }
  21172. TEST(RequestSmugglingTest, ContentLengthAndTransferEncodingRejected) {
  21173. // RFC 9112 §6.3: A request with both Content-Length and Transfer-Encoding
  21174. // must be rejected with 400 Bad Request.
  21175. Server svr;
  21176. svr.Post("/test", [&](const Request &, Response &res) {
  21177. res.set_content("ok", "text/plain");
  21178. });
  21179. thread t = thread([&] { svr.listen(HOST, PORT); });
  21180. auto se = detail::scope_exit([&] {
  21181. svr.stop();
  21182. t.join();
  21183. ASSERT_FALSE(svr.is_running());
  21184. });
  21185. svr.wait_until_ready();
  21186. // Exact "chunked"
  21187. {
  21188. auto req = "POST /test HTTP/1.1\r\n"
  21189. "Host: localhost\r\n"
  21190. "Content-Length: 5\r\n"
  21191. "Transfer-Encoding: chunked\r\n"
  21192. "Connection: close\r\n"
  21193. "\r\n"
  21194. "hello";
  21195. std::string response;
  21196. ASSERT_TRUE(send_request(1, req, &response));
  21197. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21198. response.substr(0, response.find("\r\n")));
  21199. }
  21200. // Multi-valued Transfer-Encoding (e.g., "gzip, chunked")
  21201. {
  21202. auto req = "POST /test HTTP/1.1\r\n"
  21203. "Host: localhost\r\n"
  21204. "Content-Length: 5\r\n"
  21205. "Transfer-Encoding: gzip, chunked\r\n"
  21206. "Connection: close\r\n"
  21207. "\r\n"
  21208. "hello";
  21209. std::string response;
  21210. ASSERT_TRUE(send_request(1, req, &response));
  21211. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21212. response.substr(0, response.find("\r\n")));
  21213. }
  21214. }
  21215. TEST(RequestSmugglingTest, NonFinalChunkedTransferEncodingRejected) {
  21216. Server svr;
  21217. svr.Post("/test", [&](const Request &, Response &res) {
  21218. res.set_content("ok", "text/plain");
  21219. });
  21220. thread t = thread([&] { svr.listen(HOST, PORT); });
  21221. auto se = detail::scope_exit([&] {
  21222. svr.stop();
  21223. t.join();
  21224. ASSERT_FALSE(svr.is_running());
  21225. });
  21226. svr.wait_until_ready();
  21227. // RFC 9112 6.3: when chunked is not the final transfer coding the body
  21228. // length cannot be determined, so the server must answer 400 and close
  21229. // rather than treat the request as bodyless and leave the body in the
  21230. // socket for the next request to pick up.
  21231. for (const auto &transfer_encoding : {"gzip", "chunked, gzip"}) {
  21232. auto req = std::string("POST /test HTTP/1.1\r\n") + "Host: localhost\r\n" +
  21233. "Transfer-Encoding: " + transfer_encoding + "\r\n" + "\r\n";
  21234. std::string response;
  21235. ASSERT_TRUE(send_request(1, req, &response));
  21236. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21237. response.substr(0, response.find("\r\n")))
  21238. << transfer_encoding;
  21239. }
  21240. // RFC 9110 5.3: the codings may also be split across several
  21241. // Transfer-Encoding lines, which combine in the order they were received.
  21242. // "chunked" followed by "gzip" therefore ends in gzip and must be rejected
  21243. // just like the single-line "chunked, gzip" above.
  21244. {
  21245. auto req = "POST /test HTTP/1.1\r\n"
  21246. "Host: localhost\r\n"
  21247. "Transfer-Encoding: chunked\r\n"
  21248. "Transfer-Encoding: gzip\r\n"
  21249. "\r\n"
  21250. "0\r\n\r\n";
  21251. std::string response;
  21252. ASSERT_TRUE(send_request(1, req, &response));
  21253. EXPECT_EQ("HTTP/1.1 400 Bad Request",
  21254. response.substr(0, response.find("\r\n")));
  21255. }
  21256. // A sequence ending in chunked stays valid.
  21257. auto req = "POST /test HTTP/1.1\r\n"
  21258. "Host: localhost\r\n"
  21259. "Transfer-Encoding: gzip, chunked\r\n"
  21260. "Connection: close\r\n"
  21261. "\r\n"
  21262. "0\r\n\r\n";
  21263. std::string response;
  21264. ASSERT_TRUE(send_request(1, req, &response));
  21265. EXPECT_EQ("HTTP/1.1 200 OK", response.substr(0, response.find("\r\n")));
  21266. // ...including when it is spread over several lines.
  21267. auto split_req = "POST /test HTTP/1.1\r\n"
  21268. "Host: localhost\r\n"
  21269. "Transfer-Encoding: gzip\r\n"
  21270. "Transfer-Encoding: chunked\r\n"
  21271. "Connection: close\r\n"
  21272. "\r\n"
  21273. "0\r\n\r\n";
  21274. std::string split_response;
  21275. ASSERT_TRUE(send_request(1, split_req, &split_response));
  21276. EXPECT_EQ("HTTP/1.1 200 OK",
  21277. split_response.substr(0, split_response.find("\r\n")));
  21278. }
  21279. // Regression for issue #2450: a DELETE without Content-Length on a
  21280. // keep-alive connection must not let the post-response drain consume the
  21281. // next request's bytes.
  21282. TEST(KeepAliveTest, DeleteWithoutContentLengthDoesNotEatNextRequest) {
  21283. Server svr;
  21284. std::atomic<int> delete_count(0);
  21285. svr.Delete("/items/:id", [&](const Request &, Response &res) {
  21286. delete_count++;
  21287. res.status = StatusCode::NoContent_204;
  21288. });
  21289. auto port = svr.bind_to_any_port(HOST);
  21290. thread t = thread([&] { svr.listen_after_bind(); });
  21291. auto se = detail::scope_exit([&] {
  21292. svr.stop();
  21293. t.join();
  21294. });
  21295. svr.wait_until_ready();
  21296. auto error = Error::Success;
  21297. auto sock = detail::create_client_socket(
  21298. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21299. /*connection_timeout_sec=*/2, 0,
  21300. /*read_timeout_sec=*/2, 0,
  21301. /*write_timeout_sec=*/2, 0, std::string(), error);
  21302. ASSERT_NE(INVALID_SOCKET, sock);
  21303. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21304. auto send_request_and_read_response = [&](const std::string &req,
  21305. std::string &out) -> bool {
  21306. auto sent = send(sock, req.data(), req.size(), 0);
  21307. if (sent != static_cast<ssize_t>(req.size())) { return false; }
  21308. char buf[4096];
  21309. for (;;) {
  21310. auto n = recv(sock, buf, sizeof(buf), 0);
  21311. if (n <= 0) { return !out.empty(); }
  21312. out.append(buf, static_cast<size_t>(n));
  21313. if (out.find("\r\n\r\n") != std::string::npos) { return true; }
  21314. }
  21315. };
  21316. std::string req1 = "DELETE /items/1 HTTP/1.1\r\n"
  21317. "Host: localhost\r\n"
  21318. "\r\n";
  21319. std::string resp1;
  21320. ASSERT_TRUE(send_request_and_read_response(req1, resp1));
  21321. EXPECT_NE(std::string::npos, resp1.find("HTTP/1.1 204"));
  21322. std::string req2 = "DELETE /items/2 HTTP/1.1\r\n"
  21323. "Host: localhost\r\n"
  21324. "Connection: close\r\n"
  21325. "\r\n";
  21326. std::string resp2;
  21327. ASSERT_TRUE(send_request_and_read_response(req2, resp2));
  21328. EXPECT_NE(std::string::npos, resp2.find("HTTP/1.1 204"));
  21329. EXPECT_EQ(2, delete_count.load());
  21330. }
  21331. TEST(KeepAliveTest, UnconsumedChunkedBodyIsNotDrainedWhenResponseCloses) {
  21332. Server svr;
  21333. svr.Post("/ingest", [&](const Request &, Response &res,
  21334. const ContentReader &content_reader) {
  21335. auto consumed = content_reader([](const char *, size_t) { return false; });
  21336. EXPECT_FALSE(consumed);
  21337. res.status = StatusCode::Conflict_409;
  21338. res.set_header("Connection", "close");
  21339. });
  21340. auto port = svr.bind_to_any_port(HOST);
  21341. thread t = thread([&] { svr.listen_after_bind(); });
  21342. auto se = detail::scope_exit([&] {
  21343. svr.stop();
  21344. t.join();
  21345. });
  21346. svr.wait_until_ready();
  21347. auto error = Error::Success;
  21348. auto sock = detail::create_client_socket(
  21349. HOST, "", port, AF_UNSPEC, false, false, nullptr,
  21350. /*connection_timeout_sec=*/2, 0,
  21351. /*read_timeout_sec=*/1, 0,
  21352. /*write_timeout_sec=*/2, 0, std::string(), error);
  21353. ASSERT_NE(INVALID_SOCKET, sock);
  21354. auto sock_se = detail::scope_exit([&] { detail::close_socket(sock); });
  21355. std::string request = "POST /ingest HTTP/1.1\r\n"
  21356. "Host: localhost\r\n"
  21357. "Transfer-Encoding: chunked\r\n"
  21358. "\r\n"
  21359. "4\r\n"
  21360. "data\r\n";
  21361. auto sent = send(sock, request.data(), request.size(), 0);
  21362. ASSERT_EQ(static_cast<ssize_t>(request.size()), sent);
  21363. std::string response;
  21364. ssize_t received = 0;
  21365. do {
  21366. char buf[4096];
  21367. received = recv(sock, buf, sizeof(buf), 0);
  21368. if (received > 0) { response.append(buf, static_cast<size_t>(received)); }
  21369. } while (received > 0);
  21370. EXPECT_NE(std::string::npos, response.find("HTTP/1.1 409 Conflict"));
  21371. EXPECT_NE(std::string::npos, response.find("Connection: close"));
  21372. EXPECT_EQ(0, received);
  21373. }
  21374. namespace no_proxy_test {
  21375. // Server bound to 127.0.0.1:<dynamic>, listen thread spawned by listen(),
  21376. // auto-stopped + joined on scope exit. Register handlers via svr() BEFORE
  21377. // calling listen().
  21378. class ScopedServer {
  21379. public:
  21380. ScopedServer() { port_ = svr_.bind_to_any_port("127.0.0.1"); }
  21381. ~ScopedServer() {
  21382. svr_.stop();
  21383. if (th_.joinable()) { th_.join(); }
  21384. }
  21385. Server &svr() { return svr_; }
  21386. int port() const { return port_; }
  21387. void listen() {
  21388. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21389. svr_.wait_until_ready();
  21390. }
  21391. private:
  21392. Server svr_;
  21393. std::thread th_;
  21394. int port_ = 0;
  21395. };
  21396. class ProxyAndTargetServers {
  21397. public:
  21398. ProxyAndTargetServers() {
  21399. proxy_mock_.Get(".*", [this](const Request &req, Response &res) {
  21400. proxy_hits_++;
  21401. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21402. res.set_content("via-proxy", "text/plain");
  21403. });
  21404. target_.Get(".*", [this](const Request &req, Response &res) {
  21405. target_hits_++;
  21406. last_had_proxy_authz_ = req.has_header("Proxy-Authorization");
  21407. res.set_content("direct", "text/plain");
  21408. });
  21409. proxy_port_ = proxy_mock_.bind_to_any_port("127.0.0.1");
  21410. target_port_ = target_.bind_to_any_port("127.0.0.1");
  21411. proxy_thread_ = std::thread([this] { proxy_mock_.listen_after_bind(); });
  21412. target_thread_ = std::thread([this] { target_.listen_after_bind(); });
  21413. proxy_mock_.wait_until_ready();
  21414. target_.wait_until_ready();
  21415. }
  21416. ~ProxyAndTargetServers() {
  21417. proxy_mock_.stop();
  21418. target_.stop();
  21419. if (proxy_thread_.joinable()) { proxy_thread_.join(); }
  21420. if (target_thread_.joinable()) { target_thread_.join(); }
  21421. }
  21422. Server &proxy_mock() { return proxy_mock_; }
  21423. Server &target() { return target_; }
  21424. int proxy_port() const { return proxy_port_; }
  21425. int target_port() const { return target_port_; }
  21426. int proxy_hits() const { return proxy_hits_.load(); }
  21427. int target_hits() const { return target_hits_.load(); }
  21428. bool last_had_proxy_authz() const { return last_had_proxy_authz_.load(); }
  21429. void reset_counters() {
  21430. proxy_hits_ = 0;
  21431. target_hits_ = 0;
  21432. last_had_proxy_authz_ = false;
  21433. }
  21434. private:
  21435. Server proxy_mock_;
  21436. Server target_;
  21437. std::thread proxy_thread_;
  21438. std::thread target_thread_;
  21439. int proxy_port_ = 0;
  21440. int target_port_ = 0;
  21441. std::atomic<int> proxy_hits_{0};
  21442. std::atomic<int> target_hits_{0};
  21443. std::atomic<bool> last_had_proxy_authz_{false};
  21444. };
  21445. inline std::unique_ptr<Client> make_client(const std::string &host,
  21446. ProxyAndTargetServers &s) {
  21447. auto cli = detail::make_unique<Client>(host, s.target_port());
  21448. cli->set_hostname_addr_map({{host, "127.0.0.1"}});
  21449. cli->set_proxy("127.0.0.1", s.proxy_port());
  21450. return cli;
  21451. }
  21452. } // namespace no_proxy_test
  21453. using no_proxy_test::make_client;
  21454. using no_proxy_test::ProxyAndTargetServers;
  21455. TEST(NoProxyTest, ExactHostnameBypasses) {
  21456. ProxyAndTargetServers s;
  21457. auto cli = make_client("example.com", s);
  21458. cli->set_no_proxy({"example.com"});
  21459. auto res = cli->Get("/");
  21460. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21461. EXPECT_EQ(0, s.proxy_hits());
  21462. EXPECT_EQ(1, s.target_hits());
  21463. }
  21464. TEST(NoProxyTest, SubdomainBypasses) {
  21465. ProxyAndTargetServers s;
  21466. auto cli = make_client("foo.example.com", s);
  21467. cli->set_no_proxy({"example.com"});
  21468. auto res = cli->Get("/");
  21469. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21470. EXPECT_EQ(0, s.proxy_hits());
  21471. EXPECT_EQ(1, s.target_hits());
  21472. }
  21473. TEST(NoProxyTest, EvilExampleDoesNotMatchExample) {
  21474. // Regression guard: "evilexample.com" must not be considered a subdomain
  21475. // of "example.com". Without the dot-boundary rule, a naive endsWith
  21476. // check would let traffic bypass the proxy and leak credentials direct
  21477. // to the attacker host.
  21478. ProxyAndTargetServers s;
  21479. auto cli = make_client("evilexample.com", s);
  21480. cli->set_no_proxy({"example.com"});
  21481. auto res = cli->Get("/");
  21482. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21483. EXPECT_GE(s.proxy_hits(), 1);
  21484. EXPECT_EQ(0, s.target_hits());
  21485. }
  21486. TEST(NoProxyTest, ExampleDotEvilDoesNotMatchExample) {
  21487. ProxyAndTargetServers s;
  21488. auto cli = make_client("example.com.evil.com", s);
  21489. cli->set_no_proxy({"example.com"});
  21490. auto res = cli->Get("/");
  21491. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21492. EXPECT_GE(s.proxy_hits(), 1);
  21493. EXPECT_EQ(0, s.target_hits());
  21494. }
  21495. TEST(NoProxyTest, LeadingDotPatternMatchesBareDomain) {
  21496. ProxyAndTargetServers s;
  21497. auto cli = make_client("example.com", s);
  21498. cli->set_no_proxy({".example.com"});
  21499. auto res = cli->Get("/");
  21500. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21501. EXPECT_EQ(0, s.proxy_hits());
  21502. EXPECT_EQ(1, s.target_hits());
  21503. }
  21504. TEST(NoProxyTest, CaseInsensitiveHostname) {
  21505. ProxyAndTargetServers s;
  21506. auto cli = make_client("Example.COM", s);
  21507. cli->set_no_proxy({"EXAMPLE.com"});
  21508. auto res = cli->Get("/");
  21509. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21510. EXPECT_EQ(0, s.proxy_hits());
  21511. EXPECT_EQ(1, s.target_hits());
  21512. }
  21513. TEST(NoProxyTest, TrailingDotIsNormalized) {
  21514. ProxyAndTargetServers s;
  21515. auto cli = make_client("example.com.", s);
  21516. cli->set_no_proxy({"example.com"});
  21517. auto res = cli->Get("/");
  21518. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21519. EXPECT_EQ(0, s.proxy_hits());
  21520. EXPECT_EQ(1, s.target_hits());
  21521. }
  21522. TEST(NoProxyTest, TrailingDotOnEntryIsNormalized) {
  21523. // Trailing dots must be normalized on BOTH sides — host and entry.
  21524. // An implementation that only strips the host-side trailing dot would
  21525. // fail to match host "example.com" against entry "example.com." because
  21526. // a literal substring search would compare 11 chars against 12.
  21527. ProxyAndTargetServers s;
  21528. auto cli = make_client("example.com", s);
  21529. cli->set_no_proxy({"example.com."});
  21530. auto res = cli->Get("/");
  21531. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21532. EXPECT_EQ(0, s.proxy_hits());
  21533. EXPECT_EQ(1, s.target_hits());
  21534. }
  21535. TEST(NoProxyTest, WildcardBypassesEverything) {
  21536. ProxyAndTargetServers s;
  21537. auto cli = make_client("anything.invalid.test", s);
  21538. cli->set_no_proxy({"*"});
  21539. auto res = cli->Get("/");
  21540. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21541. EXPECT_EQ(0, s.proxy_hits());
  21542. EXPECT_EQ(1, s.target_hits());
  21543. }
  21544. TEST(NoProxyTest, IPv4LiteralExactMatch) {
  21545. ProxyAndTargetServers s;
  21546. Client cli("127.0.0.1", s.target_port());
  21547. cli.set_proxy("127.0.0.1", s.proxy_port());
  21548. cli.set_no_proxy({"127.0.0.1"});
  21549. auto res = cli.Get("/");
  21550. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21551. EXPECT_EQ(0, s.proxy_hits());
  21552. EXPECT_EQ(1, s.target_hits());
  21553. }
  21554. TEST(NoProxyTest, IPv6LiteralExactMatchAcrossEquivalentForms) {
  21555. ProxyAndTargetServers s;
  21556. Client cli("0:0:0:0:0:0:0:1", s.target_port());
  21557. cli.set_hostname_addr_map({{"0:0:0:0:0:0:0:1", "127.0.0.1"}});
  21558. cli.set_proxy("127.0.0.1", s.proxy_port());
  21559. cli.set_no_proxy({"::1"});
  21560. auto res = cli.Get("/");
  21561. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21562. EXPECT_EQ(0, s.proxy_hits());
  21563. EXPECT_EQ(1, s.target_hits());
  21564. }
  21565. TEST(NoProxyTest, BareIPv6LiteralMatchesIPv6Cidr) {
  21566. // Regression guard: a bare IPv6 host literal (no surrounding brackets)
  21567. // must still be recognized as IPv6 for CIDR matching. Implementations
  21568. // that detect IPv6 only when the host begins with '[' would parse the
  21569. // host as a hostname and miss the match.
  21570. ProxyAndTargetServers s;
  21571. Client cli("fe80::1", s.target_port());
  21572. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21573. cli.set_proxy("127.0.0.1", s.proxy_port());
  21574. cli.set_no_proxy({"fe80::/10"});
  21575. auto res = cli.Get("/");
  21576. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21577. EXPECT_EQ(0, s.proxy_hits());
  21578. EXPECT_EQ(1, s.target_hits());
  21579. }
  21580. TEST(NoProxyTest, BracketedIPv6EntryAccepted) {
  21581. ProxyAndTargetServers s;
  21582. Client cli("::1", s.target_port());
  21583. cli.set_hostname_addr_map({{"::1", "127.0.0.1"}});
  21584. cli.set_proxy("127.0.0.1", s.proxy_port());
  21585. cli.set_no_proxy({"[::1]"});
  21586. auto res = cli.Get("/");
  21587. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21588. EXPECT_EQ(0, s.proxy_hits());
  21589. EXPECT_EQ(1, s.target_hits());
  21590. }
  21591. TEST(NoProxyTest, BracketedIPv6CidrEntryAccepted) {
  21592. ProxyAndTargetServers s;
  21593. Client cli("fe80::1", s.target_port());
  21594. cli.set_hostname_addr_map({{"fe80::1", "127.0.0.1"}});
  21595. cli.set_proxy("127.0.0.1", s.proxy_port());
  21596. cli.set_no_proxy({"[fe80::]/10"});
  21597. auto res = cli.Get("/");
  21598. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21599. EXPECT_EQ(0, s.proxy_hits());
  21600. EXPECT_EQ(1, s.target_hits());
  21601. }
  21602. TEST(NoProxyTest, IPv4MappedIPv6IsNotCrossMatchedAgainstIPv4Entry) {
  21603. // Policy: keep address families separate. "::ffff:1.2.3.4" must NOT
  21604. // satisfy a NO_PROXY entry of "1.2.3.4". This avoids subtle bypass
  21605. // tricks via address-family conversion.
  21606. ProxyAndTargetServers s;
  21607. Client cli("::ffff:127.0.0.1", s.target_port());
  21608. cli.set_hostname_addr_map({{"::ffff:127.0.0.1", "127.0.0.1"}});
  21609. cli.set_proxy("127.0.0.1", s.proxy_port());
  21610. cli.set_no_proxy({"127.0.0.1"});
  21611. auto res = cli.Get("/");
  21612. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21613. EXPECT_GE(s.proxy_hits(), 1);
  21614. EXPECT_EQ(0, s.target_hits());
  21615. }
  21616. TEST(NoProxyTest, IPv4CidrMatch) {
  21617. ProxyAndTargetServers s;
  21618. Client cli("127.0.0.1", s.target_port());
  21619. cli.set_proxy("127.0.0.1", s.proxy_port());
  21620. cli.set_no_proxy({"127.0.0.0/8"});
  21621. auto res = cli.Get("/");
  21622. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21623. EXPECT_EQ(0, s.proxy_hits());
  21624. EXPECT_EQ(1, s.target_hits());
  21625. }
  21626. TEST(NoProxyTest, IPv4CidrNonMatch) {
  21627. ProxyAndTargetServers s;
  21628. Client cli("127.0.0.1", s.target_port());
  21629. cli.set_proxy("127.0.0.1", s.proxy_port());
  21630. cli.set_no_proxy({"10.0.0.0/8"});
  21631. auto res = cli.Get("/");
  21632. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21633. EXPECT_GE(s.proxy_hits(), 1);
  21634. EXPECT_EQ(0, s.target_hits());
  21635. }
  21636. TEST(NoProxyTest, IPv4CidrPrefixZeroMatchesAll) {
  21637. // Prefix 0 must not trigger the (1u << 32) shift UB. Result: every
  21638. // IPv4 target matches.
  21639. ProxyAndTargetServers s;
  21640. Client cli("127.0.0.1", s.target_port());
  21641. cli.set_proxy("127.0.0.1", s.proxy_port());
  21642. cli.set_no_proxy({"0.0.0.0/0"});
  21643. auto res = cli.Get("/");
  21644. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21645. EXPECT_EQ(0, s.proxy_hits());
  21646. EXPECT_EQ(1, s.target_hits());
  21647. }
  21648. TEST(NoProxyTest, IPv4CidrSingleHostNoSlash) {
  21649. ProxyAndTargetServers s;
  21650. Client cli("127.0.0.1", s.target_port());
  21651. cli.set_proxy("127.0.0.1", s.proxy_port());
  21652. cli.set_no_proxy({"127.0.0.1"});
  21653. auto res = cli.Get("/");
  21654. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21655. EXPECT_EQ(0, s.proxy_hits());
  21656. EXPECT_EQ(1, s.target_hits());
  21657. }
  21658. TEST(NoProxyTest, MalformedCidrPrefixIsDropped) {
  21659. ProxyAndTargetServers s;
  21660. Client cli("127.0.0.1", s.target_port());
  21661. cli.set_proxy("127.0.0.1", s.proxy_port());
  21662. cli.set_no_proxy({"127.0.0.0/33"});
  21663. auto res = cli.Get("/");
  21664. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21665. EXPECT_GE(s.proxy_hits(), 1);
  21666. EXPECT_EQ(0, s.target_hits());
  21667. }
  21668. TEST(NoProxyTest, TrailingSlashCidrIsRejected) {
  21669. // Empty prefix after the slash must be rejected, not silently treated as /32.
  21670. ProxyAndTargetServers s;
  21671. Client cli("127.0.0.1", s.target_port());
  21672. cli.set_proxy("127.0.0.1", s.proxy_port());
  21673. cli.set_no_proxy({"127.0.0.1/"});
  21674. auto res = cli.Get("/");
  21675. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21676. EXPECT_GE(s.proxy_hits(), 1);
  21677. EXPECT_EQ(0, s.target_hits());
  21678. }
  21679. TEST(NoProxyTest, ProxyAuthorizationSuppressedWhenBypassed) {
  21680. ProxyAndTargetServers s;
  21681. auto cli = make_client("internal.corp", s);
  21682. cli->set_proxy_basic_auth("u", "p");
  21683. cli->set_no_proxy({"internal.corp"});
  21684. auto res = cli->Get("/");
  21685. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21686. EXPECT_EQ(1, s.target_hits());
  21687. EXPECT_EQ(0, s.proxy_hits());
  21688. EXPECT_FALSE(s.last_had_proxy_authz())
  21689. << "Proxy-Authorization must not be sent direct to the target";
  21690. }
  21691. TEST(NoProxyTest, ProxyAuthorizationSentWhenNotBypassed) {
  21692. ProxyAndTargetServers s;
  21693. auto cli = make_client("public.example", s);
  21694. cli->set_proxy_basic_auth("u", "p");
  21695. cli->set_no_proxy({"internal.corp"}); // does not match
  21696. auto res = cli->Get("/");
  21697. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21698. EXPECT_GE(s.proxy_hits(), 1);
  21699. EXPECT_TRUE(s.last_had_proxy_authz());
  21700. }
  21701. TEST(NoProxyTest, EmptyNoProxyKeepsProxyOn) {
  21702. ProxyAndTargetServers s;
  21703. auto cli = make_client("anything.test", s);
  21704. auto res = cli->Get("/");
  21705. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21706. EXPECT_GE(s.proxy_hits(), 1);
  21707. EXPECT_EQ(0, s.target_hits());
  21708. }
  21709. TEST(NoProxyTest, PortSpecificEntryRejected) {
  21710. ProxyAndTargetServers s;
  21711. auto cli = make_client("example.com", s);
  21712. cli->set_no_proxy({"example.com:8080"});
  21713. auto res = cli->Get("/");
  21714. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21715. EXPECT_GE(s.proxy_hits(), 1);
  21716. EXPECT_EQ(0, s.target_hits());
  21717. }
  21718. TEST(NoProxyTest, EmptyAndWhitespaceEntriesDropped) {
  21719. ProxyAndTargetServers s;
  21720. auto cli = make_client("anything.test", s);
  21721. cli->set_no_proxy({"", " ", "\t"});
  21722. auto res = cli->Get("/");
  21723. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21724. EXPECT_GE(s.proxy_hits(), 1);
  21725. EXPECT_EQ(0, s.target_hits());
  21726. }
  21727. TEST(NoProxyTest, ValidEntryWithSurroundingWhitespaceStillMatches) {
  21728. // An entry with leading/trailing whitespace must still match — env-style
  21729. // values are commonly pasted with stray spaces and an implementation
  21730. // that feeds the raw token directly to inet_pton would fail to match
  21731. // valid CIDRs because of the spaces.
  21732. ProxyAndTargetServers s;
  21733. Client cli("127.0.0.1", s.target_port());
  21734. cli.set_proxy("127.0.0.1", s.proxy_port());
  21735. cli.set_no_proxy({" 127.0.0.0/8 "});
  21736. auto res = cli.Get("/");
  21737. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21738. EXPECT_EQ(0, s.proxy_hits());
  21739. EXPECT_EQ(1, s.target_hits());
  21740. }
  21741. TEST(NoProxyTest, RedirectToBypassedHostStripsProxyAndProxyAuth) {
  21742. // Analog of GHSA-6hrp-7fq9-3qv2: redirect to a NO_PROXY-matched host must
  21743. // go direct and must NOT carry Proxy-Authorization.
  21744. std::atomic<int> proxy_hits{0};
  21745. std::atomic<int> target_hits{0};
  21746. std::atomic<bool> target_saw_authz{false};
  21747. no_proxy_test::ScopedServer proxy_mock, target;
  21748. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21749. proxy_hits++;
  21750. res.status = 302;
  21751. res.set_header("Location", "http://127.0.0.1:" +
  21752. std::to_string(target.port()) + "/landed");
  21753. });
  21754. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21755. target_hits++;
  21756. if (req.has_header("Proxy-Authorization")) { target_saw_authz = true; }
  21757. res.set_content("direct", "text/plain");
  21758. });
  21759. proxy_mock.listen();
  21760. target.listen();
  21761. Client cli("public.example", target.port());
  21762. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21763. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21764. cli.set_proxy_basic_auth("u", "p");
  21765. cli.set_no_proxy({"127.0.0.1"});
  21766. cli.set_follow_location(true);
  21767. auto res = cli.Get("/redir");
  21768. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21769. EXPECT_GE(proxy_hits.load(), 1);
  21770. EXPECT_GE(target_hits.load(), 1);
  21771. EXPECT_FALSE(target_saw_authz.load());
  21772. }
  21773. #ifdef CPPHTTPLIB_SSL_ENABLED
  21774. TEST(NoProxyTest, BypassedTargetReturning407DoesNotLeakProxyDigestCredentials) {
  21775. // Direct origin replying 407 must not trigger the digest retry; otherwise
  21776. // proxy creds would be sent to the (possibly hostile) origin.
  21777. std::atomic<int> target_hits{0};
  21778. std::atomic<bool> target_saw_proxy_authz{false};
  21779. no_proxy_test::ScopedServer target;
  21780. target.svr().Get(".*", [&](const Request &req, Response &res) {
  21781. target_hits++;
  21782. if (req.has_header("Proxy-Authorization")) {
  21783. target_saw_proxy_authz = true;
  21784. }
  21785. res.status = StatusCode::ProxyAuthenticationRequired_407;
  21786. res.set_header("Proxy-Authenticate", "Digest realm=\"evil\", qop=\"auth\", "
  21787. "nonce=\"abc\", algorithm=MD5");
  21788. });
  21789. target.listen();
  21790. // The proxy address is set to the target's port: the bypass MUST kick in;
  21791. // if it doesn't, the test still routes "via proxy" to the same server and
  21792. // the Proxy-Authorization assertion below catches the leak.
  21793. Client cli("evil.example", target.port());
  21794. cli.set_hostname_addr_map({{"evil.example", "127.0.0.1"}});
  21795. cli.set_proxy("127.0.0.1", target.port());
  21796. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  21797. cli.set_no_proxy({"evil.example"});
  21798. auto res = cli.Get("/x");
  21799. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21800. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  21801. EXPECT_EQ(1, target_hits.load());
  21802. EXPECT_FALSE(target_saw_proxy_authz.load());
  21803. }
  21804. #endif
  21805. TEST(NoProxyTest, MultiHopRedirectThroughBypassedHostKeepsProxy) {
  21806. // A (via proxy) → B (NO_PROXY-matched, direct) → C must re-engage the proxy.
  21807. std::atomic<int> proxy_hits{0};
  21808. std::atomic<int> bypass_hits{0};
  21809. std::atomic<bool> proxy_saw_c_url{false};
  21810. no_proxy_test::ScopedServer proxy_mock, bypass_server;
  21811. proxy_mock.svr().Get(".*", [&](const Request &req, Response &res) {
  21812. proxy_hits++;
  21813. if (req.path.find("/start") != std::string::npos) {
  21814. res.status = 302;
  21815. res.set_header("Location", "http://127.0.0.1:" +
  21816. std::to_string(bypass_server.port()) +
  21817. "/middle");
  21818. return;
  21819. }
  21820. if (req.path.find("/end") != std::string::npos) {
  21821. proxy_saw_c_url = true;
  21822. res.set_content("c-via-proxy", "text/plain");
  21823. return;
  21824. }
  21825. res.set_content("unexpected", "text/plain");
  21826. });
  21827. // public.example's "advertised" port is arbitrary (the request never lands
  21828. // there — it goes through the proxy), but use a dynamic value to stay
  21829. // friendly with sharded parallel runs.
  21830. int public_port = bypass_server.port();
  21831. bypass_server.svr().Get(".*", [&](const Request &, Response &res) {
  21832. bypass_hits++;
  21833. res.status = 302;
  21834. res.set_header("Location", "http://public.example:" +
  21835. std::to_string(public_port) + "/end");
  21836. });
  21837. proxy_mock.listen();
  21838. bypass_server.listen();
  21839. Client cli("public.example", public_port);
  21840. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21841. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21842. cli.set_no_proxy({"127.0.0.1"});
  21843. cli.set_follow_location(true);
  21844. auto res = cli.Get("/start");
  21845. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  21846. EXPECT_EQ(StatusCode::OK_200, res->status);
  21847. EXPECT_EQ("c-via-proxy", res->body);
  21848. EXPECT_GE(proxy_hits.load(), 2);
  21849. EXPECT_GE(bypass_hits.load(), 1);
  21850. EXPECT_TRUE(proxy_saw_c_url.load());
  21851. }
  21852. TEST(NoProxyTest, KeepAliveSocketInvalidatedOnSetNoProxy) {
  21853. // Mid-session set_no_proxy must drop any keep-alive socket so the next
  21854. // request reconnects to the correct endpoint.
  21855. std::atomic<int> proxy_hits{0};
  21856. std::atomic<int> target_hits{0};
  21857. no_proxy_test::ScopedServer proxy_mock, target;
  21858. proxy_mock.svr().Get(".*", [&](const Request &, Response &res) {
  21859. proxy_hits++;
  21860. res.set_content("via-proxy", "text/plain");
  21861. });
  21862. target.svr().Get(".*", [&](const Request &, Response &res) {
  21863. target_hits++;
  21864. res.set_content("direct", "text/plain");
  21865. });
  21866. proxy_mock.listen();
  21867. target.listen();
  21868. Client cli("public.example", target.port());
  21869. cli.set_hostname_addr_map({{"public.example", "127.0.0.1"}});
  21870. cli.set_proxy("127.0.0.1", proxy_mock.port());
  21871. cli.set_keep_alive(true);
  21872. auto res1 = cli.Get("/a");
  21873. ASSERT_TRUE(res1);
  21874. EXPECT_EQ("via-proxy", res1->body);
  21875. EXPECT_EQ(1, proxy_hits.load());
  21876. EXPECT_EQ(0, target_hits.load());
  21877. cli.set_no_proxy({"public.example"});
  21878. auto res2 = cli.Get("/b");
  21879. ASSERT_TRUE(res2);
  21880. EXPECT_EQ("direct", res2->body);
  21881. EXPECT_EQ(1, proxy_hits.load());
  21882. EXPECT_EQ(1, target_hits.load());
  21883. }
  21884. #if defined(CPPHTTPLIB_SSL_ENABLED) && !defined(_WIN32)
  21885. namespace proxy_tunnel_test {
  21886. // SSLServer counterpart to no_proxy_test::ScopedServer.
  21887. class ScopedSSLServer {
  21888. public:
  21889. ScopedSSLServer() : svr_(SERVER_CERT_FILE, SERVER_PRIVATE_KEY_FILE) {
  21890. port_ = svr_.bind_to_any_port("127.0.0.1");
  21891. }
  21892. ~ScopedSSLServer() {
  21893. svr_.stop();
  21894. if (th_.joinable()) { th_.join(); }
  21895. }
  21896. SSLServer &svr() { return svr_; }
  21897. int port() const { return port_; }
  21898. void listen() {
  21899. th_ = std::thread([this] { svr_.listen_after_bind(); });
  21900. svr_.wait_until_ready();
  21901. }
  21902. private:
  21903. SSLServer svr_;
  21904. std::thread th_;
  21905. int port_ = 0;
  21906. };
  21907. // Accepts CONNECT, replies 200, byte-forwards to forward_port.
  21908. class ScopedConnectProxy {
  21909. public:
  21910. explicit ScopedConnectProxy(int forward_port) : forward_port_(forward_port) {
  21911. listen_fd_ = ::socket(AF_INET, SOCK_STREAM, 0);
  21912. if (listen_fd_ < 0) { return; }
  21913. int yes = 1;
  21914. ::setsockopt(listen_fd_, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(yes));
  21915. sockaddr_in a{};
  21916. a.sin_family = AF_INET;
  21917. a.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21918. a.sin_port = 0;
  21919. if (::bind(listen_fd_, reinterpret_cast<sockaddr *>(&a), sizeof(a)) != 0) {
  21920. return;
  21921. }
  21922. socklen_t alen = sizeof(a);
  21923. if (::getsockname(listen_fd_, reinterpret_cast<sockaddr *>(&a), &alen) !=
  21924. 0) {
  21925. return;
  21926. }
  21927. port_ = ntohs(a.sin_port);
  21928. if (::listen(listen_fd_, 1) != 0) { return; }
  21929. th_ = std::thread([this] { run(); });
  21930. }
  21931. ~ScopedConnectProxy() {
  21932. stop_ = true;
  21933. if (listen_fd_ >= 0) {
  21934. ::shutdown(listen_fd_, SHUT_RDWR);
  21935. ::close(listen_fd_);
  21936. }
  21937. if (th_.joinable()) { th_.join(); }
  21938. }
  21939. int port() const { return port_; }
  21940. int connect_hits() const { return connect_hits_.load(); }
  21941. // Head of the last CONNECT request, as the proxy saw it on the wire.
  21942. std::string connect_request() const {
  21943. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21944. return connect_request_;
  21945. }
  21946. private:
  21947. void run() {
  21948. while (!stop_.load()) {
  21949. fd_set rfds;
  21950. FD_ZERO(&rfds);
  21951. FD_SET(listen_fd_, &rfds);
  21952. timeval tv{0, 100 * 1000};
  21953. int sel = ::select(listen_fd_ + 1, &rfds, nullptr, nullptr, &tv);
  21954. if (sel <= 0) { continue; }
  21955. int client_fd = ::accept(listen_fd_, nullptr, nullptr);
  21956. if (client_fd < 0) { continue; }
  21957. std::string req;
  21958. char buf[2048];
  21959. while (req.find("\r\n\r\n") == std::string::npos) {
  21960. ssize_t n = ::recv(client_fd, buf, sizeof(buf), 0);
  21961. if (n <= 0) { break; }
  21962. req.append(buf, static_cast<size_t>(n));
  21963. }
  21964. if (req.compare(0, 7, "CONNECT") != 0) {
  21965. ::close(client_fd);
  21966. continue;
  21967. }
  21968. connect_hits_++;
  21969. {
  21970. std::lock_guard<std::mutex> lock(connect_request_mutex_);
  21971. connect_request_ = req;
  21972. }
  21973. const char *ok = "HTTP/1.1 200 Connection established\r\n\r\n";
  21974. ::send(client_fd, ok, std::strlen(ok), 0);
  21975. int origin_fd = ::socket(AF_INET, SOCK_STREAM, 0);
  21976. sockaddr_in o{};
  21977. o.sin_family = AF_INET;
  21978. o.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
  21979. o.sin_port = htons(static_cast<unsigned short>(forward_port_));
  21980. if (::connect(origin_fd, reinterpret_cast<sockaddr *>(&o), sizeof(o)) !=
  21981. 0) {
  21982. ::close(client_fd);
  21983. ::close(origin_fd);
  21984. continue;
  21985. }
  21986. auto forward = [](int from, int to) {
  21987. char b[8192];
  21988. for (;;) {
  21989. ssize_t n = ::recv(from, b, sizeof(b), 0);
  21990. if (n <= 0) { break; }
  21991. ssize_t off = 0;
  21992. while (off < n) {
  21993. ssize_t s = ::send(to, b + off, static_cast<size_t>(n - off), 0);
  21994. if (s <= 0) {
  21995. off = n;
  21996. break;
  21997. }
  21998. off += s;
  21999. }
  22000. }
  22001. ::shutdown(to, SHUT_WR);
  22002. };
  22003. std::thread t1([&] { forward(client_fd, origin_fd); });
  22004. std::thread t2([&] { forward(origin_fd, client_fd); });
  22005. t1.join();
  22006. t2.join();
  22007. ::close(client_fd);
  22008. ::close(origin_fd);
  22009. }
  22010. }
  22011. int forward_port_ = -1;
  22012. int listen_fd_ = -1;
  22013. int port_ = 0;
  22014. std::thread th_;
  22015. std::atomic<bool> stop_{false};
  22016. std::atomic<int> connect_hits_{0};
  22017. mutable std::mutex connect_request_mutex_;
  22018. std::string connect_request_;
  22019. };
  22020. // Sends one request through the CONNECT proxy to the TLS origin with a
  22021. // credential configured for each hop, and checks that each credential reaches
  22022. // only the hop it was configured for: the proxy's on the CONNECT request, the
  22023. // origin's (every header in origin_headers) on the tunnelled request.
  22024. void CredentialsStayWithTheirHop(
  22025. const std::function<void(SSLClient &)> &set_credentials,
  22026. const std::string &scheme,
  22027. const std::vector<std::string> &origin_headers = {"Authorization"}) {
  22028. std::atomic<int> origin_hits{0};
  22029. std::atomic<bool> origin_saw_proxy_authz{false};
  22030. std::atomic<bool> origin_saw_headers{false};
  22031. ScopedSSLServer origin;
  22032. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22033. origin_hits++;
  22034. origin_saw_proxy_authz = req.has_header("Proxy-Authorization");
  22035. origin_saw_headers =
  22036. std::all_of(origin_headers.begin(), origin_headers.end(),
  22037. [&](const std::string &h) { return req.has_header(h); });
  22038. res.set_content("ok", "text/plain");
  22039. });
  22040. origin.listen();
  22041. ScopedConnectProxy proxy(origin.port());
  22042. ASSERT_NE(0, proxy.port());
  22043. // Pinned to 127.0.0.1 for the same reason as the test below.
  22044. SSLClient cli("127.0.0.1", origin.port());
  22045. cli.enable_server_certificate_verification(false);
  22046. cli.set_proxy("127.0.0.1", proxy.port());
  22047. set_credentials(cli);
  22048. auto res = cli.Get("/x");
  22049. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22050. EXPECT_EQ(StatusCode::OK_200, res->status);
  22051. EXPECT_EQ(1, origin_hits.load());
  22052. EXPECT_EQ(1, proxy.connect_hits());
  22053. EXPECT_TRUE(origin_saw_headers.load());
  22054. EXPECT_FALSE(origin_saw_proxy_authz.load())
  22055. << "Proxy-Authorization must not be sent inside the tunnel";
  22056. auto connect_req = proxy.connect_request();
  22057. EXPECT_NE(std::string::npos,
  22058. connect_req.find("\r\nProxy-Authorization: " + scheme + " "));
  22059. for (const auto &h : origin_headers) {
  22060. EXPECT_EQ(std::string::npos, connect_req.find("\r\n" + h + ": "))
  22061. << h << " must not be sent to the proxy on CONNECT";
  22062. }
  22063. }
  22064. } // namespace proxy_tunnel_test
  22065. TEST(ProxyTunnelTest, BasicCredentialsStayWithTheirHop) {
  22066. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22067. [](SSLClient &cli) {
  22068. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22069. cli.set_basic_auth("origin-user", "origin-pass");
  22070. },
  22071. "Basic");
  22072. }
  22073. TEST(ProxyTunnelTest, BearerCredentialsStayWithTheirHop) {
  22074. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22075. [](SSLClient &cli) {
  22076. cli.set_proxy_bearer_token_auth("proxy-token");
  22077. cli.set_bearer_token_auth("origin-token");
  22078. },
  22079. "Bearer");
  22080. }
  22081. TEST(ProxyTunnelTest, DefaultHeadersStayOffConnect) {
  22082. proxy_tunnel_test::CredentialsStayWithTheirHop(
  22083. [](SSLClient &cli) {
  22084. cli.set_proxy_basic_auth("proxy-user", "proxy-pass");
  22085. cli.set_default_headers({{"Authorization", "Bearer origin-token"},
  22086. {"Cookie", "sid=origin-session"},
  22087. {"X-Api-Key", "origin-key"}});
  22088. },
  22089. "Basic", {"Authorization", "Cookie", "X-Api-Key"});
  22090. }
  22091. TEST(ProxyTunnelTest, OriginReturning407InsideTunnelDoesNotLeakProxyDigest) {
  22092. // Origin inside a CONNECT tunnel replying 407 must not trigger the digest
  22093. // retry; otherwise proxy creds would be sent to the origin.
  22094. std::atomic<int> origin_hits{0};
  22095. std::atomic<bool> origin_saw_proxy_authz{false};
  22096. proxy_tunnel_test::ScopedSSLServer origin;
  22097. origin.svr().Get(".*", [&](const Request &req, Response &res) {
  22098. origin_hits++;
  22099. if (req.has_header("Proxy-Authorization")) {
  22100. origin_saw_proxy_authz = true;
  22101. }
  22102. res.status = StatusCode::ProxyAuthenticationRequired_407;
  22103. res.set_header("Proxy-Authenticate",
  22104. "Digest realm=\"evil\", qop=\"auth\", nonce=\"abc\", "
  22105. "algorithm=MD5");
  22106. });
  22107. origin.listen();
  22108. proxy_tunnel_test::ScopedConnectProxy proxy(origin.port());
  22109. ASSERT_NE(0, proxy.port());
  22110. // Pin to 127.0.0.1: the proxy listens on 127.0.0.1 only, while "localhost"
  22111. // may resolve to ::1 first. A concurrent test (e.g. another gtest shard)
  22112. // holding ::1 with the same ephemeral port number would hijack the CONNECT
  22113. // and answer with its own status, making this test flaky.
  22114. SSLClient cli("127.0.0.1", origin.port());
  22115. cli.enable_server_certificate_verification(false);
  22116. cli.set_proxy("127.0.0.1", proxy.port());
  22117. cli.set_proxy_digest_auth("proxy-user", "proxy-pass");
  22118. auto res = cli.Get("/x");
  22119. ASSERT_TRUE(res) << "Error: " << to_string(res.error());
  22120. EXPECT_EQ(StatusCode::ProxyAuthenticationRequired_407, res->status);
  22121. EXPECT_EQ(1, origin_hits.load());
  22122. EXPECT_FALSE(origin_saw_proxy_authz.load());
  22123. EXPECT_EQ(1, proxy.connect_hits());
  22124. }
  22125. #endif